比较运算符
1、检查是否相等
相等运算符(==):用来判断二者是否“相等”,注意与赋值运算符(=)区分。
car = 'audi' '''在Python中判断是否相等时区分大小写''' car == 'Audi' '''False,返回0''' car.title() == 'Audi' '''True,返回1'''
2、检查是否不相等
(1)比较数字:小于(<)、小于等于(<=)、大于(>)、大于等于(>=)。
age = 19 age < 21 '''True,返回1''' age <= 21 '''True,返回1''' age > 19 '''False,返回0''' age >= 19 '''True,返回1'''
(2)条件判断:不等于(!=)。
requested_topping = 'mushrooms' if requested_topping != 'anchovies': print("Hold the anchovies!")
逻辑运算符
使用逻辑运算符and和or可一次检查多个条件,形成更复杂的判断式。
age_0 = 22 age_1 = 18 age_0 >= 21 and age_1 >= 21 '''False,返回0''' age_0 >= 21 or age_1 >= 21 '''True,返回1''' age_1 = 22 age_0 >= 21 and age_1 >= 21 '''True,返回1'''
if语句
上述程序中的判断语句,均可作为if语句的条件测试。若测试值为真,Python将会执行if语句所包含的代码,若为假则不会执行。
1、简单的if语句
age = 19 if age >= 18: print("You are old enough to vote!")
2、if-else语句
age = 17 if age >= 18: print("You are old enough to vote!") print("Have you registered to vote yet?") else: print("Sorry, you are too young to vote.") print("Please register to vote as soon as you turn 18!")
输出为:
Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!
和for语句相同,当测试值为真时,Python会执行所有紧跟在if语句之后且缩进的代码。
3、if-elif-else结构(elif意为else if)
可用于进行多分支的判断。
age = 12 if age < 4: price = 0 elif age < 18: price = 5 elif age < 65: price = 10 else: price = 5 print("Your admission cost is " + str(price) + " dollars.")
使用if语句处理列表
1、判断列表是否为空
当把列表名用作if语句的条件表达式时,Python将在列表至少包含一个元素时返回True,在列表为空时返回False。
requested_toppings = [] if requested_toppings: print("not empty") else: print("empty")
'''列表为空,故打印empty'''
2、判断元素是否在列表中
使用in表示包含于列表,not in表示不包含于列表。
available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese'] '''在Python中,当一行代码过多时,可像这样直接换行继续写''' requested_toppings = ['mushrooms', 'french fries', 'extra cheese'] for requested_topping in requested_toppings: if requested_topping not in available_toppings: print("Sorry, we don't have " + requested_topping + ".") else: print("Adding " + requested_topping + ".") print(" Finished making your pizza!")
输出为:
Adding mushrooms. Sorry, we don't have french fries. Adding extra cheese. Finished making your pizza!
参考书籍:《Python编程:从入门到实践》
2020-07-09