我們在寫程序時,常常需要指明兩條或更多的執行路徑,而在程序執行時,允許選擇其中一條路徑,或者說當給定條件成立時,則執行其中某語句。在這個過程中我們就需要用條件語句來幫我們判定。在python中,最常見的條件語句就是if,if是如何用的呢?下面我們來看看。
if 語句的判斷條件可以用>(大於)、<(小於)、==(等於)、>=(大於等於)、<=(小於等於)來表示其關系。
在使用中, if 可以判斷條件
出現條件不成立的情況,使用 else
1、if條件語句的基本用法:
if 判斷條件:
執行語句……
else:
執行語句……
實例::輸入一個數字並判斷是否大於10
a = int(input("請輸入一個數:"))
if a >= 10:
print("大於等於10")
else:
print("小於10")
2、if嵌套語句
當判斷條件為多個值時,可以使用以下兩種形式:
第一種
if 判斷條件1:
執行語句1……
elif 判斷條件2:
執行語句2……
elif 判斷條件3:
執行語句3……
else:
執行語句4……
第二種
if 判斷條件1:
執行語句1……
elif 判斷條件2:
執行語句2……
elif 判斷條件3:
執行語句3……
else:
執行語句4……
3、if – elif – else語句的使用
#猜拳游戲
import random #random() 方法返回隨機生成的一個實數,它在[0,1)范圍內
player_imput =input("請輸入(0剪刀、1石頭、2布):")
player =int(player_imput)
computer = random.randint(0,2)
if (player ==0 and computer == 2) or (player ==1 and computer == 0)\
or (player == 2 and computer == 1):
print("恭喜你,你贏了")
elif (player ==2 and computer == 0) or (player ==0 and computer == 1)\
or (player == 1 and computer == 2):
print("電腦贏了,你是個豬嗎")
else:
print("平局,還不錯")
以上就是python中條件語句if的使用方法,在編程高級語言中,經常能用到,要掌握哦~
本文轉自SDK社區:http://www.sdk.cn