Python编程笔记5if语句

 

Python编程学习笔记,第5记:if语句

本节将学习:简单if语句、条件测试、检查两个值是否相等、数字比较、使用and/or检查多个条件、检查特定值是否包含在列表中、if-else语句、if-elif-else语句……

目录

 

Python编程学习笔记,第5记:if语句

#  if语句

# 条件测试

#  检查是否相等

# 检查是否不等

# 比较数字

# 检查多个条件

# 使用and检查多个条件

# 使用or检查多个条件

# 检查特定值是否在列表中

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

# 布尔表达式

# if语句

#  简单if语句

# if-else语句

# if-elif-else语句

# 使用多个elif代码块

# 省略else代码块

# 使用if语句处理列表

# 在条件测试的格式设置方面,PEP8提供的唯一建议是,在诸如==、>=、<=等比较运算符两边各添加一个空格.

百败而其志不折。


#  if语句

# 5if语句
# 在Python中,if语句让你能够检查程序的当前状态,并据此采取相应的措施.
# 1.该示例中的循环首先检查当前的汽车名称是否是'bmw'.如果是,就以全部大写的方式打印输出;
# 否则就以首字母大写的方式打印输出.
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())

输出结果为:

Audi
BMW
Subaru
Toyota

# 条件测试

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

#  检查是否相等

# 3.检查是否相等
# 在Python中检查是否相等时,是区分大小写的.同一个字母的大小写会被视为不相等.
car = 'audi'
print("\n在Python中检查是否相等时,是区分大小写的.同一个字母的大小写会被视为不相等.")  # 只是为了换行
print(car == 'Audi')
print(car == 'audi')

输出结果为:

在Python中检查是否相等时,是区分大小写的.同一个字母的大小写会被视为不相等.
False
True

# 如果大小写无关紧要,而只是想检查变量的值,可将变量的值转换为小写,再进行比较.
print("\n如果大小写无关紧要,而只是想检查变量的值,可将变量的值转换为小写,再进行比较.")
car = 'Bmw'
print(car == 'bmw')
print(car.lower() == 'bmw')
# 在这里函数lower()不会修改存储在变量car中的值,因此进行比较时不会影响原来的变量.
print(car)

输出结果为:

如果大小写无关紧要,而只是想检查变量的值,可将变量的值转换为小写,再进行比较.
False
True

# 检查是否不等

# 检查是否不等
# 要判断是否不等,可结合使用惊叹号的等号(!=),其中惊叹号表示不.
# 编写的大多数条件表达式都是检查两个值是否相等,但有时候检查两个值是否不等的效率更高.
print("\n编写的大多数条件表达式都是检查两个值是否相等,但有时候检查两个值是否不等的效率更高.")
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
    print("Hold the anchovies.")

输出结果为:

编写的大多数条件表达式都是检查两个值是否相等,但有时候检查两个值是否不等的效率更高.
Hold the anchovies.

# 比较数字

# 4.比较数字
age = 18
if age == 18:
    print("She was eighteen.")
if age != 18:
    print("He is not eighteen.")
if age < 18:
    print("He is a minor.")

输出结果为:

She was eighteen.

# 条件语句中可包含各种数学比较,如小于<、小于等于<=、大于>、大于等于>=。
answer = 168
print("answer =", answer)
print("answer < 100:")
print(answer < 100)
print("answer <= 200:")
print(answer <= 200)
print("answer > 100:")
print(answer > 100)
print("answer >= 168:")
print(answer >= 168)

输出结果为:

answer = 168
answer < 100:
False
answer <= 200:
True
answer > 100:
True
answer >= 168:
True

# 检查多个条件

# 使用and检查多个条件

# 5.检查多个条件
# 使用and检查多个条件
# 要检查两个条件是否都为True,可使用关键字and将两个条件测试合二为一;
# 如果每个表达式都通过了,整个表达式就为True;如果至少有一个测试没通过,则整个表达式就为False.
age = 20
print("\nage =", age)
print("age >= 18 and age > 20:")
print(age >= 18 and age > 20)
print("age >= 18 and age >= 20:")
print(age >= 18 and age >= 20)

打印结果为:

age = 20
age >= 18 and age > 20:
False
age >= 18 and age >= 20:
True

# 使用or检查多个条件

# 使用or检查多个条件
# 使用关键字or检查多个条件,只要至少有一个条件满足,就能通过整个测试;
# 仅当两个测试都没通过时,使用or的表达式才为False.
age = 18
print("\nage =", age)
print("为了改善可读性,将每个测试都分别放在一对括号内.")
print("(age >= 18) or (age > 20):")
print((age >= 18) or (age > 20))
print("(age < 18) or (age >= 20):")
print((age < 18) or (age >= 20))

输出结果为:

age = 18
为了改善可读性,将每个测试都分别放在一对括号内.
(age >= 18) or (age > 20):
True
(age < 18) or (age >= 20):
False

# 检查特定值是否在列表中

# 6.检查特定值是否在列表中.
# 要检查特定值是否在列表中,可使用关键字in.
requested_toppings = ['mushrooms', 'onions', 'pineapple']
print(" 'mushromms' in requested_toppings:")
print('mushrooms' in requested_toppings)

输出结果为:

 'mushromms' in requested_toppings:
True

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

# 7.检查特定值是否不包含在列表中.
# 有时候,需要确定特定的值是否不包含在列表中,可使用关键字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.

# 布尔表达式

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

# if语句

#  简单if语句

# if语句
# 1.简单if语句:最简单的if语句只有一个测试和一个操作.
age = 19
if age >= 18:
    print("You are old enough to vote.")
    print("Have you registered to vote yet?")

输出结果为:

You are old enough to vote.
Have you registered to vote yet?

# if-else语句

# 2.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("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.

# if-elif-else语句

# 3.if-elif-else语句
# Python只执行if-elif-else结构中的一个代码块,它依次检查每个条件测试,直到遇到通过了的条件测试.
# 测试通过后,Python将执行紧跟在它后面的代码,并跳过余下的所有测试.
age = 12
if age < 4:
    print("Your admission cost is $0.")
elif age < 18:
    print("Your admission cost is $5.")
else:
    print("Your admission cost is $10.")
# 与上面功能相同,结构更小的if-elif-else结构.除了效率更高外,也更容易修改、维护.
# 要修改输出消息内容,只需修改一条而不是三条print语句.
age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 5
else:
    price = 10
print("Your admission cost is $" + str(price) + ".")
# 还记得函数str()的作用吗?不记得的话,请查看Python编程笔记2.

输出结果为:

Your admission cost is $5.
Your admission cost is $5.

# 使用多个elif代码块

# 使用多个elif代码块.
# 可根据需要使用任意数量的elif代码块.
age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 5
elif age < 50:
    price = 10
elif age < 65:
    price = 5
else:
    price = 0
print("Your admission cost is $" + str(price) + ".")

输出结果为:

Your admission cost is $5.

 

  • # 省略else代码块

  • # else是一条包罗万象的语句,只要不满足任何if或elif中的条件测试,
  • # else中的代码块就会执行,这可能会引入无效甚至恶意的数据.
  • # 如果知道最终要测试的条件,应考虑使用一个elif代码块来代替else代码块.
  •  
  • # if-elif-else结构功能强大,但仅适用于只有一个条件满足的情况下:遇到通过了的条件测试后,Python就会跳过余下的所有测试.
  • # 这种行为很好,效率很高,让你能够测试一个特定的条件.然而,有时候必须检查你关心的所有条件.
  • # 在这种情况下,应使用一系列不包含elif和else代码块的简单if语句.
  •  
  • # 总之,如果你只想执行一个代码块,就使用if-elif-else结构;如果必须要检查你关心的所有条件,要运行多个代码块,就使用一系列独立的if语句.

# 使用if语句处理列表

# 使用if语句处理列表
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
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!")

输出结果为:

Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.

Finished making your pizza!

# 在运行for循环前,最好确定一下列表是否为空很重要.

# 使用多个列表
available_toppings = ['mushrooms', 'olives', 'green peppers',
                      'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
if requested_toppings:
    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.")
else:
    print("Are you sure you want a plain pizza?")

输出结果为:

Adding mushrooms.
Sorry, we don't have french fries.
Adding extra cheese.

Finished making your pizza.

 

  • # 在条件测试的格式设置方面,PEP8提供的唯一建议是,在诸如==、>=、<=等比较运算符两边各添加一个空格.

 

 

  • 百败而其志不折。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值