The fifth chapter if statement

5.1 Test Conditions

note:

  • Python is case sensitive while checking for equality, for example, two different values ​​can be considered equal to one case
  • If the case does not matter, but only want to check the value of the variable, the variable value can be converted to lower case, then compared (Lower Method ())

5.2 Check

  • Use keywords and checking multiple conditions
  • Use keywords or check a plurality of conditions
  • Use keywords in check for a specific value is contained in the list
  • Use Keywords not in check whether a value is not included in the list

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?

   

   

Guess you like

Origin www.cnblogs.com/lovely-bones/p/10979054.html