python学习笔记: 第五章 if语句

󰃭 2017-04-05

python学习笔记: 第五章 if语句


示例

cars = ['audi', 'bmw', 'subaru', 'toyota']         

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

条件测试

car = 'Audi'
print(car == 'audi')
print(car.lower() == 'audi')
print(car)

相等判定

requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
    print("Hold the anchovies!")

检查特定值是否在列表中,如果不在则加入列表

requested_topping = ['mushrooms', 'onions', 'pineapple']
one_topping = 'tomato'
if one_topping not in requested_topping:
    print(one_topping.title() + "is not here!")
    requested_topping.append(one_topping)
    print(requested_topping)

输入并判断是否在列表中: if-else语句

requested_topping = ['mushrooms', 'onions', 'pineapple']
print("请输入一种requsted_topping:\n>>")
topping = input()
if topping in requested_topping:
    print("Hi,%s is here!" %topping)
else:
    print("%s is none!" %topping)

if-elif-else语句

age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 5
elif age < 65:
    price = 10
else:
    price = 5

print("Your admisson cost is $ " + str(price) + ".")

测试多个列表

requested_toppings = ['mushrooms', 'onions', 'pineapple']
if 'mushrooms' in requested_toppings:
    print("Adding mushrooms.")
if 'onions' in requested_toppings:
    print("Adding onions.")
if 'extra cheese' in requested_toppings:
    print("Adding extra cheese.")
print("\n Finished making your pizza!")

采用if语句处理列表

requested_toppings = ['mushrooms', 'onions', 'pineapple']
for requested_topping in requested_toppings:
    if requested_topping == 'green peppers':
        print("Sorry, we are out of green peppers right now.")
    else:
        print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")

执行列表前采用if语句判断极为重要

requested_toppings = []
#其实啥都没有做,哪里来的Pizza?
for requested_topping in requested_toppings:
    print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")

if语句判断

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?")

采用for-if-else语句实现两个列表中元素相同的判断

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!")