Python编程-第五章-if语句

一个简单的例子

5.1 一个简单示例

cars=['audi','bmw','sbaru','toyota']  
  
for car in cars:  
    if car == 'bmw':  
        print (car.upper())  
    else:  
        print(car.title())

条件测试

条件测试

字符串比较

  1. 检查字符串是否相等
requested_topping ='mushrooms'  
if requested_topping != 'anchovies':  
    print("Hold the anchovies")
car = 'Bmw'  
print(car.lower() == 'bmw')
Warning

注意:目前大小写是敏感的。

数字比较

  1. 大小比较
age=19  
print(age<21)  
print(age>21)  
print(age>=21)
print(age!=9)

列表比较

检查特定值是否包含在列表中

requested_toppings = ['mushrooms','oninos','pineapple']  
print('mushrooms' in requested_toppings)  
print('pinepple' in requested_toppings)
  1. 和if 语句结合使用
banned_users =['andrew','carolina','david']  
user = 'marie'  
if user not in banned_users:  
    print(f"{user.title()},you can post a  response if you wish.")

逻辑运算

检查多个条件

  1. and
age_0= 22  
age_1 =18  
print(age_0 >= 21 and age_1 >=21)  
age_1 =22  
print(age_0 >= 21 and age_1 >=21)
# 代码优化,阅读性更强。
print((age_0 >= 21) and (age_1 >=21))
  1. or
age_0=22  
age_1=18  
print(age_0 >=21 or age_1 >= 21)  
age_0=18  
print(age_0 >=21 or age_1 >=21)

IF 语句

if 语句

age =17  
if age >= 18:  
    print("You are old enough to vote")  
    print("Have you registered to vote yet?")  
else:  
    print("Sorry,you ar too young to vote.")  
    print("Please register to vote as soon as you turn 18!")
# if-else-if
age = 12  
if age < 4:  
    print("Your admission cost is $0.")  
elif age < 18:  
    print("You admission cost is $25.")  
else:  
    print("Your admission cost is $40")
# price for ticks
age=12  
if age <4:  
    price=0  
elif age < 18 :  
    price=25  
elif age < 65:  
    price=40  
elif age >=65:  
    price=20  
  
print(f"Your admission cost is ${price}.")

# for list 
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.")

练习题

练习5-3:外星人颜色 假设在游戏中刚射杀了一个外星人,请创建一个名为alien_color 的变量,并将其赋值为'green' 、'yellow' 或'red' 。编写一条if 语句,检查外星人是否是绿色的。如果是,就打印一条消息,指出玩家获得了5分。编写这个程序的两个版本,在一个版本中上述测试通过了,而在另一个版本中未通过(未通过测试时没有输出)

alien_color='yellow'  
  
if alien_color == 'green':  
    print("got it 5 score.")  
elif alien_color == 'yellow'  
    print("got it 10 score.")  
elif alien_color =='red'  
    print("got it 15 score")

人生的不同阶段

ages=[14,23,56,90]  
for age in ages:  
    if age < 2:  
        print("婴儿")  
    elif age >=2 and age < 4:  
        print("幼儿")  
    elif age >=4 and age < 13:  
        print("儿童")  
    elif age >=13 and age <20:  
        print("青少年")  
    elif age >=20 and age < 65:  
        print("成年人")  
    elif age >=65:  
        print("老年人")

喜欢的水果

favorite_fruits=['apple','bananas','alice']  
fruits='bananas'  
if fruits in favorite_fruits :  
    print(f"You really like {fruits.title()}")

使用IF 语句处理列表

检查特殊元素

检查特殊元素

requested_toppings = ['mushrooms','green peppers','extra cheeese']  
for requested_topping in requested_toppings:  
    if requested_topping == 'green peppers':  
        print("Sorry,we are out of green peppers right now.")  
    else:  
        print(f"Adding {requested_topping}.")  
    print(f"Adding {requested_topping}.")  
  
print("\nFinnished making you pizza!")

判断列表是否为空

确定列表不是空的

requested_toppings = []  
if requested_toppings:  
    for requested_topping in requested_toppings:  
        print(f"Adding {requested_topping}.")  
    print("\nFinnished making you pizza!")  
else:  
    print("Are you sure you want a plain pizza?")

使用多个列表

使用多个列表

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(f"Adding {requested_topping}.")  
    else:  
        print(f"Sorry, we don't have{requested_topping}.")  
print("\nFinished making your pizza!")

练习题

练习5-8:以特殊方式跟管理员打招呼

users=['admin','alice','aming','job','lili']  
for user in users:  
    if user == 'admin':  
        print(f"Hello {user}, wolud you like to see a status report?")  
    else:  
        print(f"Hello {user},thank you for logging in again." )

处理没有用户的情形

users=[]  
if users:  
    for user in users:  
        if user == 'admin':  
            print(f"Hello {user}, wolud you like to see a status report?")  
        else:  
            print(f"Hello {user},thank you for logging in again." )  
else:  
    print(f"We need to find some users")

检查用户名

current_users=['admin','alice','aming','job','lili']  
new_users=['john','alice','aming','job','lili']  
  
for user in new_users:  
    if user in current_users:  
        print(f"Hello {user}, 已经存在?")  
    else:  
        print(f"Hello {user},可以使用." )

序数

number=[1,2,3,4,5,6,7,8,9]  
for i in number:  
    if i ==1:  
        print(f"{i}st")  
    elif i==2:  
        print(f"{i}nd")  
    else:  
        print(f"{i}th")