Python
Python
com – MATERIALS
Audio of all lectures: https://itunes.apple.com/us/podcast/python-for-everybody-audio-py4e/
id1214665693
You can also use the "Python Playground" to experiment with writing your own Python
applications using only your browser.
We recommend that you use the Brackets text editor for this course. We prefer it because it
works the same on Windows, Macintosh, and Linux.
For other text editor options, we have a page detailing other options.
Why PROGRAM ?
We have to speak its language
Syntax error is when the computer program “says” to itself they ‘don’t know” what to do (run)
next
Cannot use reserved words as for variable names, identifiers (false, none, true, del, if,…)
Sentences or lines
x = 2 assignment statement
x = x + 2 assignment with expression
print (x) Print function
Conditional Steps
*Repeated Steps
Loops (repeated steps) have iteration ( the repetition of a process - su lap lai) variables that
change each time through a loop As soon as soon as the statements become false then the
loop exit
Ex:
Program:
n=5
while n >0 :
print (n)
n=n–1
print(‘Blastoff!’)
Output:
5
4
3
2
1
Blastoff!
Sequential code is not being indented Just go down khong co thut vao` dau dong`
3 patterns: Sequential code, conditional code, repeated code
Modules 4: Experssion
Fixed values: such as numbers, letters and strings are called constants cuz their value does not
change
String constant: use single quotes (‘) or double quotes (“)
Numeric constant: >> print (123) – 123
Variables: named place in the memory where a programmer can store data and later using
variable “name”
You can change the contents of a variable in a later statement
x= 12.2
y = 14
x =100
The right side is an expression. Once the expression is evaluated, the result is placed in (assigned
to) the variable on the left side (i.e., x).
x = 3.9 * x * (1 – x)
Các dấu phép tính như EXCEL, nhưng dấu MŨ là **, phép chia lấy SỐ DƯ là %
Ex: >>> print (4 ** 3)
64
>>> jj = 23
>>> kk = jj % 5
>>> print (kk)
3
Order of evaluation
- When we string operators together – Python must know which one to do first
- This is called “ operator precedence ”
- Which operator “takes precedence”over the others ?
Ex: x = 1+ (2 * 3) – (4 / (5 ** 6))
Type Matters
- Python knows what “type” everything is
- Some operations are prohibited
- You cannot “add 1” to a string
- We can ask Python what type something is by using type () function là hàm để define lệnh
đó là gì ( chữ, số ??? )
Type Conversions
- When you put an integer and floating point in an expression, the integer is implicity converted
to a float
- You can control this with the built-in functions int() and float()
- Can use int() and float() to convert between strings and integers
- Will get an error if the string does not contain numeric characters
Ex: x = “123”
>>> type (x)
< class ‘str’>
>>> print (x +1)
Traceback … (Error)
>>> y = int (x)
>>> type (y)
<class ‘int’>
>>> print (y +1)
124
User Input
- We can instruct Python to pause and read data from the user using the input() function
- The input () function returns a string
Ex:
nam = input (‘ Who are you?’)
Print (‘Welcome’, nam)
User # trước mỗi câu lệnh đễ mô tả mình làm gì tiếp theo hoặc giải thích đoạn code ở dưới
Sẽ không chạy đoạn code đó mà hiển thị 1 dòng # ….
- If we want to read a number from the user, we must convert it from a string to a number using a
type conversion function
- Later we will deal with bad input data
- If we want to read a number from the user, we must convert it from a string to a number using a
type conversion function
x=5
if x < 10:
print (‘Smaller’)
if x > 20:
print (‘Bigger’)
print (‘Finis’)
Comparison Operators
- Boolean expressions ask a question and produce a Yes or No result which we use to control
program flow
- Boolean expressions using comparison operators evaluate to True / False or Yes/ No
- Comparison operators look at variable but do not change the variables
Mỗi dòng lệnh thụt vô (if, for) đều kết thúc bởi 1 dòng thụt ra
Ex:
x=5
if x >2 :
print (‘Bigger than 2’)
print (‘Still Bigger’)
print (‘Done with 2’)
Nested Decisions
x = 42
if x > 1:
print (‘More than one’)
if x < 100:
print(‘Less than 100’)
print (‘All done’)
x=4
if x >2:
print (‘bigger’)
else:
print (‘smaller’)
print (‘All done’)
If x < 2:
Print (‘small’)
Elif x < 10:
Print (‘Medium’)
Else :
Print (‘Large’)
Print (‘All done’)
Không nhất thiết cần có Else, nếu không có thì sẽ chạy tới kết quả cuối All done
Nhưng có thể có nhiều Elif chồng lê nnhau:
Ex:
if x <2:
Print (‘Small’)
Elif x <10:
Print (‘Medium’)
Elif x <20:
Print (‘Big’)
Elif x <40:
Print (‘Large’)
Elif x <100:
Print (‘Huge’)
Else:
Print (‘Ginormous’)
Try – Except
- You surround a dangerous section of code with try and except
- If the code in the try works – the except is skipped
- If the code in the try fails – it jumps to the except section 5
Thay vì bị lỗi Hiện traceback thì chạy qua except luôn
Ex:
astr = ‘Hello Bob’
try:
istr = istr (astr)
except:
istr = -1
2 outcome la:
First -1
Second 123
When the first conversion fails it just drops into the except: clause and the program
continues
When the second conversion succeeds – it skips the except: clause and the program continues.
Once it gets to the except block It go down below to the next line, not comeback !
Sample try/except
if ival > 0:
print (‘Nice work’)
else:
print (‘Not a number’)
GIẢ SỬ 2 file khác nhau:
FILE 1: $ python3 trynum.py sẽ ra kết quả
Enter a number: 42
Nice wokr
def thing():
print (‘Hello’)
print (‘Fun’)
thing ()
print (‘Zip’)
thing ()
Output:
Hello có từ lúc câu lệnh dòng 3: thing()
Fun có từ lúc câu lệnh dòng 3: thing()
Zip
Hello
Fun
Max Function
A function is some stored code that we use. A function takes some input and produces an output.
‘w’ ( a string)
Type Conversions
When you put an integer and floating point in an expression, the integer is implicity converted to
a float
You can control this with built- in function int() and float ()
Ex: ví dụ hàm là:
x = ‘123’
print (x +1) sẽ không đc vì x đang là string
đổi y = int(x)
Print (y +1)
124
Hàm type là để define variable là int hay float
We create new function using the def keyword followed by optional parameters in parentheses
We indent the body of the function
This defines the function but does not execute the body of the function
Ex:
x=5
print (‘Hello’)
def print_lyrics():
print (‘I’m a lumberjack’)
print (‘I sleep all night’)
print (‘Yo)
x=x+2
print (x)
- Outcome sẽ là Hello
Yo
7
Arguments
An argument is a value we pass into the function as its input when we call the function
We use arguments so we can direct the function to do different kinds of work when we call it at
different times
A parameter is a variable which we use in the function definition. It is a “handle” that allows the
code in the function to access the arguments for a particular function invocation
Ex:
def greet(lang):
if lang == ‘es’:
print (‘Hola’)
if lang == ‘fr’:
print (‘Bonjour’)
else:
print (‘Hello’)
greet (‘en’)
Hello
greet (‘es’)
Hola
greet (‘fr’)
Bonjour
Return Values
Often a function will take its arguments, do some computation, and return a value to be used as
the value of the function call in the calling expression. The return keyword is used for this.
Output:
Hello Glenn
Hello Sally
Ex:
Def addtwo (a,b):
added = a +b
return added
x = addtwo (3,5)
print (x)
8 (out come)
Loops ( repeated steps ) have iteration variables that change each time through a loop. Often
these iteration variables go through a sequence of numbers
Program:
n=5
while n > 0:
print (n)
n = n -1
print (‘Blastoff!’)
print (n)
Output: Ở đây hàm while thì nó sẽ tự quay lại check n = n -1 > 0 không và ra tiếp tục các câu
lệnh tới khi < 0 thì sẽ chuyển qua dòng print Blastoff
5
4
3
2
1
Blastoff
0
An Infinite Loop
n=5
while n > 0:
print (‘Lather’)
print (‘Rinse’)
print (‘Dryoff’)
biến “n” không thay đổi nên nó sẽ chạy liên tục đến khi máy HẾT PIN, VÔ HẠN
Cần iteration variable để control how long the iteration runs when it comes to FALSE
Skip to next statement
- The break statement ends the current loop and jumps to the statement immediately
following the loop
- It is like a loop test that can happen anywhere in the body of the loop
Program:
while True:
line = input (‘>’)
if line == ‘done’ :
break
print (line)
print (‘Done!’)
Khi thấy lệnh break thì chuyển ngay xuống lệnh Done!
- The continue statement ends the current iteration and jumps to the top of the loop and starts
the next iteration
“Break” skip out of the Loop and “Continue” skip to the top of the Loop
while True:
line = input (‘>’)
if line [0] == “#’ :
continue (move to while true)
if line == ‘done’:
break (move to print Done!)
print (line)
print (‘Done!’)
Definite Loops
Outcome:
5
4
3
2
1
Blastoff!
Outcome:
Happy new year, Joseph
Happy new year, Glenn
Happy new year, Sally
Done!
Definite loops (for loops) have explicit (minh bach- clearly) iteration variables that change
each time through a loop. These iteration variables move through the sequence or set. for
statement Chạy hết những variables mình list ra
Looking at IN
The “for” statement manages the success value of ‘i”, runs all the values
The trick is “knowing” something about the whole loop when you are stuck writing code that
only sees one entry at a time
- When we construct a Loop, think about how the program, computer gonna solve that Loop, not
how our “brain” will solve
Input:
largest_so_far = -1
print (‘Before’, largest_so_far)
for the_num in [9, 41 ,12, 3, 74, 15]:
if the_num > largest_so_far:
largest_so_far = the _num
print (largest_so_far, the num)
print ('After', largest_so_far)
Outcome:
Before -1
99
41 41
41 12
41 3
74 74
74 15
After 74
To count how many times we execute a loop, we introduce a counter variable that starts at 0 and
add one to it each time through the loop.
zork = 0
print (‘Before”, zork)
for thing in [9, 41, 12, 3, 74, 15]:
zork = zork + 1
print (zork, thing)
print (‘After”, zork)
Outcome:
Before 0
19
2 41
3 12
43
5 74
6 15
After 6
Summing in a Loop
To add up a value we encounter in a loop, we introduce a sum variable that starts at 0 and add
the value to the sum each time through the loop
zork = 0
print (‘Before”, zork)
for thing in [9, 41, 12, 3, 74, 15]:
zork = zork + thing
print (zork, thing)
print (‘After”, zork)
Outcome:
Before 0
99
50 41
62 12
65 3
139 74
154 15
After 154
An average just combines the counting and sum patterns and divides when the loop is done.
count = 0
sum = 0
print (‘Before’, count, sum)
for value in [9, 41, 12, 3, 74, 15]:
count = count + 1
sum = sum + value
print (count, sum, value)
print (‘After’, count, sum, sum / count)
Outcome:
Before 0 0
199
2 50 41
3 62 12
4 65 3
5 139 74
6 154 15
After 6 154 25
Filtering in a Loop
We use an if statement in the loop to catch/filter the values we r looking for
print(‘Before’)
for value in [ 9, 41, 12, 3, 74, 15]:
if value > 20:
print( ‘Large number’, value)
print (‘After’)
Before
Large number 41
Large number 74
After
If we want to search and know if a value was found, we use a variable that starts at False and is
set to True as soon as we find what we are looking for.
Input:
found = False
print (‘Before’, found)
for value in [9, 41, 12, 3, 74, 15]:
if value == 3:
found = True
print (found, value)
print (‘After’, found)
Before False
False 9
False 41
False 12
True 3
True 74
True 15
After True
** Nếu ta dùng lệnh break ở found true thì sẽ không quay lại 74 15 mà print After True
luôn
largest_so_far = -1
print (‘Before’, largest_so_far)
for the_num in [9, 41 ,12, 3, 74, 15]:
if the_num > largest_so_far:
largest_so_far = the _num
print (largest_so_far, the num)
print ('After', largest_so_far)
Outcome:
Before -1
99
41 41
41 12
41 3
74 74
74 15
After 74
Sử dụng None như một cách gắn cờ cho giá trị đầu tiên và so nó với các giá trị tiếp theo
smallest = None
print (‘Before’)
for value in [9, 41 ,12, 3, 74, 15]:
if smallest is None:
smallest = value
elif value < smallest:
smallest = value
print (smallest, value)
print ('After', smallest)
Outcome:
Before
99
9 41
9 12
33
3 74
3 15
After 3
We still have a variable that is the smallest so far. The first time through the loop smallest is
None, so we take the first value to be the smallest.
smallest = None
print (‘Before’)
for value in [3, 41 ,12, 9, 74, 15]:
if smallest is None:
smallest = value
elif value < smallest:
smallest = value
print (smallest, value)
print ('After', smallest)
Đề
Sau khi dừng, in ra số lớn nhất và nhỏ nhất trong các số đã nhập.
INPUT:
Enter a number: 7
Enter a number: 2
Enter a number: bob
Invalid input
Enter a number: 10
Enter a number: 4
Enter a number: done
Maximum is 10
Minimum is 2
- largest và smallest bắt đầu là None để dễ kiểm tra giá trị đầu tiên.
- try/except: để bắt lỗi khi người dùng nhập thứ không phải số.
- continue: bỏ qua vòng lặp hiện tại nếu lỗi, và tiếp tục vòng mới.
- break: thoát khỏi vòng while khi nhập 'done'. (vậy lệnh if num = “done” và break chỉ
chạy khi mình nhập done
Chú Ý:
Vì 2 lệnh if cuối để trả kết quả số vẫn cần ở trong vòng lặp để xét num phải ident đúng
dòng với num = input
Câu lệnh:
x = int(num)
là để chuyển dữ liệu người dùng nhập (dạng chuỗi) thành kiểu số nguyên (int) — vì khi dùng
input() thì dù bạn nhập số, Python vẫn hiểu đó là chuỗi! Khi gõ vào input tất cả là string
try:
x = int(num) # lỗi ở đây nếu nhập "bob"
except:
print("Invalid input")
continue