python if 语句

检查两个值是否相等, 用 ==

day = "sunny"
if day == "sunny": //由于变量day的值是sunny,因此通过这条条件测序,python就会执行紧跟在if语句后面的代码块
    print("Excellent")
//输出结果为:
Excellent

检查两个值不相等, 用!=

day = "rainy"
if day != "sunny":
    print("Sorry, you need to do one more time")
//输出结果为:
Sorry, you need to do one more time

使用and检查多个条件,如果每个条件都通过时,整个表达式就为True,如果至少有一个测试没有通过,就为False

例子1

price_1 = 5
price_2 = 10
if price_1 >=4 and price_2 <=11: //通过条件测试,python会执行后面print的代码块
    print("well done")
// 输出结果为:
well done

例子2

price_1 = 2
price_2 = 10
if price_1 >=4 and price_2 <=11: //因为price_1的值为2,小于4,导致这个条件测序不通过,因此python不会执行后面print的代码块
    print("well done")
//没有输出结果,因为if这个条件测序没有通过

使用or检测多个条件,只要至少有一个条件通过测试,就为True

price_1 = 2
price_2 = 10
if price_1 >=4 or price_2 <=11: //虽然price_1的值为2,小于4,但是price_2 <=11 这个条件成立,因此整个条件测试通过,python执行print语句
    print("well done")
//输出结果为:
well done

测试一个条件,就使用if-else或者if-elif-else语句,这两个语句仅适用于只有一个条件满足的情况,遇到通过了的测试后,python就跳过余下的测序。

例子1 if-else 语句, 这个语法只检查两个情形

age = 8
if age >=6:  //测试通过,执行print代码块
    print("you could enter the primary school now") 
else:
    print("You are not old enough to go to school")
//输出结果为:
you could enter the primary school now
age = 5
if age >=6: //测试不通过,python将会执行else后面的代码块
    print("you could enter the primary school now")
else:
    print("You are not old enough to go to school")
//输出结果为:
You are not old enough to go to school

例子 2 if-elif-else语句, 这个语法可以执行超过两个的情形,可以根据需要使用任意数量的elif代码块

age = 17
if age <4:
    price = 0
elif age <18:
    price = 7
else:
    price = 10
print("You need to pay RMB " + str(age) + ".")
//输出结果为:
You need to pay RMB 17.

测试多个条件,就使用一系列if语句,不包含elif 和else语句

favoriate_countries = ["China", "Poland", "Greece", "Germany", "Norway"]
if "China" in favoriate_countries: //通过测试
    print("I will go to china")
if "Poland" in favoriate_countries:  //通过测试
    print("I will go to poland")
if "sweden" in favoriate_countries:  //不通过测试
    print("I will go to sweden")
if "Norway" in favoriate_countries:  //通过测试
    print("I will go to norway too. ")
//输出结果为:
I will go to china
I will go to poland
I will go to norway too.

确定列表不是空的

favoriate_countries = [] //创建一个空列表
if favoriate_countries: //if语句中用列表名在条件表达式中时,python将在列表至少包含一个元素时返回True,并在列表为空时返回False,由于列表为空,因此将实行else语块代码。 
    for favoriate_countrie in favoriate_countries:
        print("I plan to go to " + favoriate_countries + ".")
else:
    print("I will not go anywhere")
//输出结果为:
I will not go anywhere
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值