资料来源于Github项目**30-Days-Of-Python,本文为第十章翻译。**
循环语句
生活中充满了例行公事。在编程中,我们也需要完成很多重复性的任务。为了处理这些任务,编程语言使用循环结构。Python编程语言也提供了以下两种类型的循环结构:
while循环for循环
while循环
我们使用保留字while来创建while循环。它用于重复执行一系列语句,直到满足给定条件为止。当条件变为假时,循环后的代码行将继续执行。
# 语法
while 条件:
代码
示例:
count = 0
while count < 5:
print(count)
count = count + 1
#打印从0到4的代码
在上面的while循环中,当计数器count为5时,条件变为假,循环停止。如果我们想在条件不再为真时运行一段代码块,可以使用else语句。
# 语法
while 条件:
代码
else:
代码
示例:
count = 0
while count < 5:
print(count)
count = count + 1
else:
print(count)
当计数器count为5时,循环条件变为假,循环停止,并执行else语句。因此,5将被打印出来。
break和continue-第一部分
break:当我们想要跳出或停止循环时,我们使用break。
# 语法
while 条件:
代码
if 另一个条件:
break
示例:
count = 0
while count < 5:
print(count)
count = count + 1
if count == 3:
break
上面的while循环仅打印0、1、2,但当它达到3时就停止了。
continue:使用continue语句,我们可以跳过当前迭代,继续执行下一次迭代:
# 语法
while 条件:
代码
if 另一个条件:
continue
示例:
count = 0
while count < 5:
if count == 3:
continue
print(count)
count = count + 1
上面的while循环只打印0、1、2和4(跳过3)。
for循环
使用for关键字可以创建一个for循环,类似于其他编程语言,但语法有些不同。循环用于迭代一个序列(可以是List、Tuple、Dictionary、Set或String)。
List的for循环
# 语法
for 迭代器 in 列表:
代码
示例:
numbers = [0, 1, 2, 3, 4, 5]
for number in numbers: # number是用于引用列表中项的临时名称,仅在此循环内部有效
print(number) # 这段代码将逐行打印数字,从0到5
String的for循环
# 语法
for 迭代器 in 字符串:
代码
示例:
language = 'Python'
for letter in language:
print(letter)
for i in range(len(language)):
print(language[i])
tuple的for循环
# 语法
for 迭代器 in 元组:
代码
示例:
numbers = (0, 1, 2, 3, 4, 5)
for number in numbers:
print(number)
- 使用
Dictionary的for循环,遍历Dictionary时将获得Dictionary的键。
# 语法
for 迭代器 in 字典:
代码
示例:
person = {
'first_name':'Asabeneh',
'last_name':'Yetayeh',
'age':250,
'country':'Finland',
'is_marred':True,
'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address':{
'street':'Space street',
'zipcode':'02210'
}
}
for key in person:
print(key)
for key, value in person.items():
print(key, value) # 这种方式可以同时打印出字典的键和值
Set的for循环
# 语法
for 迭代器 in 集合:
代码
示例:
it_companies = {'Facebook', 'Google', 'Microsoft', 'Apple', 'IBM', 'Oracle', 'Amazon'}
for company in it_companies:
print(company)
b**reak 和 continue - 第二部分**
简单提醒:break:当我们想要在循环完成之前停止循环时,我们使用break。
# 语法
for 迭代器 in 序列:
代码
if 条件:
break
示例:
numbers = (0,1,2,3,4,5)
for number in numbers:
print(number)
if number == 3:
break
在上面的例子中,循环在达到3时停止。
continue:当我们想要跳过循环迭代中的一些步骤时,我们使用continue。
# 语法
for 迭代器 in 序列:
代码
if 条件:
continue
示例:
numbers = (0,1,2,3,4,5)
for number in numbers:
print(number)
if number == 3:
continue
print('Next number should be ', number + 1) if number != 5 else print("loop's end") # 在使用Python的短语法条件语句时,需要同时使用if和else语句。
print('outside the loop')
在上面的示例中,如果数字等于3,则跳过条件后面的步骤(但在循环内部),如果还有迭代,则继续执行循环。
range()函数
range()函数用于生成数字列表。range(start, end, step)函数有三个参数:起始值、结束值和步长。默认情况下,起始值为0,步长为1。range()函数至少需要1个参数(结束值)。使用range()函数创建数字序列:
lst = list(range(11))
print(lst) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
st = set(range(1, 11)) # 当使用 range() 函数时,传入2个参数表示序列的起始和结束值,步长默认为1:
print(st) # {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
lst = list(range(0,11,2))
print(lst) # [0, 2, 4, 6, 8, 10]
st = set(range(0,11,2))
print(st) # {0, 2, 4, 6, 8, 10}
# 语法
for iterator in range(start, end, step):
示例:
for number in range(11):
print(number) # 会输出0到10的数字,不包括11
嵌套循环
我们可以在一个循环内部编写另一个循环,这被称为嵌套循环。
# 语法
for x in y:
for t in x:
print(t)
示例:
person = {
'first_name': 'Asabeneh',
'last_name': 'Yetayeh',
'age': 250,
'country': 'Finland',
'is_marred': True,
'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address': {
'street': 'Space street',
'zipcode': '02210'
}
}
for key in person:
if key == 'skills':
for skill in person['skills']:
print(skill)
for-else
如果我们想在循环结束时执行一些操作,可以使用 else 语句。
# 语法
for 迭代器 in range(开始, 结束, 步长):
代码
else:
print('The loop ended')
示例:
for number in range(11):
print(number) # 会输出0到10的数字,不包括11
else:
print('The loop stops at', number)
pass
在 Python 中,当需要一个语句(在冒号后)但我们不想在那里执行任何代码时,我们可以使用 pass 关键字来避免错误。同时,我们还可以将 pass 用作占位符,用于未来的语句。
示例:
for number in range(6):
pass
评论区