python编程基础(四):if 语句 & 增强程序鲁棒性

本文介绍了Python编程中的条件测试,包括相等判断、and与or逻辑、in与not in操作符的使用。接着详细讲解了if结构,包括简单if、if-else与if-elif-else语句。最后,讨论了如何增强程序的鲁棒性,特别是处理空列表和防止异常的方法,通过实例展示了在客户点餐场景中应用这些技巧。

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

一、 条件测试

1、判断相等:  ==

2、使用 and 判断多个条件:  条件均为 true 的时候,才是 true

类似于 &&  与

3、使用 or 判断多个条件:  条件有一个为 true 的时候,就是 true

类似于   ||   或

4、判断特定值是不是在列表中:用关键词  in    /    not in

requested_topping = ['mushrooms','onions','pineapple']
'mushrooms' in requested_topping

结果:
True


'car' not in requested_topping

结果:
True

二、if结构

1、简单 if 语句

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

注意  if 语句后面要加冒号

2、if-else 语句

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

注意,if  else 后面都要加 冒号

3、if-elif-else 语句

age = 12
if age < 4:
    print("Your admission cost is $0")
elif age < 18:
    print("Your admisiion cost is $5")
else:
    print("Your admission cost is $10")

三、增强程序的鲁棒性

加入我们在使用 if 语句判断某特殊元素是否在列表中时,列表必须是有元素的,若是空列表,即没有元素,那么会让程序崩溃或者出现莫名bug,所以在程序实现过程中,要考虑到以下:

1>  程序中要使用列表,那么在使用时一定要加上列表是否为空的判断

2> 调用列表的元素时,如果调用的不存在于列表,也就是 要求异常的情况下的防范方法

下面模拟客户点匹萨配料时的情况

# 这个是披萨店提供的配料
available_topping = ['mushrooms','olives','green peppers','pepperoni',
                     'extra cheese','pineapple']

# 这个是客户想要的配料
requested_toppings = ['mushrooms','french fires','extra cheese']

if available_topping:  # 如果 available_topping 这个列表不空,那就正常进行
    if requested_toppings:
        for requested_topping in requested_toppings:
            if requested_topping in available_topping:
                print('Add ' + requested_topping + '.')
            else:
                print('Sorry we do not have ' + requested_topping + '.')
    else:
        print("Your requestd topping is empty!")    
else:
    print("Are you sure you want a plain pizza?")

print("\nFinished making your pizza!")


结果:
Add mushrooms.
Sorry wo donot have french fires.
Add extra cheese.

Finished making your pizza!

注意 在程序上我们用了 if 来判断这两个列表是否为空

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值