Python学习之路(5)if 语句

茴香豆 Lv5

本章中,你将学习条件测试,学习简单的if语句,以及创建一系列复杂的if语句来确定当前到底处于什么情形。接下来将if应用于列表,以编写for循环。

if语句

一个简单实例:

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

1.条件测试

  • 等于(==),大于(>),小于(<), 小于等于(<=),大于等于(>=)
  • and、or
  • 检查特定值是否包含在列表中(in)、是否不包含在列表中(not in)
  • bool表达式(True、False)

2.使用if语句处理列表

以披萨店制作披萨为例,每添加一种配料都打印一条消息:

1
2
3
4
5
6
7
8
9
10
11
# usr if check list
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
#output
Adding mushrooms.
Adding green peppers.
Adding extra cheese.

Finished making your pizza!

青椒用光了:

1
2
3
4
5
6
7
8
9
10
11
12
13
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!")
#output
Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.

Finished making your pizza!

判断顾客点的配料列表是否为空:

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

顾客的要求往往五花八门,下面定义两个列表。第一个包含披萨店供应的配料,第二个包含顾客点的配料。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
requested_toppings = ['mushrooms', 'french fires', 'extra cheese']
available_toppings = ['mushrooms', 'olives', 'green peppers',
'pepperoni', 'pineapple', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding " + requested_topping + ".")
else:
print("Sorry, we donot have " + requested_topping + ".")
print("\nFinished making your pizza!")
#output:
Adding mushrooms.
Sorry, we donot have french fires.
Adding extra cheese.

Finished making your pizza!
  • Title: Python学习之路(5)if 语句
  • Author: 茴香豆
  • Created at : 2022-07-01 14:32:05
  • Updated at : 2022-07-01 21:58:08
  • Link: https://hxiangdou.github.io/2022/07/01/Python_5/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
Python学习之路(5)if 语句