📘 Day 10
🎉 本系列为 Python 基础学习,原稿来源于英文项目,大奇主要是对其本地化翻译、逐条验证和补充。此系列适合零基础同学,或仅了解 Python 一点知识,但又没有系统学习的使用者。总之如果你想提升自己的 Python 技能,欢迎加入《挑战 30 天学完 Python》
作者:大奇 MegaQi | Info 签约作者 ,专注测试开发技术实战干货分享,欢迎访问主页长期关注
循环
生活中充满了例行公事。在程序中一样,也要做很多重复的工作。编程语言使用循环处理这些重复任务。Python 编程语言提供以下两种循环:
while
我们使用保留字 while 进行一种循环。在符合给定的条件之内,它会一直重复执行语句块。当条件为false时,代码将跳出循环。
# 语法形式while condition: code goes here
复制代码
举例
count = 0while count < 5: print(count) count = count + 1# 将打印 0 到 4
复制代码
在上边的 while 循环中,当 count 加到 5 的时候条件变成了 false,这时循环停止了。如果想条件不满足的时候执行其他代码块,我们可以使用 else。
# 语法while condition: code goes hereelse: code goes here
复制代码
举例
count = 0while count < 5: print(count) count = count + 1else: print(count)
复制代码
当 count=5 的时条件变为 false,循环停止并执行 else 下语句块。结果最后值 5 被打印出来。
while break
当我们想要跳出或停止循环时,我们使用break。
# 语法while condition: code goes here if another_condition: break
复制代码
实际举例
count = 0while count < 5: print(count) count = count + 1 if count == 3: break
复制代码
上面的 while 循环只打印 0、1、2,但是当它到达 3 时就停止了。
while continue
通过continue语句,我们可以跳过当前迭代,并继续下一个迭代。
# 语法while condition: code goes here if another_condition: continue
复制代码
举例
count = 0while count < 5: if count == 3: continue print(count) count = count + 1
复制代码
以上 while 循环仅打印 0,1,2 和 4(其中 3 被忽略)。
for
另一种循环方式是使用关键词 for 。类似其他语言的 for 循环,但又有一些差异点。Python 中迭代序列可以是 list、tuple、dict、set 或 str。
numbers = [0, 1, 2, 3, 4, 5]for number in numbers: # number是引用列表项的临时名称,仅在此循环内有效 print(number) # 数字将从0到5逐行打印
复制代码
# 拆分python字符串language = 'Python'for letter in language: print(letter)
# 通过下脚标访问打印for i in range(len(language)): print(language[i])
# 以上两个输出均为Python
复制代码
numbers = (0, 1, 2, 3, 4, 5)for number in numbers: print(number)
# 依次换行打印 0-5
复制代码
dict 字典 for 迭代
默认循环字典时候会迭代字典的 key
person = { 'name':'MegaQi', 'age':180, 'country':'China', 'is_marred':True, 'skills':['Java', 'React', 'Node', 'Mysql', 'Python'] }
for key in person: print(key)
复制代码
可以同时循环取得 key 和 value
person = { 'name':'MegaQi', 'skills':['Java', 'React', 'Node', 'Mysql', 'Python'], 'address':{ 'city':'上海', 'code':'021' } }
for key, value in person.items(): print(key, value)
复制代码
it_companies = {'Facebook', 'Google', 'Microsoft', 'Apple', 'IBM', 'Oracle', 'Amazon'}for company in it_companies: print(company)
复制代码
for break
同 while break 相同,如果想停止迭代使用关键词 break。
# 语法形式for iterator in sequence: code goes here if condition: break
复制代码
举例
numbers = (0,1,2,3,4,5)for number in numbers: print(number) if number == 3: break
复制代码
在上面的例子中,循环在达到 3 时执行 break 停止继续迭代。
for continue
同理也可以使用continue忽略本迭代后边操作。
# 语法for iterator in sequence: code goes here if condition: continue
复制代码
举例
numbers = (0, 1, 2, 3, 4, 5)for number in numbers: print(number) if number == 3: continue print('下一个数字将是 ', number + 1) if number != 5 else print("循环结束") # 注意此处使用短条件语句print('循环外部')
复制代码
在上面的例子中,如果数字等于 3,则跳过条件之后的步骤(在循环内部),如果还未完成迭代,则继续执行循环。
范围函数 range
函数 range() 按给参数值返回一个数字列表。函数 range(start, end, step) 有三个参数:开始、结束和增数。默认情况下,它从 0 开始,增量为 1。范围序列至少需要一个参数(end)。它将创建一个范围序列。
lst = list(range(11)) print(lst) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]st = set(range(1, 11)) # 给了两个参数表示开始到结束,默认增长值1print(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}
复制代码
注意 range 第一个参数 start 是包含本身,而第二个参数 end 是不包含本身。
它可以直接应用在 for 循环上
# 使用形式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 = { 'name': 'MegaQi', 'country': 'China', 'is_marred': True, 'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], 'address': { 'city': 'ShangHai', 'code': '021' }}for key in person: if key == 'skills': for skill in person['skills']: print(skill)
复制代码
以上字典中技能是个列表,那增加一个条件判断,当关键词等于 skills 时,增加一个循环打印技能列表。
这里大家可以扩展两点思考:
for else
如果我们想在循环结束时执行逻辑外代码则使用 else。
# 语法形式for iterator in range(start, end, step): do somethingelse: print('The loop ended')
复制代码
实际举例
for number in range(11): print(number) # 打印 0 到 10else: print('迭代停止于:', number)
复制代码
pass
在 python 中,语法冒号后必须要给定执行语句。但有时候我们不希望做任何事情。为了避免语法的错误,使用pass关键词做占位符。
# 输出了寂寞for number in range(6): pass
# 跳过4for number in range(6): if number == 4: pass else: print(number)
复制代码
🌕你实现了一个巨大的里程碑,你是不可阻挡的。继续前进!你 刚刚完成了第 10 天的挑战,你向你的伟大之路前进了 10 步。现在趁热打铁块来巩固下,做些适应性练习吧。
第 10 天练习
练习 1 级
使用 for 循环打印 0-10,然后用 while 实现同样功能
使用 for 循环打印 10-0,然后同样用 while 实现
编写一个打印循环(7 次),输出如下的三角图案:
# ## ### #### ##### ###### #######
复制代码
使用嵌套循环创建如下输出
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
复制代码
利用循环方法打印以下图案:
0 x 0 = 0 1 x 1 = 1 2 x 2 = 4 3 x 3 = 9 4 x 4 = 16 5 x 5 = 25 6 x 6 = 36 7 x 7 = 49 8 x 8 = 64 9 x 9 = 81 10 x 10 = 100
复制代码
使用 for 循环遍历列表['Python', 'Numpy','Pandas','Django', 'Flask'],并打印其项
使用 for 循环 0 到 100,且只打印偶数
使用 for 循环 0 到 100,但只打印奇数
练习 2 级
使用 for 循环从 0 到 100 进行迭代,并输出所有数字的和。
使用 for 循环从 0 到 100 进行迭代,并输出所有偶数和所有奇数的和。
所有偶数的和是2550。所有奇数的总和是2500。
复制代码
🎉 CONGRATULATIONS ! 🎉
github 项目(含参考答案)地址:https://github.com/QiCodeCN/30-Days-Of-Python-zh_CN
如喜欢通过“点赞👍收藏❤️关注➕”鼓励作者大奇
文章中如有错误或疑问欢迎指正和交流。
评论