if语句

一.一个简单示例

  1. cars = ['audi', 'bmw', 'subaru', 'toyota']
  2. for car in cars:
  3. if car == 'bmw':
  4. print(car.upper())
  5. else:
  6. print(car.title())
  1. Audi
  2. BMW
  3. Subaru
  4. Toyota

二.条件测试

1.检查是否相等

  1. >>> car = 'bmw'
  2. >>> car == 'bmw'
  3. True

我们首先使用一个等号将car 的值设置为’bmw’。接下来,使用两个等号(== )检查car 的值是否为’bmw’ 。这个相等运算符在它两边的值相等时返回True ,否则返回False 。在这个示例中,两边的值相等,因此Python返回True 。如果变量car 的值不是’bmw’ ,上述测试将返回False :

  1. >>> car = 'audi'
  2. >>> car == 'bmw'
  3. False

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

  1. >>> car = 'Audi'
  2. >>> car == 'audi'
  3. False
  1. >>> car = 'Audi'
  2. >>> car.lower() == 'audi'
  3. True

3.检查是否不相等

  1. requested_topping = 'mushrooms'
  2. if requested_topping != 'anchovies':
  3. print("Hold the anchovies!")
  1. Hold the anchovies!

4.比较数字

  1. >>> age = 18
  2. >>> age == 18
  3. True
  1. answer = 17
  2. if answer != 42:
  3. print("That is not the correct answer. Please try again!")
  1. That is not the correct answer. Please try again!
  1. >>> age = 19
  2. >>> age < 21
  3. True
  4. >>> age <= 21
  5. True
  6. >>> age > 21
  7. False
  8. >>> age >= 21
  9. False

5.检查多个条件

①使用and检查多个条件

  1. >>> age_0 = 22
  2. >>> age_1 = 18
  3. >>> age_0 >= 21 and age_1 >= 21
  4. False
  5. >>> age_1 = 22
  6. >>> age_0 >= 21 and age_1 >= 21
  7. True

为改善可读性,可将每个测试都分别放在一对括号内,但并非必须这样做。如果你使用括号,测试将类似于下面这样:

  1. (age_0 >= 21) and (age_1 >= 21)

②使用or检查多个条件

  1. >>> age_0 = 22
  2. >>> age_1 = 18
  3. >> age_0 >= 21 or age_1 >= 21
  4. True
  5. >>> age_0 = 18
  6. >>> age_0 >= 21 or age_1 >= 21
  7. False

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

  1. >>> requested_toppings = ['mushrooms', 'onions', 'pineapple']
  2. >>> 'mushrooms' in requested_toppings
  3. True
  4. >>> 'pepperoni' in requested_toppings
  5. False

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

  1. banned_users = ['andrew', 'carolina', 'david']
  2. user = 'marie'
  3. if user not in banned_users:
  4. print(user.title() + ", you can post a response if you wish.")
  1. Marie, you can post a response if you wish.

8.布尔表达式

布尔值通常用于记录条件,如游戏是否正在运行,或用户是否可以编辑网站的特定内容:

  1. game_active = True
  2. can_edit = False

在跟踪程序状态或程序中重要的条件方面,布尔值提供了一种高效的方式。

三.if语句

1.简单的if语句

  1. if conditional_test:
  2. do something

在第1行中,可包含任何条件测试,而在紧跟在测试后面的缩进代码块中,可执行任何操作。如果条件测试的结果为True,Python就会执行紧跟在if语句后面的代码;否则Python将忽略这些代码。

  1. age = 19
  2. if age >= 18:
  3. print("You are old enough to vote!")
  4. print("Have you registered to vote yet?")
  1. You are old enough to vote!
  2. Have you registered to vote yet?

如果age 的值小于18,这个程序将不会有任何输出。

2.if-else语句

  1. age = 17
  2. if age >= 18:
  3. print("You are old enough to vote!")
  4. print("Have you registered to vote yet?")
  5. else:
  6. print("Sorry, you are too young to vote.")
  7. print("Please register to vote as soon as you turn 18!")
  1. Sorry, you are too young to vote.
  2. Please register to vote as soon as you turn 18!

3.if-elif-else结构

  1. age = 12
  2. if age < 4:
  3. print("Your admission cost is $0.")
  4. elif age < 18:
  5. print("Your admission cost is $5.")
  6. else:
  7. print("Your admission cost is $10."
  1. Your admission cost is $5.

4.使用多个elif代码块

  1. age = 12
  2. if age < 4:
  3. price = 0
  4. elif age < 18:
  5. price = 5
  6. elif age < 65:
  7. price = 10
  8. else:
  9. price = 5
  10. print("Your admission cost is $" + str(price) + ".")

5.省略else代码块

  1. age = 12
  2. if age < 4:
  3. price = 0
  4. elif age < 18:
  5. price = 5
  6. elif age < 65:
  7. price = 10
  8. elif age >= 65:
  9. price = 5
  10. print("Your admission cost is $" + str(price) + ".")

6.测试多个条件

  1. requested_toppings = ['mushrooms', 'extra cheese']
  2. if 'mushrooms' in requested_toppings:
  3. print("Adding mushrooms.")
  4. if 'pepperoni' in requested_toppings:
  5. print("Adding pepperoni.")
  6. if 'extra cheese' in requested_toppings:
  7. print("Adding extra cheese.")
  8. print("\nFinished making your pizza!")
  1. Adding mushrooms.
  2. Adding extra cheese.
  3. Finished making your pizza!

如果像下面这样转而使用if-elif-else 结构,代码将不能正确地运行,因为有一个测试通过后,就会跳过余下的测试:

  1. requested_toppings = ['mushrooms', 'extra cheese']
  2. if 'mushrooms' in requested_toppings:
  3. print("Adding mushrooms.")
  4. elif 'pepperoni' in requested_toppings:
  5. print("Adding pepperoni.")
  6. elif 'extra cheese' in requested_toppings:
  7. print("Adding extra cheese.")
  8. print("\nFinished making your pizza!")
  1. Adding mushrooms.
  2. Finished making your pizza!

四.使用if语句处理列表

1.检查特殊元素

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

然而,如果比萨店的青椒用完了,该如何处理呢?为妥善地处理这种情况,可在for 循环中包含一条if语句:

  1. requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
  2. for requested_topping in requested_toppings:
  3. if requested_topping == 'green peppers':
  4. print("Sorry, we are out of green peppers right now.")
  5. else:
  6. print("Adding " + requested_topping + ".")
  7. print("\nFinished making your pizza!")
  1. Adding mushrooms. Sorry, we are out of green peppers right now.
  2. Adding extra cheese.
  3. Finished making your pizza!

2.确定列表不是空的

  1. requested_toppings = []
  2. if requested_toppings:
  3. for requested_topping in requested_toppings:
  4. print("Adding " + requested_topping + ".")
  5. print("\nFinished making your pizza!")
  6. else:
  7. print("Are you sure you want a plain pizza?")
  1. Are you sure you want a plain pizza?

3.使用多个列表

  1. available_toppings = ['mushrooms', 'olives', 'green peppers',
  2. 'pepperoni', 'pineapple', 'extra cheese']
  3. requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
  4. for requested_topping in requested_toppings:
  5. if requested_topping in available_toppings:
  6. print("Adding " + requested_topping + ".")
  7. else:
  8. print("Sorry, we don't have " + requested_topping + ".")
  9. print("\nFinished making your pizza!")
  1. Adding mushrooms.
  2. Sorry, we don't have french fries.
  3. Adding extra cheese.
  4. Finished making your pizza!

while循环

一.while循环简介

for 循环用于针对集合中的每个元素都一个代码块,而while 循环不断地运行,直到指定的条件不满足为止。

1.使用while循环

  1. current_number = 1
  2. while current_number <= 5:
  3. print(current_number)
  4. current_number += 1
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5

2.让用户选择何时退出

  1. prompt = "\nTell me something, and I will repeat it back to you:"
  2. prompt += "\nEnter 'quit' to end the program. "
  3. message = ""
  4. while message != 'quit':
  5. message = input(prompt)
  6. print(message)

3.使用标志

  1. prompt = "\nTell me something, and I will repeat it back to you:"
  2. prompt += "\nEnter 'quit' to end the program. "
  3. active = True
  4. while active:
  5. message = input(prompt)
  6. if message == 'quit':
  7. active = False
  8. else:
  9. print(message)

4.使用break退出循环

  1. prompt = "\nPlease enter the name of a city you have visited:"
  2. prompt += "\n(Enter 'quit' when you are finished.) "
  3. while True:
  4. city = input(prompt)
  5. if city == 'quit':
  6. break
  7. else:
  8. print("I'd love to go to " + city.title() + "!")
  1. Please enter the name of a city you have visited:
  2. (Enter 'quit' when you are finished.) New York
  3. I'd love to go to New York!
  4. Please enter the name of a city you have visited:
  5. (Enter 'quit' when you are finished.) San Francisco
  6. I'd love to go to San Francisco!
  7. Please enter the name of a city you have visited:
  8. (Enter 'quit' when you are finished.) quit

5.在循环中使用continue

  1. current_number = 0
  2. while current_number < 10:
  3. current_number += 1
  4. if current_number % 2 == 0:
  5. continue
  6. print(current_number)
  1. 1
  2. 3
  3. 5
  4. 7
  5. 9

6.避免无限循环

  1. x = 1
  2. while x <= 5:
  3. print(x)
  4. x += 1

但如果你像下面这样不小心遗漏了代码行x += 1 ,这个循环将没完没了地运行

  1. # 这个循环将没完没了地运行!
  2. x = 1
  3. while x <= 5:
  4. print(x)
  1. 1
  2. 1
  3. 1
  4. 1
  5. --snip-