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