技巧1:单行if语句的使用Python允许在单个行中编写简单的if语句,这种格式简洁,可以提高代码的可读性。以下是单行if语句的基本格式:if condition: action()其中,condit...
Python允许在单个行中编写简单的if语句,这种格式简洁,可以提高代码的可读性。以下是单行if语句的基本格式:
if condition: action()其中,condition 是一个布尔表达式,而 action() 是当条件为真时执行的代码块。
num = 5
if num > 3: print("Number is greater than 3")在这个例子中,如果 num 的值大于3,将输出 “Number is greater than 3”。
if-else语句是if语句的扩展,它允许我们在条件为假时执行一个替代的代码块。
if condition: action_if_true
else: action_if_falsenum = 2
if num > 3: print("Number is greater than 3")
else: print("Number is not greater than 3")在这个例子中,因为 num 的值小于或等于3,所以会执行 else 分支,输出 “Number is not greater than 3”。
当有多个条件需要判断时,可以使用if-elif-else结构。
if condition1: action_if_condition1
elif condition2: action_if_condition2
else: action_if_all_conditions_falseage = 20
if age < 18: print("Not an adult")
elif age < 65: print("An adult")
else: print("Senior citizen")在这个例子中,根据 age 的值,输出相应的消息。
有时可能需要在一个条件判断的代码块内嵌套另一个if语句,以便进行更复杂的条件判断。
if condition1: if condition2: action_if_both_conditions else: action_if_condition2_false
else: action_if_condition1_falsenum1 = 5
num2 = 10
if num1 > 0: if num2 > num1: print("num2 is greater than num1") else: print("num2 is not greater than num1")
else: print("num1 is not greater than 0")在这个例子中,如果 num1 大于0,接着检查 num2 是否大于 num1。
逻辑运算符(如 and、or、not)可以与if语句一起使用,以创建更复杂的条件表达式。
if condition1 and condition2: action
elif condition1 or condition2: action
else: actionnum1 = 5
num2 = 10
if num1 > 3 and num2 > 8: print("Both conditions are true")
elif num1 > 3 or num2 > 8: print("At least one condition is true")
else: print("Both conditions are false")在这个例子中,第一个条件是 num1 > 3 and num2 > 8,第二个条件是 num1 > 3 or num2 > 8,根据这两个条件的真值,执行相应的代码块。