【python】If 语句

部署运行你感兴趣的模型镜像

1 使用if 进行条件判断

1.1 检查字符串是否相等

car = 'bmw'
car == 'BMW' # FALSE
car = 'bmw'
car.upper() == 'BMW' # true
# 变小写用方法:lower

1.2 检查字符串是否不相等

my_car = 'yadea'

if my_car != 'Audi':
    print("Buy one! Buy one! Buy one!")

1.3 比较数字

answer = 17
if answer == 17: 
    print("That is a correct answer. ")
if answer != 42: 
    print("That is not the correct answer. Please try again!")

1.4 检查多个条件

1.4.1 使用and 检查多个条件

使用 and 可以在 if 语句中同时检查多个条件,只有所有条件都满足时才执行相应的代码块。

num = 25
if num >= 20 and num <= 30:
    print(f"{num} 在 20 到 30 之间")

等价于

num = 15
if num >= 20:
    if num <= 30:
        print(f"{num} 在 20 到 30 之间")

组合多个条件

age = 25
is_student = False
has_discount = True

if (age < 18 or age > 60) and (is_student or has_discount):
    print("你符合折扣条件。")

用途示例:检查账户和密码

username = "root"
password = "admin123"
if username == "root" and password == "admin123":
    print("登录成功!")

条件的顺序可能会影响程序的效率。例如,在多个条件中,如果有一个条件计算起来比较耗时,而它在 and 连接的条件序列的后面,只有在前面所有条件都为 True 时,才会计算这个耗时的条件。所以在编写代码时,可以将容易判断且有可能先为 False 的条件放在前面,以减少不必要的计算。

1.4.2 使用or 检查多个条件

or 连接的条件按从左到右的顺序进行计算,一旦遇到一个为 True 的条件,就会停止计算后面的条件,可以将大概率会发生或者简单的判断放在前面,以减少不必要的计算。

num = 35
if num < 10 or num > 20:
    print(f"{num} 不在 10 到 20 之间")

等价于

num = 35
if num < 10:
    print(f"{num} 小于 10")
if num > 20:
    print(f"{num} 大于 20")

应用举例:检查用户名是否为指定值之一

username = "admin"
if username == "root" or username == "admin":
    print("用户名正确!")

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

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(f"Adding {requested_topping}.")

print("\nFinished making your pizza!")

1.5 对布尔表达式进行判断

布尔表达式的结果是一个布尔值,即 True 或 False。你可以在 if 语句中直接对布尔表达式进行判断,或通过 and 和 or 关键字组合多个布尔表达式

is_raining = True
if is_raining:
    print("今天下雨了,记得带伞。")
is_weekend = True
is_sunny = True

if is_weekend and is_sunny:
    print("今天是晴朗的周末,适合出游。")

多个布尔值结合

age = 25
is_student = False

if (age < 18 or age > 60) and not is_student:
    print("您符合老年或未成年优惠条件。")
else:
    print("您不符合老年或未成年优惠条件。")

注意事项
在布尔表达式中,not 用于取反。例如:not True 的结果是 False。
当布尔表达式的结果是 None、空列表、空字符串、数字 0 等情况时,会被视为 False。例如:
if []: 或 if “”: 或 if 0: 都会被当作 False 来判断。
if [1, 2]: 或 if “hello”: 或 if 5: 则会被当作 True 来判断。

2 使用if 进行条件控制

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

2.2 if-elif-else语句

age = 12
if age < 4:
    print("Your admission cost is $0.")
elif age < 18:
    print("Your admission cost is $25.")
else:
    print("Your admission cost is $40.")
age = 12

if age < 4:
    price = 0
elif age < 18:
    price = 25
else:
    price = 40

print(f"Your admission cost is ${price}.")

2.3 多个elif语句

age = 12

if age < 4:
    price = 0
elif age < 18:
    price = 25
elif age < 65:
    price = 40
else:
    price = 20

print(f"Your admission cost is ${price}.")

2.4 省略else语句(表达更精确)

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}.")

2.5 if 实现连续判断(多个条件判断)

上面的方案只能判定一次,如果需要多次连续判断需要多次if;

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

3 使用if语句处理列表

3.1 检查列表不是空的

requested_toppings = []

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

3.2 检查特殊元素

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(f"Adding {requested_topping}.")

print("\nFinished making your pizza!")

3.3 使用多个列表

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

4 设置if语句的格式

PEP 8: == ; >=; 等比较运算符前后各添加一个空格

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值