0% found this document useful (0 votes)
4 views

Python

The document provides an overview of Python programming concepts, including syntax, variables, data types, loops, and functions. It explains the difference between interactive and script modes, conditional statements, and error handling using try-except blocks. Additionally, it covers user input, type conversions, and the structure of functions with parameters and return values.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python

The document provides an overview of Python programming concepts, including syntax, variables, data types, loops, and functions. It explains the difference between interactive and script modes, conditional statements, and error handling using try-except blocks. Additionally, it covers user input, type conversions, and the structure of functions with parameters and return values.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

https://www.py4e.

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

From user to programmer:

Syntax error is when the computer program “says” to itself they ‘don’t know” what to do (run)
next

We may delegate for computers to do annoyed tasks such as text analysis

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

variable constant function operator

Interactive versus Script


Interactive: type directly to Python one line at a time and it responds
Script: enter a sequence of statements (lines) into a file using a text editor and tell
Python to execute the statements in the file.

When a program is running, it flows from one step to the next

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

Statement must start with a letter or underscore _


Must consist of letters, numbers and underscores
Case sensitive
Good: spam eggs spam23 _speed
Bad: 23spam #sign var.12
Different: spam Spam SPAM
An assignment statement consists of an expression on the right-hand side and a variable to store
the result

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))

Operator Precedence Rules

Highest precedence rule to lowest precedence rule:


- Parentheses are always respected
- Exponentiation (raise to power)
- Multiplication, Division, and Remainder
- Addition and Subtraction
- Left to right

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ố ??? )

Several Types of Numbers


Number have two main types:

- Integers are whole numbers: 14, -2, 0 , 1, 100, 401233


- Floating Point Numbers have decimal parts: -2.5, 0.0, 98.6, 14.0
There are other number types – they are variations on float and integer

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()

String conversions ( biến lệnh “chữ” thành số)

- 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)

Nếu Who are you ? là Chuck  Lệnh sẽ ra Welcome Chuck

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 # ….

Converting User Input

- 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

Ex: # convert elevator floors


inp = input(‘Europe floor?’)
usf = int(inp) + 1
print (‘US floor’, usf)

Nếu Europe floor?: 0 thì US floor 1

MODULE 5: Conditional Statements

Converting User Input

- 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

Ex program: PHẢI THỤT DÒNG MỚI CHẠY ĐƯỢC (SAU IF)

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

2 dấu bằng ( == ) là equal to


!= là not equal to
1 dấu bằng = is used for the assignment (gán giá trị)

Begin/ End blocks

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’)

for i in range (5) :


print (i)
if I > 2:
print (‘Bigger than 2’)
print (‘Done with i’, i)
print (‘All done’)

Nested Decisions

x = 42
if x > 1:
print (‘More than one’)
if x < 100:
print(‘Less than 100’)
print (‘All done’)

Two-way Decisions with ELSE:

x=4
if x >2:
print (‘bigger’)
else:
print (‘smaller’)
print (‘All done’)

Multi-way with ELIF

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

print (‘First’, istr)


astr = ‘123’
try:
istr = int(astr)
except: istr = -1

print (‘Second’, istr)

 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

rawstr = input (‘Enter a number:’)


try:
ival = int (rawstr)
except:
ival = -1

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

FILE 2: $ python 3 trynum.py


Enter a number: forty-two
Not a number

MODULE 5: USING FUNCTION


Stored (and reused) Steps

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

big = max (‘Hello world’)


big là assignment
max là kí tự bự nhất  w : argument

>>> big = max (‘Hello world’)


>>> print (big)
w
>>> tiny = min (‘Hello world’)
>>> print (tiny)
(kết quả là khoảng trống vì ktrong đc define là min)
>>>

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

MODULE 6: Building our own Functions


** def statement is only used to define the function, is doesnot automatically run the code

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

- Nhưng nếu gõ dòng lệnh


print_lyrics() thì sẽ ra 2 dòng I’m .. và I sleep … trước số 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

We put the arguments in parentheses after the name of the function

Big = max(‘Hello world’)  ket qua la w, Hello world la function


Parameters

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.

def greet ():


return “Hello”

print (greet(), “Glenn”)


print (greet(), “Sally”)

Output:
Hello Glenn
Hello Sally

- A "fruitful" function is one that produces a result (or return value)


- The return statement ends the function execution and "sends back" the result of the function
Ex:
def greet (lang):
if lang == ‘es' :
return 'Hola'
elif lang == 'fr':
return 'Bonjour'
else:
return 'Hello'
print (greet ('en'), 'Glenn' )
Hello Glenn
print (greet('es'), 'Sally')
Hola Sally
print (greet ('fr'), 'Michael')
Bonjour Michael

Multiple Parameters / Arguments

- We can define more than one parameter in the function definition


- We simply add more arguments when we call the function
- We match the number and order of arguments and parameters

Ex:
Def addtwo (a,b):
added = a +b
return added

x = addtwo (3,5)
print (x)
8 (out come)

MODULE 7: Loops and Iteration


Repeated Steps

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

Breaking Out of a Loop

- 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

A simple Definite Loop


for i in [5, 4, 3, 2, 1] :
print (i)
print (‘Blastoff!’)

Outcome:
5
4
3
2
1
Blastoff!

A Definite Loop with Strings

friends = [ ‘ Joseph’, ‘Glenn’, ‘Sally’ ]


for friend in friends:
print (‘Happy new year:’, friend)
Print (‘Done!’)

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

Making “smart” Loops

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

Finding the Largest Value


We make a variable that contains the largest value we have seen so far. If the current number
we are looking at is larger, it is the new largest value we have seen so far

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

Loop “Idioms”: Counting in a Loop

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

Finding the Average in a Loop

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

Search Using a Boolean Variable

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

Find the smallest Value


Ở Dưới là ví dụ Find the largest, nhưng ta không thế sửa biến -1 là số dương vì không thể
xác định, nếu -1 thì sẽ hiện -1 hết thì -1 bé nhất
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

 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.

The “is” and “is not” Operators


- Python has an is operator that can be used in logical expressions
- Implies “is the same as”
- Similar to, but stronger than ==
- is not also is a logical operator

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)

 We do not overuse is, often for True, False, None …

Đề

 Lặp lại yêu cầu nhập số nguyên từ người dùng.

 Nếu người dùng nhập 'done', thì dừng vòng lặp.


 Nếu người dùng nhập chữ (như bob), thì hiện ra thông báo lỗi.

 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

OUTPUT là mấy chỗ suy ra

Giải thích nhanh:

- 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

✍️Bonus: Nhập chữ như "bob"


Nếu bạn nhập "bob" thì int(num) sẽ bị lỗi vì không thể chuyển chữ thành số → lúc đó try/except
sẽ bắt lỗi:

try:
x = int(num) # lỗi ở đây nếu nhập "bob"
except:
print("Invalid input")
continue

You might also like