python的基础05 if语句

5.1 一个简单的示例

cars = ['audi','bmw','subaru','toyota']
for car in cars:
    if car == 'bmw':  # 检查car是否是bmw,如果是就以首字母大写的方式打印
        print(car.title())
    else:  # 如果不是就以全部字母大写的方式打印
        print(car.upper())
AUDI
Bmw
SUBARU
TOYOTA
 

5.2 条件测试

  • 每条if语句的核心都是一个值为True或者False的表达式,这种表达式称为条件测试.
  • python根据条件测试的值为True还是False来决定是否执行if语句中的代码.
  • 如果条件测试的值为True,python会执行紧跟在if语句后面的代码.
  • 如果为False,python就会忽略这些代码.

    5.2.1 检查是否相等

# 最简单的条件测试是检查两个变量的值是否相等
car = 'bmw'
print(car == 'bmw')
car = 'audi'
print(car == 'bmw')
True
False
 

5.2.2 检查是否相等时不考虑大小写

  • 在python中检查是否相等时区分大小写
car = 'AUDI'
print(car == 'audi') # 大小写不一样,结果为False
# lower()让car的值全部小写,所以AUDI变为了audi,再把转化的结果audi和==右边的audi相比较
print(car)
print(car.lower() == 'audi') 
False
AUDI
True
 

5.2.3 检查是否不相等

  • 要的判断两个值是否不相等我们使用(!=)
# 使用if语句来演示如何使用不等运算符
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
    print("Hold the anchovies!")
Hold the anchovies!
 

5.2.4 比较数字

age = 18 
print(age == 18)
age = 19
print(age != 18)
age = 25
print(age > 18)
print(age < 18)
print(age % 3 == 1)
True
True
True
False
True
 

5.2.5 检查多个条件

  • 有时候需要比较两个条件都为True时才执行相应的操作,而有时候只需要一个条件的结果为True就执行相应的操作,这个时候我们可以使用关键字and和or

    1.使用and检查多个条件

  • 要检查是否两个条件都为True,可以使用and将两个条件测试合而为一
    • 如果每个测试都通过了,整个表达式的结果就是True
    • 如果至少有一个测试没有通过,整个表达式的结果就是False
# 检查两个人的年龄都不小于21
age_0 = 22
age_1 = 18
print(age_0 >= 21 and age_1 >= 21)
age_1 = 21
print((age_0 >= 21) and (age_1 >= 21))
False
True
 

2.使用or检查多个条件

  • 关键字or也能够让我们检查多个条件,但至少有一个条件满足,就能通过整个测试
  • 仅当两个测试都没有通过时,使用or的表达式才为False
age_0 = 22
age_1 = 18
print((age_0 >= 21) or (age_1 >= 21))
age_0 = 16
print((age_0 >= 21) or (age_1 >= 21))
True
False
 

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

  • 要判断特定的值是否包含在列表中,可使用关键字in
# in练习
requested_toppings = ['mushrooms','onions','pineapple']
print('mushrooms' in requested_toppings)
print('pepperoni' in requested_toppings)
True
False
 

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

  • 检查特定值是否不包含在列表中,我们使用关键字not in
# not in 练习
banned_users = ['andrew','carolina','david']
user = 'marie'
if user not in banned_users:
    print(user.title() + ",you can post a response if you wish.")
Marie,you can post a response if you wish.
 

5.2.8 布尔表达式

  • 与条件表达式一样,布尔表达式的结果要么为True,要么为False.
  • 布尔值通常用于记录条件,在跟踪程序状态中重要的条件方面,布尔值提供了一种高效的方式
 

5.3 if语句

  • if语句有很多种,选择哪种取决于我们要测试嘚瑟条件数.
  • if 条件表达式:最简单的if语句只有一个测试和操作.
    • 条件表达式就是计算结果必须为布尔值的表达式
    • 表达式后面的冒号(:)必须有,不能少
    • 注意if后面的代码块(我们把缩进相同的语句称之为代码块),如果属于if语句,则必须使用同一个缩进等级
    • 条件表达式的结果为True则执行if后面的语句块

      5.3.1 简单的if语句

  • 最简单的if语句只有一个测试和操作.
age = 19
if age > 18:  # 表达式的结果为True,所以会执行下面的print
    print("You are old enough to vote")
    print("Have you registered to vote yet?")
    
# 练习2
age = 17  # 把17赋值给age
if age < 18:  # if空格+条件表达式. 因为年龄17 < 18,结果为True,所以会执行下面的语句快
    print("\n对不起!")
    print("你未满十八岁")
    print("你不能待在这里")
print("欢迎你老这里玩")
You are old enough to vote
Have you registered to vote yet?

对不起!
你未满十八岁
你不能待在这里
欢迎你老这里玩
 

5.3.2 if-else语句

  • 经常需要在条件测试通过时执行一些操作,并且在没有通过时执行另一个操作,在这种情况下我们使用if-else语句.
    • 双向分支有两个分支,当程序执行到if...else..的时候,一定会执行其中的一个,也仅仅执行其中的一个
    • 缩进的问题,if和else属于一个层级,其余语句一个层级
age = 17
if age >= 18:  # 条件表达式的结果为False,所以不会执行if的缩进语块,而是执行else语块
    print("You are old enough to vote!")
    print("Have you registered to vote yet?")
else:
    print("Sorry,you are too young to vote.")
    print("Please register to vote as soon as you turn 18!")
Sorry,you are too young to vote.
Please register to vote as soon as you turn 18!
 

5.3.3 if-elif-else结构

  • 经常需要检查查过两个的情形,这种情况我们使用if-elif-else结构.
  • python只会执行if-elif-else结构中的一个代码块.
  • python会一次检查每个条件测试,直到遇到了通过的条件测试,python会执行紧跟在它后面的代码,而跳过余下的测试. 
# 游乐园收费规则
# 四岁以下免费,4-18收费5美元,大于等于18岁收费10美元
age = 12
if age < 4: # 条件测试结果为False,不会执行紧跟在它后面的语句
    print("You admission cost is $0.")
elif age >= 4 and age < 18: # 条件测试的结果是True,执行紧跟语句,忽略else.
    print("You admission cost is $5.")
else:
    print("You admission cost is $10")

# 修改上述代码
age = 12
if age < 4:
    price = 0
elif 4 <= age < 18:
    price = 5
else:
    price = 10
print("Your admission cost is $" + str(price) + '.')
You admission cost is $5.
Your admission cost is $5.
 

5.3.4 使用多个elif代码块

  • 可根据需要使用多个的elif代码块
age = 68
if age < 4:
    price = 0
elif 4 <= age < 18:
    price = 5
elif age >= 65:
    price = 5
else:
    price = 10
print("Your admission cost is $" + str(price) + '.')
  Your admission cost is $5.
 

5.3.6 测试多个条件

  • 有时候必须检查我们关心的所有条件,在这种情况下,应该使用一系列不包含elif和else代码块的简单的if语句.
  • 在可能有多个条件为True,且我们需要在每个条件为True时都执行相应的措施,适合使用这种方法.
requested_toppings = ['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
    print(1)
if 'pepperoni' not in requested_toppings:
    print(2)
if 'extra cheese' in requested_toppings:
    print(3)
1
2
3
 

动手试一试 

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

'''5-4 外星人颜色#2:像练习 5-3 那样设置外星人的颜色,并编写一个 if-else 结构。
 如果外星人是绿色的,就打印一条消息,指出玩家因射杀该外星人获得了 5 个
点。
 如果外星人不是绿色的,就打印一条消息,指出玩家获得了 10 个点。
 编写这个程序的两个版本,在一个版本中执行 if 代码块,而在另一个版本中执
行 else 代码块。'''
# 1
alien_color = 'yellow'
if alien_color == 'green':
    print("你获得了5个点")
else:
    print("你获得了10个点")
# 2
alien_color = 'green'
if alien_color != 'yellow':
    print("恭喜你获得了5个点")
else:
    print("你获得了5个点")
'''5-5 外星人颜色#3:将练习 5-4 中的 if-else 结构改为 if-elif-else 结构。
 如果外星人是绿色的,就打印一条消息,指出玩家获得了 5 个点。
 如果外星人是黄色的,就打印一条消息,指出玩家获得了 10 个点。
 如果外星人是红色的,就打印一条消息,指出玩家获得了 15 个点。'''
alien_color = 'green'
if alien_color == 'green':
    print("你获得了5个点")
elif alien_color == 'yellow':
    print("你获得了10个点")
else:
    print("你获得了15个点")
你获得了5个.
你获得了10个点
恭喜你获得了5个点
你获得了5个点
 
'''5-6 人生的不同阶段: 设置变量 age 的值, 再编写一个 if-elif-else 结构, 根据 age
的值判断处于人生的哪个阶段。
 如果一个人的年龄小于 2 岁,就打印一条消息,指出他是婴儿。
 如果一个人的年龄为 2(含)~4 岁,就打印一条消息,指出他正蹒跚学步。
 如果一个人的年龄为 4(含)~13 岁,就打印一条消息,指出他是儿童。
 如果一个人的年龄为 13(含)~20 岁,就打印一条消息,指出他是青少年。
 如果一个人的年龄为 20(含)~65 岁,就打印一条消息,指出他是成年人。
 如果一个人的年龄超过 65(含) 岁,就打印一条消息,指出他是老年人。'''
age = 35
if age < 2:
    print("他是婴儿")
elif age >= 2 and age < 4:
    print("他正在学走路")
elif 4 <= age < 13:
    print("他是儿童")
elif(age >= 13) and (age < 20):
    print("他是青少年")
elif 20 <= age < 65:
    print("他是成年人")
else:
    print("他是老年人")
他是成年人
 
#5-7 喜欢的水果:创建一个列表,其中包含你喜欢的水果,再编写一系列独立的 if语句,检查列表中是否包含特定的水果。
fruit = ['apple','pear','banana']
if 'pear' in fruit:
    print("pear在里面")
    
#  将该列表命名为 favorite_fruits,并在其中包含三种水果。
favorite_fruits = ['apple','pear','banana']
# 编写 5 条 if 语句,每条都检查某种水果是否包含在列表中,如果包含在列表中,就打印一条消息,如“ You really like bananas!”。
if 'apple' in favorite_fruits:
    print('You really like apple!')
if 'banana' in favorite_fruits:
    print("You really like bananas")
if 'pear' in favorite_fruits:
    print('You really like pear!')
if 'orange' in favorite_fruits:
    print('You really like bananas!')
if 'watermellon' in favorite_fruits:
    print('You really like bananas!')
pear在里面
You really like apple!
You really like bananas
You really like pear!
 

5.4 使用if语句处理列表

5.4.1 检查特殊元素

requested_toppings = ['mushrooms','green peppers','extra cheese']
for requested_topping in requested_toppings:
    print("Adding " + requested_topping + '.')
print("\nFinished making your pizza!")
    Adding mushrooms.
Adding green peppers.
Adding extra cheese.

Finished making your pizza!
 
# 在for循环中包含if语句
# 如果青椒用完了,告诉顾客我们没有青椒了
requested_toppings = ['mushrooms','green peppers','extra cheese']
for requested_topping in requested_toppings:
    if requested_topping == 'green pepers':
        print("Sorry,we are out of green pepers right now.")
    else:
        print("Adding " + requested_topping + '.')
print("\nFinished making your pizza!")
Adding mushrooms.
Adding green peppers.
Adding extra cheese.

Finished making your pizza!
 

5.4.2 确定列表不是空的

# 创建了一个空的列表
resuested_toppings = []
# 在if语句中,将列表名用在条件表达式时,python将在列表中包含一个元素时返回True,并在列表为空时返回False.
if requested_toppings:  # 因为是一个空列表,所以python不会执行下面这个for循环
    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?
 

5.4.3 使用多个列表 

# 我们定义了一个列表,其中包含比萨店供应的配料
available_toppings = ['mushrooms','olives','green pepers','pepperoni','pineapple','extra cheese']
# 定义了一个列表,其中包含顾客点的配料
requested_tippings = ['mushrooms','french fries','extra cheese']
# 遍历顾客点的配料列表。在这个循环中,对于顾客点的每种配料,我们都检查它是否包含在供应的配料列表中
for requested_topping in requested_toppings:
# 如果这个原料在available_toppings中,就将其加入到比萨中,否则将运行else代码块
    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
 

动手试一试

'''5-8 以特殊方式跟管理员打招呼:创建一个至少包含 5 个用户名的列表,且其中一
个用户名为'admin'。想象你要编写代码,在每位用户登录网站后都打印一条问候消息。
遍历用户名列表,并向每位用户打印一条问候消息。
 如果用户名为'admin',就打印一条特殊的问候消息,如“ Hello admin, would you
like to see a status report?”。
 否则,打印一条普通的问候消息,如“ Hello Eric, thank you for logging in again”。'''
username = ['python','java','C','lucy','bob','admin']
if 'admin' in username:
    print('Hello admin,would you like to see a status report?')
else:
    print("Hello " + str(username) + ', thank you for logging in again.')

'''5-9 处理没有用户的情形:在为完成练习 5-8 编写的程序中,添加一条 if 语句,检
查用户名列表是否为空。
 如果为空,就打印消息“ We need to find some users!”。'''
usernames = ['python','java','C','lucy','bob','admin']
if usernames:
    for username in usernames:
        print("Hello,sir")
else:
    print('We need to find some users!')
#  删除列表中的所有用户名,确定将打印正确的消息。  
usernames = []
if usernames:
    for username in usernames:
        print("Hello,sir")
else:
    print('We need to find some users!')
Hello admin,would you like to see a status report?
Hello,sir
Hello,sir
Hello,sir
Hello,sir
Hello,sir
Hello,sir
We need to find some users!
 
#5-10 检查用户名:按下面的说明编写一个程序,模拟网站确保每位用户的用户名都独一无二的方式。
#  创建一个至少包含 5 个用户名的列表,并将其命名为 current_users。
current_users = ['1','22','juy','498','3247']
# 再创建一个包含 5 个用户名的列表,将其命名为 new_users,并确保其中有一两个用户名也包含在列表 current_users 中。
new_users= ['1','22','JUY','34','549']
'''遍历列表 new_users,对于其中的每个用户名,都检查它是否已被使用。如果是这样,就打印一条消息,指出需要输入别的用户名;否则,打印一条消息,指
出这个用户名未被使用。'''
for new_user in new_users:
    new_user = new_user.title()
    if new_user in current_users:
        print("这个用户名已经被使用了")
    else:
        print("你可以使用这个用户名")
#确保比较时不区分大消息;换句话说,如果用户名'John'已被使用,应拒绝用户名'JOHN'。
这个用户名已经被使用了
这个用户名已经被使用了
你可以使用这个用户名
你可以使用这个用户名
你可以使用这个用户名
 
'''5-11 序数:序数表示位置,如 1st 和 2nd。大多数序数都以 th 结尾,只有 1、 2 和 3
例外。
 在一个列表中存储数字 1~9。
 遍历这个列表。
 在循环中使用一个 if-elif-else 结构,以打印每个数字对应的序数。输出内容
应为 1st、 2nd、 3rd、 4th、 5th、 6th、 7th、 8th 和 9th, 但每个序数都独占一行。'''
numbers = list(range(1,10))
for number in numbers:
    number = str(number)
    if number == '1':
        print(number + "st")
    if number == '2':
        print(number + "nd")
    elif number == '3':
        print(number + 'rd')
    else:
        print(number + 'th')
1st
1th
2nd
3rd
4th
5th
6th
7th
8th
9th

猜你喜欢

转载自www.cnblogs.com/Pythonahy/p/10226560.html