if 語句
python中if語句的一般形式如下所示:
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
如果 "condition_1" 為 true 將執行 "statement_block_1" 塊語句,如果 "condition_1" 為false,將判斷 "condition_2",如果"condition_2" 為 true 將執行 "statement_block_2" 塊語句,如果 "condition_2" 為false,將執行"statement_block_3"塊語句。
python中用elif代替了else if,所以if語句的關鍵字為:if – elif – else。
注意:1、每個條件後面要使用冒號(:),表示接下來是滿足條件後要執行的語句塊。
2、使用縮進來劃分語句塊,相同縮排數的語句在一起組成乙個語句塊。
3、在python中沒有switch – case語句。
以下例項演示了狗的年齡計算判斷:
age = int(input("age of the dog: "))
print()
if age
print("this can hardly be true!")
elif age == 1:
print("about 14 human years")
elif age == 2:
print("about 22 human years")
elif age > 2:
human = 22 + (age -2)*5
print("human years: ", human)
###input('press return>')
將以上指令碼儲存在
dog.py檔案中,並執行該指令碼:
python
dog.py
age of the dog: 1
about 14 human years
以下為if中常用的操作運算子:
操作符 描述
<= 小於或等於
> 大於
>= 大於或等於
== 等於,比較物件是否相等
!= 不等於
# 程式演示了 == 操作符
# 使用數字 print(5 == 6)
# 使用變數
x = 5
y = 8
print(x == y)
以上例項輸出結果:
false
false
high_
low.py檔案:
#!/usr/bin/python3
# 該例項演示了數字猜謎遊戲
number = 7
guess = -1
print("guess the number!")
while guess != number:
guess = int(input("is it... "))
if guess == number:
print("hooray! you guessed it right!")
elif guess
print("it's bigger...")
elif guess > number:
print("it's not so big.")
python條件 Python 條件控制
python 條件控制 if 語句 python中if語句的一般形式如下所示 if condition 1 statement block 1 elif condition 2 statement block 2 else statement block 3 如果 condition 1 為 tru...
python控制條件語句 Python條件控制語句
條件控制語句 if語句 if條件加表示式 if else語句 if elif else語句 if 表示式1 語句1elif 表示式2 語句2elif 表示式3 語句3else 語句e邏輯 當程式執行到if elif else語句時,首先計算表示式1的值,如果表示式1的值為假,則執行表示式2,如果表示...
Python條件控制
if 語句 python中if語句的一般形式如下所示 if condition 1 statement block 1 elif condition 2 statement block 2 else statement block 3 如果 condition 1 為 true 將執行 statem...