SlideShare a Scribd company logo
Python Programming
Workshop
Pramote Kuacharoen
Topics
 Expressions, operators, precedence, control flows, functions
 Input/output
 List
 Classes and Objects
2
The Python Interpreter
 Python is an interpreted language
 Commands are executed through the Python interpreter
 A programmer defines a series of commands in advance and saves those
commands in a text file known as source code or a script.
 For Python, source code is conventionally stored in a file named with the .py
suffix (e.g., demo.py)
3
Writing a Simple Program
 Algorithm for calculating the area of a square
 Obtain the width from the user
 Computer the area by applying the following formula
 𝒂𝒓𝒆𝒂 = 𝒘𝒊𝒅𝒕𝒉 ∗ 𝒘𝒊𝒅𝒕𝒉
 Display the result
4
Reading Input from the Console
 Use the input function to obtain a string
 variable = input(‘Enter width : ’)
 Use the eval function to evaluate expression
 variable = eval(string_variable)
 Combination
 width = eval(input(‘Enter width : ’))
5
Calculating Square Area
width = eval(input('Enter width : '))
area = width * width
print('Area is ', area)
6
Identifiers
 Identifiers in Python are case-sensitive, so temperature and Temperature are
distinct names.
 Identifiers can be composed of almost any combination of letters, numerals,
and underscore characters.
 An identifier cannot begin with a numeral and that there are 33 specially
reserved words that cannot be used as identifiers:
7
Types
 Python is a dynamically typed language, as there is no advance declaration
associating an identifier with a particular data type.
 An identifier can be associated with any type of object, and it can later be
reassigned to another object of the same (or different) type.
 Although an identifier has no declared type, the object to which it refers has
a definite type. In our first example, the characters 98.6 are recognized as a
floating-point literal, and thus the identifier temperature is associated with
an instance of the float class having that value.
8
Numerical Data Types ad Numeric
Operators
 integer: e.g., 3, 4
 float: e.g., 3.0, 4.0
Name Meaning Example Result
+ Addition 34 + 1 35
- Subtraction 34.0 – 0.1 33.9
* Multiplication 300 * 30 9000
/ Float Division 1 / 2 0.5
// Integer Division 1 // 2 0
** Exponentiation 4 ** 0.5 2.0
% Remainder 20 % 3 2
9
Boolean Data Types
 Often in a program you need to compare two values, such as whether i is
greater than j
 There are six comparison operators (also known as relational operators) that
can be used to compare two values
 The result of the comparison is a Boolean value: true or false
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
10
String
 Sequence of characters that is treated as a single item
 Written as a sequence of characters surrounded by either single quotes (') or
double quotes (")
 Position or index of a character in a string
 Identified with one of the numbers 0, 1, 2, 3, . . . .
11
List
12
list1 = list() # Create an empty list
list2 = list([2, 3, 4]) # Create a list with elements 2, 3, 4
list3 = list(["red", "green", "blue"]) # Create a list with strings
list4 = list(range(3, 6)) # Create a list with elements 3, 4, 5
list5 = list("abcd") # Create a list with characters a, b, c
list1 = [] # Same as list()
list2 = [2, 3, 4] # Same as list([2, 3, 4])
list3 = ["red", "green"] # Same as list(["red", "green"])
append(x: object): None
insert(index: int, x: object): None
remove(x: object): None
index(x: object): int
count(x: object): int
sort(): None
reverse(): None
extend(l: list): None
pop([i]): object
List Is a Sequence Type
13
Operation Description
x in s True if element x is in sequence s
x not in s True if element x is not in sequence s
s1 + s2 Concatenates two sequences s1 and s2
s * n, n * s n copies of sequence s concatenated
s[i] ith element in sequence s
s[i : j] Slice of sequence s from index i to j - 1
len(s) Length of sequence s, i.e., the number of elements in s
min(s) Smallest element in sequence s
max(s) Largest element in sequence s
sum(s) Sum of all numbers in sequence s
for loop Traverses elements from left to right in a for loop
<, <=, >, >=, ==, != Compares two sequences
if Statement
14
if width > 0:
area = width * width
if Boolean-expression:
statement(s)
if-else Statement
15
if width > 0:
area = width * width
else:
print(‘width must be positive’)
if Boolean-expression:
statement(s) for the true case
else:
statement(s) for the false case
Multiple Alternative for if Statements
16
if score >= 90.0:
grade = 'A'
elif score >= 80.0:
grade = 'B'
elif score >= 70.0:
grade = 'C'
elif score >= 60.0:
grade = 'D'
else:
grade = 'F'
if score >= 90.0:
grade = 'A'
else:
if score >= 80.0:
grade = 'B'
else:
if score >= 70.0:
grade = 'C'
else:
if score >= 60.0:
grade = 'D'
else:
grade = 'F'
Logical Operators
17
Operator Description
not Logical negation
and Logical conjunction
or Logical disjunction
(year % 4 == 0 and year % 100 != 0) or year % 400 == 0)
A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400.
Conditional Operator
18
y = 1 if x > 0 else -1if x > 0:
y = 1
else:
y = -1
if num % 2 == 0:
print(str(num) + “is even”)
else:
print(str(num) + “is odd”);
print("number is even" if (number % 2 == 0)
else "number is odd")
Operator Precedence
 +, - unary
 **
 not
 *, /, //, %
 +, -
 <, <=, >, >=
 ==, !=
 and
 or
 =, +=, -=, *=, /=, //=, %= (Assignment operator)
19
Loops
20
for i in range(1, 6):
print (i)
num = 1
while num <= 5:
print(num)
num += 1
while conditions:
indented block of statements
for var in sequence:
indented block of statements
Functions
 Functions can be used to define reusable code and organize and simplify code
21
def sum_range(a, b):
result = 0
for i in range(a, b+1):
result += i
return result
def main():
print('Sum from 1 to 10 is ', sum_range(1, 10));
print('Sum from 50 to 100 is ', sum_range(50, 100));
main()
def function_name(list of parameters):
# Function body
Reading Input from Text Files
22
continent = input('Enter the name of a continent : ')
continent = continent.title()
if continent != 'Antarctica':
infile = open('UN.txt', 'r')
for line in infile:
data = line.split(',')
if data[1] == continent:
print(data[0])
else:
print('There are not countries in Antarctica.')
infile = open(‘Filename’, ‘r’)
List Comprehension
23
list1 = [x for x in range(5)]
[0, 1, 2, 3, 4]
line = input('Enter series of numbers : ')
text_numbers = line.split(' ')
numbers = [eval(num) for num in text_numbers]
Objects and Classes
 Object-oriented programming enables you to develop large-scale software
and GUIs effectively.
24
class Rectangle:
def __init__(self, width = 1, height = 2):
self._width = width
self._height = height
def area(self):
return self._width * self._height
def perimeter(self):
return 2 * (self._width * self._height)
def main():
r1 = Rectangle(10, 20)
print('The area of the rectangle is : ', r1.area())
print('The perimeter of the rectangle is : ', r1.perimeter())
main()
class ClassName:
initializer
methods

More Related Content

PDF
ARRAYS
PPTX
USER DEFINE FUNCTIONS IN PYTHON
PPTX
INTRODUCTION TO FUNCTIONS IN PYTHON
PPTX
OPERATOR IN PYTHON-PART2
PPTX
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
PDF
Python unit 2 as per Anna university syllabus
ARRAYS
USER DEFINE FUNCTIONS IN PYTHON
INTRODUCTION TO FUNCTIONS IN PYTHON
OPERATOR IN PYTHON-PART2
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
Python unit 2 as per Anna university syllabus

What's hot (20)

PPT
PPTX
Arrays in C language
PPT
Lecture 15 - Array
PPTX
DATA TYPE IN PYTHON
PPTX
function, storage class and array and strings
PPTX
Memory management of datatypes
PPTX
OPERATOR IN PYTHON-PART1
PPTX
Unit2 input output
PDF
Python-02| Input, Output & Import
PPTX
FLOW OF CONTROL-NESTED IFS IN PYTHON
PPTX
Array, string and pointer
PDF
Control statements-Computer programming
PDF
Python Unit 3 - Control Flow and Functions
PDF
Unit 2
PPTX
C++ lecture 04
PPT
Arrays
PPT
Functions and pointers_unit_4
PPTX
Programming in c Arrays
Arrays in C language
Lecture 15 - Array
DATA TYPE IN PYTHON
function, storage class and array and strings
Memory management of datatypes
OPERATOR IN PYTHON-PART1
Unit2 input output
Python-02| Input, Output & Import
FLOW OF CONTROL-NESTED IFS IN PYTHON
Array, string and pointer
Control statements-Computer programming
Python Unit 3 - Control Flow and Functions
Unit 2
C++ lecture 04
Arrays
Functions and pointers_unit_4
Programming in c Arrays
Ad

Similar to Python programming workshop (20)

PDF
Python cheatsheat.pdf
PDF
Introduction To Programming with Python
PPT
python language programming presentation
PPTX
python_computer engineering_semester_computer_language.pptx
PPT
python fundamental for beginner course .ppt
PPTX
Learn more about the concepts of Data Types in Python
PDF
Introduction to Python
PPTX
Introduction to python programming 1
PPTX
Python Workshop - Learn Python the Hard Way
PPTX
Python
PDF
Python Part 1
PPT
Introduction to Python Language and Data Types
PPTX
An Introduction : Python
PDF
Introduction to Python Programming | InsideAIML
PDF
computer science CLASS 11 AND 12 SYLLABUS.pdf
PDF
python notes.pdf
PDF
pythonQuick.pdf
PDF
python 34💭.pdf
PPTX
PDF
Introduction to python
Python cheatsheat.pdf
Introduction To Programming with Python
python language programming presentation
python_computer engineering_semester_computer_language.pptx
python fundamental for beginner course .ppt
Learn more about the concepts of Data Types in Python
Introduction to Python
Introduction to python programming 1
Python Workshop - Learn Python the Hard Way
Python
Python Part 1
Introduction to Python Language and Data Types
An Introduction : Python
Introduction to Python Programming | InsideAIML
computer science CLASS 11 AND 12 SYLLABUS.pdf
python notes.pdf
pythonQuick.pdf
python 34💭.pdf
Introduction to python
Ad

More from BAINIDA (20)

PDF
ดนตรีของพระเจ้าแผ่นดิน อานนท์ ศักดิ์วรวิชญ์ สุรพงษ์ บ้านไกรทอง หอประชุมวปอ 7...
PDF
Mixed methods in social and behavioral sciences
PDF
Advanced quantitative research methods in political science and pa
PPTX
Latest thailand election2019report
PDF
Data science in medicine
PPTX
Nursing data science
PDF
Financial time series analysis with R@the 3rd NIDA BADS conference by Asst. p...
PDF
Statistics and big data for justice and fairness
PDF
Data science and big data for business and industrial application
PDF
Update trend: Free digital marketing metrics for start-up
PDF
Advent of ds and stat adjustment
PPTX
เมื่อ Data Science เข้ามา สถิติศาสตร์จะปรับตัวอย่างไร
PPTX
Data visualization. map
PPTX
Dark data by Worapol Alex Pongpech
PDF
Deepcut Thai word Segmentation @ NIDA
PPTX
Professionals and wanna be in Business Analytics and Data Science
PDF
Deep learning and image analytics using Python by Dr Sanparit
PDF
Visualizing for impact final
PDF
Second prize business plan @ the First NIDA business analytics and data scien...
PDF
Second prize data analysis @ the First NIDA business analytics and data scie...
ดนตรีของพระเจ้าแผ่นดิน อานนท์ ศักดิ์วรวิชญ์ สุรพงษ์ บ้านไกรทอง หอประชุมวปอ 7...
Mixed methods in social and behavioral sciences
Advanced quantitative research methods in political science and pa
Latest thailand election2019report
Data science in medicine
Nursing data science
Financial time series analysis with R@the 3rd NIDA BADS conference by Asst. p...
Statistics and big data for justice and fairness
Data science and big data for business and industrial application
Update trend: Free digital marketing metrics for start-up
Advent of ds and stat adjustment
เมื่อ Data Science เข้ามา สถิติศาสตร์จะปรับตัวอย่างไร
Data visualization. map
Dark data by Worapol Alex Pongpech
Deepcut Thai word Segmentation @ NIDA
Professionals and wanna be in Business Analytics and Data Science
Deep learning and image analytics using Python by Dr Sanparit
Visualizing for impact final
Second prize business plan @ the First NIDA business analytics and data scien...
Second prize data analysis @ the First NIDA business analytics and data scie...

Recently uploaded (20)

PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Business Ethics Teaching Materials for college
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Pre independence Education in Inndia.pdf
PDF
Complications of Minimal Access Surgery at WLH
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Institutional Correction lecture only . . .
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
O5-L3 Freight Transport Ops (International) V1.pdf
O7-L3 Supply Chain Operations - ICLT Program
Abdominal Access Techniques with Prof. Dr. R K Mishra
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Business Ethics Teaching Materials for college
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Pre independence Education in Inndia.pdf
Complications of Minimal Access Surgery at WLH
VCE English Exam - Section C Student Revision Booklet
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
human mycosis Human fungal infections are called human mycosis..pptx
Institutional Correction lecture only . . .
Renaissance Architecture: A Journey from Faith to Humanism
2.FourierTransform-ShortQuestionswithAnswers.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Pharma ospi slides which help in ospi learning
Week 4 Term 3 Study Techniques revisited.pptx
PPH.pptx obstetrics and gynecology in nursing

Python programming workshop

  • 2. Topics  Expressions, operators, precedence, control flows, functions  Input/output  List  Classes and Objects 2
  • 3. The Python Interpreter  Python is an interpreted language  Commands are executed through the Python interpreter  A programmer defines a series of commands in advance and saves those commands in a text file known as source code or a script.  For Python, source code is conventionally stored in a file named with the .py suffix (e.g., demo.py) 3
  • 4. Writing a Simple Program  Algorithm for calculating the area of a square  Obtain the width from the user  Computer the area by applying the following formula  𝒂𝒓𝒆𝒂 = 𝒘𝒊𝒅𝒕𝒉 ∗ 𝒘𝒊𝒅𝒕𝒉  Display the result 4
  • 5. Reading Input from the Console  Use the input function to obtain a string  variable = input(‘Enter width : ’)  Use the eval function to evaluate expression  variable = eval(string_variable)  Combination  width = eval(input(‘Enter width : ’)) 5
  • 6. Calculating Square Area width = eval(input('Enter width : ')) area = width * width print('Area is ', area) 6
  • 7. Identifiers  Identifiers in Python are case-sensitive, so temperature and Temperature are distinct names.  Identifiers can be composed of almost any combination of letters, numerals, and underscore characters.  An identifier cannot begin with a numeral and that there are 33 specially reserved words that cannot be used as identifiers: 7
  • 8. Types  Python is a dynamically typed language, as there is no advance declaration associating an identifier with a particular data type.  An identifier can be associated with any type of object, and it can later be reassigned to another object of the same (or different) type.  Although an identifier has no declared type, the object to which it refers has a definite type. In our first example, the characters 98.6 are recognized as a floating-point literal, and thus the identifier temperature is associated with an instance of the float class having that value. 8
  • 9. Numerical Data Types ad Numeric Operators  integer: e.g., 3, 4  float: e.g., 3.0, 4.0 Name Meaning Example Result + Addition 34 + 1 35 - Subtraction 34.0 – 0.1 33.9 * Multiplication 300 * 30 9000 / Float Division 1 / 2 0.5 // Integer Division 1 // 2 0 ** Exponentiation 4 ** 0.5 2.0 % Remainder 20 % 3 2 9
  • 10. Boolean Data Types  Often in a program you need to compare two values, such as whether i is greater than j  There are six comparison operators (also known as relational operators) that can be used to compare two values  The result of the comparison is a Boolean value: true or false Operator Name < less than <= less than or equal to > greater than >= greater than or equal to == equal to != not equal to 10
  • 11. String  Sequence of characters that is treated as a single item  Written as a sequence of characters surrounded by either single quotes (') or double quotes (")  Position or index of a character in a string  Identified with one of the numbers 0, 1, 2, 3, . . . . 11
  • 12. List 12 list1 = list() # Create an empty list list2 = list([2, 3, 4]) # Create a list with elements 2, 3, 4 list3 = list(["red", "green", "blue"]) # Create a list with strings list4 = list(range(3, 6)) # Create a list with elements 3, 4, 5 list5 = list("abcd") # Create a list with characters a, b, c list1 = [] # Same as list() list2 = [2, 3, 4] # Same as list([2, 3, 4]) list3 = ["red", "green"] # Same as list(["red", "green"]) append(x: object): None insert(index: int, x: object): None remove(x: object): None index(x: object): int count(x: object): int sort(): None reverse(): None extend(l: list): None pop([i]): object
  • 13. List Is a Sequence Type 13 Operation Description x in s True if element x is in sequence s x not in s True if element x is not in sequence s s1 + s2 Concatenates two sequences s1 and s2 s * n, n * s n copies of sequence s concatenated s[i] ith element in sequence s s[i : j] Slice of sequence s from index i to j - 1 len(s) Length of sequence s, i.e., the number of elements in s min(s) Smallest element in sequence s max(s) Largest element in sequence s sum(s) Sum of all numbers in sequence s for loop Traverses elements from left to right in a for loop <, <=, >, >=, ==, != Compares two sequences
  • 14. if Statement 14 if width > 0: area = width * width if Boolean-expression: statement(s)
  • 15. if-else Statement 15 if width > 0: area = width * width else: print(‘width must be positive’) if Boolean-expression: statement(s) for the true case else: statement(s) for the false case
  • 16. Multiple Alternative for if Statements 16 if score >= 90.0: grade = 'A' elif score >= 80.0: grade = 'B' elif score >= 70.0: grade = 'C' elif score >= 60.0: grade = 'D' else: grade = 'F' if score >= 90.0: grade = 'A' else: if score >= 80.0: grade = 'B' else: if score >= 70.0: grade = 'C' else: if score >= 60.0: grade = 'D' else: grade = 'F'
  • 17. Logical Operators 17 Operator Description not Logical negation and Logical conjunction or Logical disjunction (year % 4 == 0 and year % 100 != 0) or year % 400 == 0) A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400.
  • 18. Conditional Operator 18 y = 1 if x > 0 else -1if x > 0: y = 1 else: y = -1 if num % 2 == 0: print(str(num) + “is even”) else: print(str(num) + “is odd”); print("number is even" if (number % 2 == 0) else "number is odd")
  • 19. Operator Precedence  +, - unary  **  not  *, /, //, %  +, -  <, <=, >, >=  ==, !=  and  or  =, +=, -=, *=, /=, //=, %= (Assignment operator) 19
  • 20. Loops 20 for i in range(1, 6): print (i) num = 1 while num <= 5: print(num) num += 1 while conditions: indented block of statements for var in sequence: indented block of statements
  • 21. Functions  Functions can be used to define reusable code and organize and simplify code 21 def sum_range(a, b): result = 0 for i in range(a, b+1): result += i return result def main(): print('Sum from 1 to 10 is ', sum_range(1, 10)); print('Sum from 50 to 100 is ', sum_range(50, 100)); main() def function_name(list of parameters): # Function body
  • 22. Reading Input from Text Files 22 continent = input('Enter the name of a continent : ') continent = continent.title() if continent != 'Antarctica': infile = open('UN.txt', 'r') for line in infile: data = line.split(',') if data[1] == continent: print(data[0]) else: print('There are not countries in Antarctica.') infile = open(‘Filename’, ‘r’)
  • 23. List Comprehension 23 list1 = [x for x in range(5)] [0, 1, 2, 3, 4] line = input('Enter series of numbers : ') text_numbers = line.split(' ') numbers = [eval(num) for num in text_numbers]
  • 24. Objects and Classes  Object-oriented programming enables you to develop large-scale software and GUIs effectively. 24 class Rectangle: def __init__(self, width = 1, height = 2): self._width = width self._height = height def area(self): return self._width * self._height def perimeter(self): return 2 * (self._width * self._height) def main(): r1 = Rectangle(10, 20) print('The area of the rectangle is : ', r1.area()) print('The perimeter of the rectangle is : ', r1.perimeter()) main() class ClassName: initializer methods