3.1 判断语句
age = 19
if age >= 18:
print(‘You are old enough to vote!’)
print(‘Have you registered to vote yet?’)
#注意:if后面跟布尔表达式(值只能是True或False)。注意:号和缩进。
3.1.1 if-else语句
#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()
3.1.2 if-elif-else
age = 12
if age < 4:
print(‘Your admission cost is $0.’)
elif age < 18:
print(‘Your admission cost is $5.’)
elif age < 65:
print(‘Your admission cost is $10.’)
else:
print(‘Your admission cost is $5.’)
print()
3.1.3 例子
#用if语句检查列表中的特殊元素:
requested_toppings = [‘mushrooms’, ‘green peppers’, ‘extra cheese’]
for t in requested_toppings:
if t == ‘green peppers’:
print(‘Sorry, we are out of green peppers right now.’)
else:
print('Adding ’ + t + ‘.’)
#用if语句检查列表是否为空:
requested_toppings = []
if requested_toppings: # 或者:len(requested_toppings) > 0
for t in requested_toppings:
print('Adding ’ + t + ‘.’)
print(‘Finished making your pizza!’)
else:
print(‘Are you sure you want a plain pizza?’)
1.输入代码
2.运行结果