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对代码的解读,只是让代码读起来更容易。