Skip to main content

Python Decision Making - IF, else, switch, for, while trong Python

Python hỗ trợ một số cấu trúc điều khiển thông dụng (if, for, while). Hầu hết các cấu trúc điều khiển đều dựa vào thụt đầu dòng (indention) để tạo thành một block xử lý, thay vì sử dụng {} như các ngôn ngữ khác (Java, PHP, Javascript)

1. If elif else

if_else_if_statement_diagram.png

- Cú pháp:

if condition1:
	indentedStatementBlockForTrueCondition1
elif condition2:
	indentedStatementBlockForFirstTrueCondition2
elif condition3:
	indentedStatementBlockForFirstTrueCondition3
elif condition4:
	indentedStatementBlockForFirstTrueCondition4
else:
	indentedStatementBlockForEachConditionFalse

- Ví dụ:

var = 100
if var == 200:
   print "1 - Got a true expression value"
   print var
elif var == 150:
   print "2 - Got a true expression value"
   print var
elif var == 100:
   print "3 - Got a true expression value"
   print var
else:
   print "4 - Got a false expression value"
   print var

print "Good bye!"

Output:

3 - Got a true expression value
100
Good bye!
2. Switch case

Python không có cấu trúc switch case

3. For in

for_loop_flow_chart_diagram.png

- Cú pháp:

for iterating_var in sequence:
	statements(s)

- Ví dụ:

for letter in 'Python': # First Example
	print 'Current Letter :', letter

fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
	print 'Current fruit :', fruit

print "Good bye!"

Output:

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
4. While

while_loop_flow_chart_diagram.png

- Cú pháp:

while expression: 
	statement(s)

- Ví dụ:

count = 0
while (count < 9):
	print 'The count is:', count
	count = count + 1

    print "Good bye!"

Output:

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!