if语句的几种类型-----python基础学习

本文深入探讨了Python中条件语句的各种用法,包括简单的if语句、if-else语句、if-elif-else结构、使用多个elif代码块、省略else代码块以及如何测试多个条件。通过具体示例,读者可以详细了解每种语句的特点和应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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!")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值