第五章 if语句

5.1 条件测试

注意:

  • 在Python中检查是否相等时区分大小写, 例如, 两个大小写不同的值会被视为不相等
  • 如果大小写无关紧要, 而只想检查变量的值, 可将变量的值转换为小写, 再进行比较(方法lower())

5.2 检查

  • 使用关键词and检查多个条件
  • 使用关键词or检查多个条件
  • 使用关键词in检查特定值是否包含在列表中
  • 使用关键词not in检查特定值是否不包含在列表中

01 # and

02 age=20

03 if age>=12 and age<=18:

04 print("teenager");

05 else:

06 print("not a teenager");

07

08 # or

09 age1=10

10 if age1<12 or age1>60:

11 print("child or a senior");

12

13 # in

14 banned_users = ['andrew', 'carolina', 'david']

15 user = 'marie'

16 if user not in banned_users:

17 print(user.title() + ", you can post a response if you wish.")

18

19 cars = ['audi', 'bmw', 'subaru', 'toyota']

20 for car in cars:

21 if car == 'bmw':

22 print(car.upper())

23 else:

24 print(car.title())

>>>

not a teenager

child or a senior

Marie, you can post a response if you wish.

Audi

BMW

Subaru

Toyota

5.3 if-elif-else结构

01 age = 12

02 if age < 4:

03 price = 0

04 elif age < 18:

05 price = 5

06 else:

07 price = 10

08 print("Your admission cost is $" + str(price) + ".")

>>>

Your admission cost is $5.

5.4 确定列表非空

  • 让用户来提供存储在列表中的信息, 因此不能再假设循环运行时列表不是空的。 有鉴于此, 在运行for 循环前确定列表是否为空很重要。
  • Python将在列表至少包含一个元素时返回True , 并在列表为空时返回False 。

01 requested_toppings = []

02 if requested_toppings:

03 for requested_topping in requested_toppings:

04 print("Adding " + requested_topping + ".")

05 print("\nFinished making your pizza!")

06 else:

07 print("Are you sure you want a plain pizza?")

>>>

Are you sure you want a plain pizza?

   

   

猜你喜欢

转载自www.cnblogs.com/lovely-bones/p/10979054.html