Python学习笔记(四)——if语句

一 1个简单的示例

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

输出结果为:
BWN
Audi
Subaru
Toyota

二 条件测试

每条if核心都是一个值为true或False的表达式,这种表达式被称为条件测试。

1.检查是否相等

大多数条件测试都是将一个变量的值和一个特定值相比最简单的条件测试检查变量的值是否与特定的值相等。

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

Python在检查时区分大小写,两个大小写不同的值会被视为不相等。
当不需要去区分大小写时,可以全部转换为小写:

car = 'Audi'
car.lower() == 'audi'

可在控制台进行验证。

3.检查是否不相等

要判断两个值是否不相等,可以使用到惊叹号加上等号(!=)

4.比较数字

可以在if语句中使用到>,<,>=,<=等等

5.检查多个条件

a.使用and检查多个条件

要检查两个条件是否都为true,可以使用关键字and将两个条件合二为一。为改善可读性,建议把条件放在括号里。

b.使用or检查多个条件

需要多个条件只要其中一个满足,就能通过整个测试。

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

可以使用关键字in,检查特定值是否包含在列表中。

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

可以使用关键字not in,检查特定值是否不在列表中。

8.布尔表达式

布尔表达式时条件测试的别名。结果通常只有True与Flase

下面是笔者所做的一些测试,可方便理解什么是True,Flase

x=['1','2','3']
a='xyz'
b='abc'
c='Xyz'
print('1' in x)
print('2' not in x)
print(a==b)
print(a==c)
print(a.title()==c.title())

输出结果为:
True
False
False
False
True

三 if语句

1.简单的if语句

最简单的if语句只有两行,如果通过了条件测试,则可以执行后续代码。若没有通过,则跳过后续操作。

if conditional_test:
    do something

2.if-else语句

age=17
if age>18:
    print("You are old enough to vote")
else:
    print("You are not old enough to vote")

如果测试结果为True,就执行第一个缩进的语句。如果结果为Flase,则执行else后面的语句。

3.if-elif-else结构

当条件超过两个是时,我们可以使用if-elif-else语句。例如有一家游乐园:

  • 4岁以下免费
  • 4~18岁收费5美元
  • 18岁(含)以上收10美元
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.")

也可以简化该程序:

age = 12
if age < 4:
    price=0
elif age < 18:
    price=5
else:
   price=10
print("Your admission cost is $",price,".")

4.使用多个elif语句

elif语句可以是任意数量。以上一个例题为例:

  • 需要给六十五岁以上的老人打五折
age = 12
if age < 4:
    price=0
elif age < 18:
    price=5
elif age < 65:
    price=10
else:
   price=5
print("Your admission cost is $",price,".")

5.省略else语句

Python并不要求if-else结构中必须有else结构,在某些情况下是可以省略的:

if age < 4:
    price=0
elif age < 18:
    price=5
elif age < 65:
    price=10
elif age>=65:
   price=5
print("Your admission cost is $",price,".")

6.测试多个条件

虽然if-elif-else语句功能强大,但当我们需要检查每一个条件时,应该使用一系列不包含elif与else语句简单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!")

四 使用if语句处理列表

1.检查特殊元素

以前面的披萨作为例子,我们给每个配料打印一条消息:

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

当青椒用完了以后,在for循环中加入一个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!

2.确定列表不是空的

此时我们的程序都是假设列表中至少存在一个元素。但需要检测列表是否为空很重要:
当顾客配料列表为空的时候:

requested_toppings = []
if requested_toppings:
    for requested_topping in requested_toppings:
        print("Adding "+requested_topping+'.')
else:
    print("Are you sure you want a plain pizza")
print("\nFinished making your pizza!")

3.使用多个列表

当存在不在同一个列表的元素时,就会使用到关键字in了。比如,当顾客点披萨时要了一份薯条时,我们应该怎么处理:

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

我们需要检查第一个列表是否包含了第二个列表中的元素,再决定是否输出。

五 设置if语句的格式

在诸如 == 、 >= 和 <= 等比较运算符两边各添加一个空格,方便阅读。

猜你喜欢

转载自blog.csdn.net/weixin_51871724/article/details/120975029