Python基础学习笔记第四章——if语句

本文详细介绍了Python编程中的if语句用法,包括简单的if判断、if-else结构、if-elif-else多条件判断,以及在处理列表时的应用。通过实例展示了如何根据年龄判断投票资格、计算电影票价以及检查披萨配料的可用性。

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

一、简单示例

#简单示例1
cars = ['audi','bmw','subaru','toyota']
for car in cars:
    if car == 'bmw': 
    #注:两个等号是发问(必须是俩等号)                                                                      
        print(car.upper())
    else:
        print(car.title())

#输出Audi
#BMW
#Subaru
#Toyota                                                                                                                                                                                                                                      

二、if 语句

1. if 语句

代码如下(示例):

age = 19
if age >= 18:
    print("You are old enough to vote!")
#输出You are old enough to vote!                                                                                                             

2. if-else语句

age = 19
if age >= 18:
    print("You are old enough to vote!")
else:
     print("Sorry,you are too young to vote.")
#输出You are old enough to vote!                                                                                                              

3. if-elif-else结构

age = 12
if age < 4:
    print("Your admission cast is 0")
elif age < 18:
    print("Your admission cast is 25")
else:
    print("Your admission cast is 40") 
#输出为Your admission cast is 25                                                                                                              

4. 使用elif代码块

age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 25
elif age < 65:
    price = 40
else:    
#注:最后结尾用else,不能用elif                                                                                        
    price = 20
 print(price)
#输出为25                                                                                                              

5. 使用if语句处理列表

availiable_toppings = ['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese']
requested_toppings = ['mushrooms','french fries','extra cheese']
for requested_topping in requested_toppings:
    if requested_topping in availiable_toppings:
        print(f"Adding {requested_topping}.")
    else:
        print(f"Sorry,we do not have {requested_topping}.")
#输出Adding mushrooms.
#Sorry,we do not have french fries.
#Adding extra cheese.                                                                                                                      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值