if语句



1.#helloword.py
cars=[ 'adui','bmw','subaru','toyota']

for car in cars:
    if car == 'bmw':
       print(car.upper())
    else:
       print(car.title())

输出:

D:\www>python helloword.py
Adui
BMW
Subaru
Toyota

2.检查是否相等时不考虑大小写

在python中检查是否相等时区分大小写

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

3.检查是否不相等,可使用!=

#helloword.py
requested_tapping='mushroom'
if requested_tapping!='anchovies':
   print("Hold the anchovies")

输出为:

D:\www>python helloword.py
Hold the anchovies

4.使用and,or检查多个条件

5.检查特定值是否包含在列表中,可使用关键字in

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

6.检查特定值是否不包含在列表中,可使用关键字not in

#helloword.py
numbers=range(1,11)
number=20
if number not in numbers:
   print("no this number")

输出为:

D:\www>python helloword.py
no this number

7.if-elif-else结构

#helloword.py
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.")

输出为:

D:\www>python helloword.py
Your admission cost is $5.

8.确定列表不是空的

在if语句中将列表名用在条件表达式中时,python将在列表至少包含一个元素时返回True,并在列表为空时返回False。

#helloword.py
numbers=[]
if numbers:
   for number in numbers:
       print("adding "+number+".")
else:
    print("numbers is empty")

输出为:

D:\www>python helloword.py
numbers is empty









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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值