1.简单的if 语句
if conditional_test:
do something
2. if-else 语句
age = 17
❶ if age >= 18:
。。。。。。。。。。。。。。。
❷ else:
。。。。。。。。。。。。
3.if-elif-else 结构
❶ 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.”)
4.使用多个elif 代码块
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) + “.”)
5.省略else 代码块
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
❶ elif age >= 65:
price = 5
print(“Your admission cost is $” + str(price) + “.”)
6. 测试多个条件
多个if和if else的区分,简单理解,if else 满足了其中一个条件,会跳过后面的内容,而多个if则是每个都要执行
❶ requested_toppings = [‘mushrooms’, ‘extra cheese’]
❷ if ‘mushrooms’ in requested_toppings:
print(“Adding mushrooms.”)
❸ if ‘pepperoni’ in requested_toppings:
print(“Adding pepperoni.”)
❹ if ‘extra cheese’ in requested_toppings:
print(“Adding extra cheese.”)
print("\nFinished making your pizza!")
本文深入探讨了Python中条件语句的各种用法,包括简单的if语句、if-else语句、if-elif-else结构、使用多个elif代码块、省略else代码块以及如何测试多个条件。通过具体示例,读者可以详细了解每种语句的特点和应用场景。
2万+

被折叠的 条评论
为什么被折叠?



