Python if语句

Python Day 4 2020-4-9
Python if语句

条件测试
1.检查是否相等
大多数条件测试都将一个变量的当前值同特定值进行比较。

>>> car = 'bmw'
>>> car == 'bmw'

2.检查是否相等时不考虑大小写
在Python中检查是否相等时区分大小写`

>>> car = 'Audi'
>>> car.lower() == 'audi'
True

3.检查是否不相等
要判断两个值是否不等,可结合使用惊叹号和等号(!=)
4.比较数字
条件语句中可包含各种数学比较,如小于、小于等于、大于、大于等于等

>>> age = 18
>>> age == 18
True

5.检查多个条件
(1)使用and检查多个条件
(2)使用or检查多个条件
6.检查特定值是否包含在列表中
要判断特定的值是否已包含在列表中,可使用关键字in。

>>> requested_toppings = ['mushrooms', 'onions', 'pineapple'] 
>>> 'mushrooms' in requested_toppings 
True

7.检查特定值是否不包含在列表中
要判断特定的值是否未包含在列表中,可使用关键字not in。

banned_users = ['andrew', 'carolina', 'david'] 
user = 'marie' 
if user not in banned_users: 
 print(user.title() + ", you can post a response if you wish.")

8.布尔表达式

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

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

2.if-else 语句

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

3.if-elif-else 结构

age = 12 
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.")

3.使用多个 elif 代码块
4.省略 else 代码块
Python并不要求if-elif结构后面必须有else代码块。在有些情况下,else代码块很有用;而在其他一些情况下,使用一条elif语句来处理特定的情形更清晰。
5.测试多个条件

使用 if 语句处理列表
1.检查特殊元素
可在for循环中包含一条if语句

requested_toppings = ['mushrooms', 'green peppers', 'extra cheese'] 
for requested_topping in requested_toppings: 
 if requested_topping == 'green peppers': 
 print("Sorry, we are out of green peppers right now.") 
 else: 
 print
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值