Python 基础三之条件语句和循环
今天学习Python 的条件语句与循环。
一、条件语句
If 语句
if 语句是是一种条件语句,根据条件为 true 还是 false 运行或执行相关代码。下面是一个简单的示例:
if phone_balance < 5:
phone_balance += 10
bank_balance -= 10
我们来详细讲解下每部分。
- 1、if 语句以关键字 if 开始,然后是要检查的条件,在此例中是 phone_balance < 5,接着是英文冒号。条件用布尔表达式指定,结果为 True 或 False。
- 2、这行之后是一个条件为 true 时将执行的缩进代码块。在此例中,仅在 phone_balance 小于 5 时才执行使 phone_balance 递增和使 bank_balance 递减的行。如果不小于 5,这个 if 块中的代码将被跳过。
If、Elif、Else
除了 if 条件之外,if 语句经常还会使用另外两个可选条件。例如:
if season == 'spring':
print('plant the garden!')
elif season == 'summer':
print('water the garden!')
elif season == 'fall':
print('harvest the garden!')
elif season == 'winter':
print('stay indoors!')
else:
print('unrecognized season')
缩进
As you have just seen, indentation is important. 正如上个例子中看到的,缩进很重要。
一些其他语言使用花括号来表示代码块从哪开始,从哪结束。在 Python 中,我们使用缩进来封装代码块。例如,if
语句使用缩进告诉 Python 哪些代码位于不同条件语句里面,哪些代码位于外面。
在 Python 中,缩进通常是四个空格一组。请严格遵守该惯例,因为更改缩进会完全更改代码的含义。如果你是 Python 程序员团队的成员,则所有人都必须遵守相同的缩进惯例!
#First Example - try changing the value of phone_balance
phone_balance = 10
bank_balance = 50
if phone_balance < 10:
phone_balance += 10
bank_balance -= 10
print(phone_balance)
print(bank_balance)
#Second Example - try changing the value of number
number = 145
if number % 2 == 0:
print("Number " + str(number) + " is even.")
else:
print("Number " + str(number) + " is odd.")
#Third Example - try to change the value of age
age = 35
多个条件判断
由于 python 并不支持 switch 语句,所以多个条件判断,只能用 elif 来实现,如果判断需要多个条件需同时判断时,可以使用 or (或),表示两个条件有一个成立时判断条件成功;使用 and (与)时,表示只有两个条件同时成立的情况下,判断条件才成功。
注意下面这种写法在Python中是错误的,并且不能用 &&
只能用 and
# write your if statement here
if points >= 1 && points <= 50:
result = "Congratulations! You won a wooden rabbit!"
正确的:
# write your if statement here
if points >= 1 and points <= 50:
result = "Congratulations! You won a wooden rabbit!"
示例:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 例3:if语句多个条件
num = 9
if num >= 0 and num <= 10: # 判断值是否在0~10之间
print 'hello'
# 输出结果: hello
num = 10
if num < 0 or num > 10: # 判断值是否在小于0或大于10
print 'hello'
else:
print 'undefine'
# 输出结果: undefine
num = 8
# 判断值是否在0~5或者10~15之间
if (num >= 0 and num <= 5) or (num >= 10 and num <= 15):
print 'hello'
else:
print 'undefine'
# 输出结果: undefine
条件布尔表达式
If 语句有时候会使用更加复杂的条件布尔表达式。可能包括多个比较运算符、逻辑运算符,甚至包括算式。例如:
if 18.5 <= weight / height**2 < 25:
print("BMI is considered 'normal'")
if is_raining and is_sunny:
print("Is there a rainbow?")
if (not unsubscribed) and (location == "USA" or location == "CAN"):
print("send email")
对于非常复杂的条件,你可能需要结合使用 and、or 和 not。使用括号可以使运算符组合更清晰。
无论是简单还是复杂的条件,if 语句中的条件都必须是结果为 True 或 False 的布尔表达式,该值决定了 if 语句中的缩进代码块是否执行。
真假值测试
如果我们在if 语句中使用非布尔对象代替布尔表达式,Python 将检查其真假值,判断是否运行缩进代码。默认情况下,Python 中对象的真假值被视为 True,除非在文档中被指定为 False。
以下是在 Python 中被视为 False 的大多数内置对象:
- 定义为 false 的常量:None 和 False
- 任何数字类型的零:0、0.0、0j、Decimal(0)、Fraction(0, 1)
- 空序列和空集合:””、()、[]、{}、set()、range(0)
示例:
errors = 3
if errors:
print("You have {} errors to fix!".format(errors))
else:
print("No errors to fix!")
在上述代码中,errors 的真假值为 True,因为它是非零数字,因此输出了错误消息。这是一个编写 if 语句的简练方式。
示例:
我们首先设置prize = None
,如果得分能够获得奖品,则更新 prize。然后如果有奖品的话,使用 prize 的真假值输出消息,如果没有奖品,则输出另一条消息。
prize = None
if points <= 50:
prize = "a wooden rabbit"
elif 151 <= points <= 180:
prize = "a wafer-thin mint"
elif points >= 181:
prize = "a penguin"
if prize:
result = "Congratulations! You won " + prize + "!"
else:
result = "Oh dear, no prize this time."
print(result)
For循环
Python 有两种类型的循环:for 循环和 while 循环。for
循环用来遍历可迭代对象。
可迭代对象是每次可以返回其中一个元素的对象,包括字符串、列表和元组等序列类型,以及字典和文件等非序列类型。你还可以使用迭代器和生成器定义可迭代对象,我们将在这门课程的稍后阶段详细了解迭代器和生成器。
我们来了解下 for 循环的各个组成部分。请看下面的示例:
# iterable of cities
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
# for loop that iterates over the cities list
for city in cities:
print(city.title())
For 循环的组成部分
- 1、循环的第一行以关键字 for 开始,表示这是一个 for 循环
- 2、然后是 iteration_variable in iterable,表示正在被遍历的是可迭代的对象,并且用迭代变量表示当前正在被处理的可迭代对象的元素。在此示例中,迭代变量 city 在第一次迭代时将是“new york city”,在第二次迭代时将是“mountain view。
- 3、
for
循环头部始终以英文冒号 : 结束。 - 4、
for
循环头部之后的是在此 for 循环的每次迭代时运行的缩进代码块。在此块中,我们可以使用迭代变量访问当前正在被处理的元素的值。 -
你可以随意命名迭代变量。常见模式是为迭代变量和可迭代对象指定相同的名称,但是分别使用单复数形式(例如 'city' 和 'cities)
创建和修改列表
除了从列表中提取信息之外,你还可以使用 for 循环创建和修改列表。你可以在 for 循环的每次迭代时向新列表中添加元素,创建一个列表。如下所示。
# Creating a new list
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
capitalized_cities = []
for city in cities:
capitalized_cities.append(city.title())
range
修改列表稍微复杂些,需要使用新的函数:range()
。
range()
是一个内置函数,用于创建不可变的数字序列。它有三个参数,必须都为整数。
range(start=0, stop, step=1)
Start
是该序列的第一个数字,stop比该序列的最后一个数字大 1,step是该序列中每个数字之间的差。如果未指定的话,start默认为 0,step 默认为 1(即上述 =0和 =1)。
- 如果你在
range()
的括号里指定一个参数,它将用作 'stop' 的值,另外两个参数使用默认值。
E.g.list(range(4))
返回[0, 1, 2, 3]
- 如果你在
range()
的括号里指定两个参数,它们将用作 'start' 和 'stop' 的值,'step' 将使用默认值。 E.g.list(range(2, 6))
返回[2, 3, 4, 5]
- 或者你可以为三个参数 'start、stop' 和 'step' 均指定一个值。 E.g.
list(range(1, 10, 2))
返回[1, 3, 5, 7, 9]
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
for index in range(len(cities)):
cities[index] = cities[index].title()
虽然修改列表是 range 函数的一个用途,但是并非只有这一个用途。你将经常使用 range 和 for 循环重复某个操作一定的次数。
for i in range(3):
print("Hello!")
练习
创建用户名
写一个遍历 names
列表以创建 usernames 列表的 for 循环。要为每个姓名创建用户名,使姓名全小写并用下划线代替空格。对以下列表运行 for 循环:
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
应该会创建列表:
usernames = ["joey_tribbiani", "monica_geller", "chandler_bing", "phoebe_buffay"]
结果:
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []
# write your for loop here
for name in names:
new_name = name.lower()
last_name = new_name.replace(" ", "_")
usernames.append(last_name)
print(usernames)
直接写:
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []
for name in names:
usernames.append(name.lower().replace(" ", "_"))
print(usernames)
另一种range简洁写法:
usernames = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
# write your for loop here
for index in range(len(usernames)):
usernames[index] = usernames[index].lower().replace(" ", "_")
print(usernames)
打印:
['joey_tribbiani', 'monica_geller', 'chandler_bing', 'phoebe_buffay']
练习二:
写一个 for 循环,用于遍历字符串列表 tokens 并数一下有多少个 XML 标记。XML 是一种类似于 HTML 的数据语言。如果某个字符串以左尖括号“<”开始并以右尖括号“>”结束,则是 XML 标记。使用 count 记录这种标记的数量。
你可以假设该字符串列表不包含空字符串。
tokens = ['<greeting>', 'Hello World!', '</greeting>']
count = 0
# write your for loop here
for token in tokens:
if token.count('<'):
count += 1
print(count)
严谨写法:
tokens = ['<greeting>', 'Hello World!', '</greeting>']
count = 0
for token in tokens:
if token[0] == '<' and token[-1] == '>':
count += 1
print(count)
为者常成,行者常至
自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)