# 如何编写简单的if语句、if-else语句和if-elif-else结构。在程序中,你使用了这些结构来测试特定的条
# 件,以确定这些条件是否满足。你学习了如何在利用高效的for循环的同时,以不同于其他元素
# 的方式对特定的列表元素进行处理。你还再次学习了Python就代码格式方面提出的建议,这可确
# 保即便你编写的程序越来越复杂,其代码依然易于阅读和理解。
# if
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
#检测是否相等
print(car == 'bmw')
# 使用and检查多个条件
age_0 = 22
age_1 = 18
print("")
print(age_0 >=21 and age_1 >=21)
print(age_0 >=21 or age_1 >=21)
# 要判断特定的值是否已包含在列表中,可使用关键字in
requested_toppings = ['mushrooms', 'onions', 'pineapple']
print()
print( 'mushrooms' in requested_toppings)
print( 'mushroom' in requested_toppings)
# 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!")
# if elif else
print()
age = 22
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $5.")
else:
print("Your admission cost is $10.")
# 使用多个 elif 代码块
print()
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) + ".")
python ch5 if语句
最新推荐文章于 2024-07-18 15:53:23 发布