Python学习之路(五)if语句

条件测试

检查是否相等 ==
如果相等返回True,执行后面紧跟的代码,不相等则返回False,忽略紧跟代码

检查是否相等时区别大小写

比较数字
== != > < <= >=

检查是否不相等
!=

检查多个条件
and两个条件都为真时执行
or一个条件为真就执行

检查特定值是否包含在列表中
in

布尔表达式
True
False

if语句

if

age=19
if age > 18:
    print("You are old enough to vote!")
    print("Have you registered to vote yet?")   #条件为True,执行紧跟在后边缩进的代码

if-else

age=17
if age > 18:
    print("You are old enough to vote!")
    print("Have you registered to vote yet?")
else:   #条件通过执行紧跟代码,不通过执行else代码
    print("Sorry,you are too young to vote.")
    print("Plase register to vote as soon as you turn 19!")

if-elif-else

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)+".")
#else代码块可省略,使用elif代替 避免恶意数据

测试多个条件

requested_toppings=['mushrooms','exra chese']
if 'mushrooms' in requested_toppings:
    print("Adding mushrooms")
if 'pepperoni' in requested_toppings:
    print("Adding pepperoni")
if 'exra chese' in requested_toppings:
    print("Adding requested_toppings")
print("Finished making your pizza!")

使用if语句处理列表

检查特殊元素

requested_toppings=['mushrooms','green poppers','extra cheese']
for requested_topping in requested_toppings:
    if requested_topping == 'green poppers':
        print("Sorry,we are out of green poppers right now.")
    else:
        print("Adding "+requested_topping+".")

print("\nFinished making your pizza")

确定列表不是空的

reuested_toppings=[]
if reuested_toppings:	#为空返回Flase,不为空则返回True
    for requested_topping in requested_toppings:
        print("Adding "+requested_topping+".")
    print("\nFinished making your pizza")
else:
    print("Are you sure you want a plain pizza?")

使用多个列表

available_toppings=['mushrooms','olives','green peppers',
                    'pepperoni','pineapple','extra cheese']
requested_toppings=['mushrooms','french fries','extra cheese']
for requested_tooping in requested_toppings:
    if requested_tooping in available_toppings:
        print("Adding "+requested_tooping+".")
    else:
        print("Sorry,we don't have"+requested_tooping+".")
print("\nFinished making your pizza!")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值