三、if语句基本用法

if语句

最简单的if语句只有一个测试和一个操作。

if conditional_test:    
    do something
age=19
if age >= 18:    
print('You have enouth to vote!')    
print('Have you registered to vote yet?')
You have enouth to vote!
Have you registered to vote yet?

一.if-else语句

age=17
if age >= 18:    
print('You have enouth to vote!')    
print('Have you registered to vote yet?')
else:    
print('Sorry,you are too young to vite.')
print('Please register to vote as soon as you turn 18!')
Sorry,you are too young to vite.
Please register to vote as soon as you turn 18!

else语句指定条件未通过时要执行的操作。

二.if-elif-else结构

用于检查超过两个的情形。

age = 12
if age < 4:    
price=0
elif age < 18:    
price = 5
else:    
price = 10
print('Your admission cost is $' + str(price) + '.')
Your admission cost is $5.

使用多个elif代码块

age = 67
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) + '.')
Your admission cost is $5.

省略else代码块

age = 67
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) + '.')
Your admission cost is $5.

三.测试多个条件

if-elif-else结构仅适用只有一个条件满足的情况:遇到通过了的测试后,Python就跳过余下的测试。

有时候必须检查所关心的所有条件。
应使用一系列不包含elif和else代码块的简单if语句。

有可能多个条件为True,且需要在每个条件为True时都采取相应措施。

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!')
Adding mushrooms.
Adding extra cheese.

Finished making your pizza!

每当这个程序运行时,都会进行这三个独立的测试。

四.处理列表

1.确定列表不是空的

requested_toppings=[]
if requested_toppings:    
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?')
Are you sure you want a plain pizza?

2.使用多个列表

available_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 available_toppings:
        print('Adding ' + requested_topping + '.')
    else:        
       print("Sorry, we don't have " + requested_topping + ".")
print('\nFinished making your pizza!')
Adding mushrooms.
Sorry, we don't have french fries.
Adding extra cheese.

Finished making your pizza!

五.设置if语句的格式

在诸如==、>=、<=等比较运算符两边各添加一个空格,这样的空格不会影响Python对代码的解读,只是让代码读起来更容易。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值