一、Python中條件語句簡介
條件語句是編程語言中非常重要的一種語句類型,它根據特定的條件來判斷是否執行某些代碼塊,也可以根據不同的條件執行不同的代碼塊。Python中常用的條件語句包括if語句、if-else語句、if-elif語句等。
二、Python中if語句的基本使用
num = 10
if num <= 20:
print("The number is less than or equal to 20")
上面的代碼中,首先定義了一個變數num,並將其賦值為10。然後使用if語句判斷num是否小於等於20,因為10小於等於20,所以if語句中的代碼塊被執行,結果輸出”The number is less than or equal to 20″。
三、Python中if-else語句的使用
num = 30
if num <= 20:
print("The number is less than or equal to 20")
else:
print("The number is greater than 20")
上面的代碼中,首先定義了一個變數num,並將其賦值為30。然後使用if-else語句判斷num是否小於等於20,因為30大於20,所以else語句中的代碼塊被執行,結果輸出”The number is greater than 20″。
四、Python中if-elif-else語句的使用
num = 50
if num <= 20:
print("The number is less than or equal to 20")
elif num > 20 and num <= 40:
print("The number is between 20 and 40")
else:
print("The number is greater than 40")
上面的代碼中,首先定義了一個變數num,並將其賦值為50。然後使用if-elif-else語句判斷num的範圍。因為50大於40,所以else語句中的代碼塊被執行,結果輸出”The number is greater than 40″。
五、Python中嵌套if語句的使用
name = "Alice"
age = 25
if name == "Alice":
if age == 25:
print("Welcome Alice!")
else:
print("Incorrect age, please try again.")
else:
print("Sorry, you are not Alice.")
上面的代碼中,首先定義了一個變數name,並將其賦值為”Alice”,另外一個變數age被賦值為25。在一個if語句中,首先判斷name是否等於”Alice”,如果滿足條件,則繼續判斷age是否等於25,如果都滿足條件,則輸出”Welcome Alice!”。否則,輸出”Incorrect age, please try again.”。如果name不等於”Alice”,則輸出”Sorry, you are not Alice.”。
完整代碼示例:
name = "Alice"
age = 25
if name == "Alice":
if age == 25:
print("Welcome Alice!")
else:
print("Incorrect age, please try again.")
else:
print("Sorry, you are not Alice.")
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/158174.html