菜鸟教程 -- 学的不仅是技术,更是梦想!

Python 3 教程
Python3 教程 Python3 简介 Python3 环境搭建 Python3 VScode Python3 基础语法 Python3 基本数据类型 Python3 数据类型转换 Python3 解释器 Python3 注释 Python3 运算符 Python3 数字(Number) Python3 字符串 Python3 列表 Python3 元组 Python3 字典 Python3 集合 Python3 条件控制 Python3 循环语句 Python3 编程第一步 Python3 推导式 Python3 迭代器与生成器 Python3 with Python3 函数 Python3 lambda Python3 装饰器 Python3 数据结构 Python3 模块 Python __name__ Python3 输入和输出 Python3 File Python3 OS Python3 错误和异常 Python3 面向对象 Python3 命名空间/作用域 Python 虚拟环境的创建 Python 类型注解 Python3 标准库概览 Python3 实例 Python 测验

Python3 高级教程

Python3 正则表达式 Python3 CGI编程 Python3 MySQL(mysql-connector) Python3 MySQL(PyMySQL) Python3 网络编程 Python3 SMTP发送邮件 Python3 多线程 Python3 XML 解析 Python3 JSON Python3 日期和时间 Python3 内置函数 Python3 MongoDB Python3 urllib Python uWSGI 安装配置 Python3 pip Python3 operator Python math Python requests Python random Python OpenAI Python 有用的资源 Python AI 绘画 Python statistics Python hashlib Python 量化 Python pyecharts Python selenium 库 Python 爬虫 Python Scrapy 库 Python Markdown Python sys 模块 Python Pickle 模块 Python subprocess 模块 Python queue 模块 Python StringIO 模块 Python logging 模块 Python datetime 模块 Python re 模块 Python csv 模块 Python threading 模块 Python asyncio 模块 Python PyQt Python for 循环 Python while 循环
(追記) (追記ここまで)

Python3 循环语句

本章节将为大家介绍 Python 循环语句的使用。

Python 中的循环语句有 for 和 while。

Python 循环语句的控制结构图如下所示:

循环控制关键字与方法

关键字 / 函数 说明 示例
for 迭代循环,用于遍历序列或可迭代对象 for i in list:
while 条件循环,条件为 True 时持续执行 while x > 0:
break 立即终止当前循环 break
continue 跳过本次循环剩余代码,进入下一次迭代 continue
else(循环) 循环正常结束(未被 break)时执行 for i in range(3): ... else: ...
pass 循环中的占位语句(空操作) for i in range(5): pass
range() 生成整数序列,常与 for 循环配合使用 range(0, 5)
enumerate() 遍历时同时获取索引和值 for i, v in enumerate(list):

while 循环

Python 中 while 语句的一般形式:

while 判断条件(condition):
 执行语句(statements)……

执行流程图如下:

执行 Gif 演示:

同样需要注意冒号和缩进。另外,在 Python 中没有 do..while 循环。

以下实例使用了 while 来计算 1 到 100 的总和:

实例

#!/usr/bin/env python3n = 100sum = 0counter = 1whilecounter <= n: sum = sum + countercounter += 1print("1 到 %d 之和为: %d" % (n,sum))

执行结果如下:

1 到 100 之和为: 5050

无限循环

我们可以通过设置条件表达式永远不为 false 来实现无限循环,实例如下:

实例

#!/usr/bin/python3var = 1whilevar == 1 : # 表达式永远为 truenum = int(input("输入一个数字 :"))print("你输入的数字是: ", num)print("Good bye!")

执行以上脚本,输出结果如下:

输入一个数字 :5
你输入的数字是: 5
输入一个数字 :

你可以使用 CTRL+C 来退出当前的无限循环。

无限循环在服务器上客户端的实时请求非常有用。

while 循环使用 else 语句

如果 while 后面的条件语句为 false 时,则执行 else 的语句块。

语法格式如下:

while <expr>:
 <statement(s)>
else:
 <additional_statement(s)>

expr 条件语句为 true 则执行 statement(s) 语句块,如果为 false,则执行 additional_statement(s)。

循环输出数字,并判断大小:

实例

#!/usr/bin/python3count = 0whilecount < 5: print(count, " 小于 5")count = count + 1else: print(count, " 大于或等于 5")

执行以上脚本,输出结果如下:

0 小于 5
1 小于 5
2 小于 5
3 小于 5
4 小于 5
5 大于或等于 5

简单语句组

类似 if 语句的语法,如果你的 while 循环体中只有一条语句,你可以将该语句与 while 写在同一行中, 如下所示:

实例

#!/usr/bin/pythonflag = 1while(flag): print('欢迎访问菜鸟教程!')print("Good bye!")

注意:以上的无限循环你可以使用 CTRL+C 来中断循环。

执行以上脚本,输出结果如下:

欢迎访问菜鸟教程!
欢迎访问菜鸟教程!
欢迎访问菜鸟教程!
欢迎访问菜鸟教程!
欢迎访问菜鸟教程!
……

for 语句

Python for 循环可以遍历任何可迭代对象,如一个列表或者一个字符串。

for循环的一般格式如下:

for <variable> in <sequence>: <statements> else: <statements>

流程图:

Python for 循环实例:

实例

#!/usr/bin/python3sites = ["Baidu", "Google","Runoob","Taobao"]forsiteinsites: print(site)

以上代码执行输出结果为:

Baidu
Google
Runoob
Taobao

也可用于打印字符串中的每个字符:

实例

#!/usr/bin/python3word = 'runoob'forletterinword: print(letter)

以上代码执行输出结果为:

r
u
n
o
o
b

整数范围值可以配合 range() 函数使用:

实例

#!/usr/bin/python3# 1 到 5 的所有数字:fornumberinrange(1, 6): print(number)

以上代码执行输出结果为:

1
2
3
4
5

for...else

在 Python 中,for...else 语句用于在循环结束后执行一段代码。

语法格式如下:

for item in iterable:
 # 循环主体
else:
 # 循环结束后执行的代码

当循环执行完毕(即遍历完 iterable 中的所有元素)后,会执行 else 子句中的代码,如果在循环过程中遇到了 break 语句,则会中断循环,此时不会执行 else 子句。

实例

for x in range(6):
print(x)
else:
print("Finally finished!")

执行脚本后,输出结果为:

0
1
2
3
4
5
Finally finished!

以下 for 实例中使用了 break 语句,break 语句用于跳出当前循环体,不会执行 else 子句:

实例

#!/usr/bin/python3sites = ["Baidu", "Google","Runoob","Taobao"]forsiteinsites: ifsite == "Runoob": print("菜鸟教程!")breakprint("循环数据 " + site)else: print("没有循环数据!")print("完成循环!")

执行脚本后,在循环到 "Runoob"时会跳出循环体:

循环数据 Baidu
循环数据 Google
菜鸟教程!
完成循环!

range() 函数

如果你需要遍历数字序列,可以使用内置 range() 函数。它会生成数列,例如:

实例

>>>foriinrange(5): ... print(i) ... 01234

你也可以使用 range() 指定区间的值:

实例

>>>foriinrange(5,9) : print(i)5678 >>>

也可以使 range() 以指定数字开始并指定不同的增量(甚至可以是负数,有时这也叫做'步长'):

实例

>>>foriinrange(0, 10, 3) : print(i)0369 >>>

负数:

实例

>>>foriinrange(-10, -100, -30) : print(i) -10 -40 -70 >>>

您可以结合 range() 和 len() 函数以遍历一个序列的索引,如下所示:

实例

>>>a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ'] >>> foriinrange(len(a)): ... print(i, a[i]) ... 0Google1Baidu2Runoob3Taobao4QQ >>>

还可以使用 range() 函数来创建一个列表:

实例

>>>list(range(5))[0, 1, 2, 3, 4] >>>

更多关于 range() 函数用法参考:https://www.runoob.com/python3/python3-func-range.html


break 和 continue 语句及循环中的 else 子句

break 执行流程图:

continue 执行流程图:

while 语句代码执行过程:

for 语句代码执行过程:

break 语句可以跳出 for 和 while 的循环体。如果你从 for 或 while 循环中终止,任何对应的循环 else 块将不执行。

continue 语句被用来告诉 Python 跳过当前循环块中的剩余语句,然后继续进行下一轮循环。

实例

while 中使用 break:

实例

n = 5
while n > 0:
n -= 1
if n == 2:
break
print(n)
print('循环结束。')

输出结果为:

4
3
循环结束。

while 中使用 continue:

实例

n = 5
while n > 0:
n -= 1
if n == 2:
continue
print(n)
print('循环结束。')

输出结果为:

4
3
1
0
循环结束。

更多实例如下:

实例

#!/usr/bin/python3forletterin'Runoob': # 第一个实例ifletter == 'b': breakprint('当前字母为 :', letter)var = 10# 第二个实例whilevar > 0: print('当前变量值为 :', var)var = var -1ifvar == 5: breakprint("Good bye!")

执行以上脚本输出结果为:

当前字母为 : R
当前字母为 : u
当前字母为 : n
当前字母为 : o
当前字母为 : o
当前变量值为 : 10
当前变量值为 : 9
当前变量值为 : 8
当前变量值为 : 7
当前变量值为 : 6
Good bye!

以下实例循环字符串 Runoob,碰到字母 o 跳过输出:

实例

#!/usr/bin/python3forletterin'Runoob': # 第一个实例ifletter == 'o': # 字母为 o 时跳过输出continueprint('当前字母 :', letter)var = 10# 第二个实例whilevar > 0: var = var -1ifvar == 5: # 变量为 5 时跳过输出continueprint('当前变量值 :', var)print("Good bye!")

执行以上脚本输出结果为:

当前字母 : R
当前字母 : u
当前字母 : n
当前字母 : b
当前变量值 : 9
当前变量值 : 8
当前变量值 : 7
当前变量值 : 6
当前变量值 : 4
当前变量值 : 3
当前变量值 : 2
当前变量值 : 1
当前变量值 : 0
Good bye!

循环语句可以有 else 子句,它在穷尽列表(以for循环)或条件变为 false (以while循环)导致循环终止时被执行,但循环被 break 终止时不执行。

如下实例用于查询质数的循环例子:

实例

#!/usr/bin/python3forninrange(2, 10): forxinrange(2, n): ifn % x == 0: print(n, '等于', x, '*', n//x)breakelse: # 循环中没有找到元素print(n, ' 是质数')

执行以上脚本输出结果为:

2 是质数
3 是质数
4 等于 2 * 2
5 是质数
6 等于 2 * 3
7 是质数
8 等于 2 * 4
9 等于 3 * 3

pass 语句

Python pass是空语句,是为了保持程序结构的完整性。

pass 不做任何事情,一般用做占位语句,如下实例

实例

>>>whileTrue: ... pass# 等待键盘中断 (Ctrl+C)

最小的类:

实例

>>>classMyEmptyClass: ... pass

以下实例在字母为 o 时 执行 pass 语句块:

实例

#!/usr/bin/python3forletterin'Runoob': ifletter == 'o': passprint('执行 pass 块')print('当前字母 :', letter)print("Good bye!")

执行以上脚本输出结果为:

当前字母 : R
当前字母 : u
当前字母 : n
执行 pass 块
当前字母 : o
执行 pass 块
当前字母 : o
当前字母 : b
Good bye!

if None:
 print("Hello")
for i in [1, 0]:
 print(i+1)
i = sum = 0
while i <= 4: sum += i i = i+1 print(sum) 
while 4 == 4:
 print('4')
for char in 'PYTHON STRING':
 if char == ' ':
 break
 print(char, end='')
 
 if char == 'O':
 continue
AI 思考中...

17 篇笔记 写笔记

  1. #0
    227

    使用内置 enumerate 函数进行遍历:

    for index, item in enumerate(sequence):
     process(index, item)
    

    实例

    >>> sequence = [12, 34, 34, 23, 45, 76, 89]
    >>> for i, j in enumerate(sequence):
    ... print(i, j)
    ... 
    0 12
    1 34
    2 34
    3 23
    4 45
    5 76
    6 89
    
    9年前 (2017年02月27日)
  2. #0

    夏木研

    104***[email protected]

    59

    for 循环 1-100 所有整数的和

    #!/usr/bin/env python3
    n = 0
    sum = 0
    for n in range(0,101):# n 范围 0-100
     sum += n
    print(sum)
    

    夏木研

    104***[email protected]

    9年前 (2017年06月14日)
  3. #0

    zero

    562***[email protected]

    118

    使用循环嵌套来实现99乘法法则:

    #!/usr/bin/python3
    #外边一层循环控制行数
    #i是行数
    i=1
    while i<=9:
     #里面一层循环控制每一行中的列数
     j=1
     while j<=i:
     mut =j*i
     print("%d*%d=%d"%(j,i,mut), end=" ")
     j+=1
     print("")
     i+=1
    

    zero

    562***[email protected]

    9年前 (2017年06月19日)
  4. #0

    Micachen

    811***[email protected]

    32

    for 循环的嵌套使用实例:

    #!/usr/bin/python3
    for i in range(1,6):
     for j in range(1, i+1):
     print("*",end='')
     print('\r')

    输出结果:

    *
    **
    ***
    ****
    *****

    Micachen

    811***[email protected]

    9年前 (2017年07月10日)
  5. #0

    payboy

    jk@***.com

    248

    1-100 的和:

    >>> sum(range(101))
    5050

    payboy

    jk@***.com

    9年前 (2017年08月02日)
  6. #0

    Try

    910***[email protected]

    137

    while 循环语句和 for 循环语句使用 else 的区别:

    • 1、如果 else 语句和 while 循环语句一起使用,则当条件变为 False 时,则执行 else 语句。
    • 2.如果 else 语句和 for 循环语句一起使用,else 语句块只在 for 循环正常终止时执行!

    Try

    910***[email protected]

    9年前 (2017年09月12日)
  7. #0

    在哪里学习就在哪里分享

    dre***[email protected]

    121

    关于pass的作用:

    pass只是为了防止语法错误。

    if a>1:
     pass #如果没有内容,可以先写pass,但是如果不写pass,就会语法错误

    pass就是一条空语句。在代码段中或定义函数的时候,如果没有内容,或者先不做任何处理,直接跳过,就可以使用pass。

    在哪里学习就在哪里分享

    dre***[email protected]

    9年前 (2017年11月18日)
  8. #0

    若能绽放光芒

    740***[email protected]

    38
    #十进制转化
    while True:
     number = input('请输入一个整数(输入Q退出程序):') 
     if number in ['q','Q']:
     break #如果输入的是q或Q,结束退出
     elif not number.isdigit():
     print('您的输入有误!只能输入整数(输入Q退出程序)!请重新输入')
     continue #如果输入的数字不是十进制,结束循环,重新开始
     else :
     number = int(number)
     print('十进制 --> 十六进制 :%d -> 0x%x' %(number,number))
     print('十进制 --> 八进制 :%d -> 0o%o' %(number,number))
     print('十进制 --> 二进制 :%d ->'%number,bin(number))

    若能绽放光芒

    740***[email protected]

    9年前 (2017年12月15日)
  9. #0

    HantCoCo

    zco***@163.com

    77

    冒泡排序,python 版本

    解析:很经典的排序方式,从数组中的第0个元素开始,与后面一个元素进行比较,如果前面的元素大于后面的元素,就调换位置,循环到最后(即:a0与a1比较得到结果后,a1与a2比较...),最大的元素被换到数组最末尾,剔除掉最后一个元素,在余下的数组元素中进行上述操作,到最后,整个数组呈现从小到大的排序

    # python 冒泡排序
    def paixu(li) :
     max = 0
     for ad in range(len(li) - 1):
     for x in range(len(li) - 1 - ad):
     if li[x] > li[x + 1]:
     max = li[x]
     li[x] = li[x + 1]
     li[x + 1] = max
     else:
     max = li[x + 1]
     print(li)
    paixu([41,23344,9353,5554,44,7557,6434,500,2000])

    HantCoCo

    zco***@163.com

    9年前 (2018年02月05日)
  10. #0

    jason

    598***[email protected]

    46

    猜拳小游戏

    import random
    while 1:
     s=int(random.randint(1,3))
     if s==1:
     ind="石头"
     elif s==2:
     ind="剪刀"
     elif s==3:
     ind="布" 
     m=input('输入石头,剪刀,布,输入end结束游戏:')
     
     blist=['石头','剪刀','布']
     
     if(m not in blist) and (m!='end'):
     print("输入错误,重试:")
     elif(m=='end')and(m not in blist):
     print(ind)
     print("\n游戏退出")
     break
     elif m==ind:
     print("平")
     elif (m == '石头' and ind =='剪刀') or (m == '剪刀' and ind =='布') or (m == '布' and ind =='石头'):
     print ("电脑出了: " + ind +",你赢了!")
     else:
     print ("电脑出了: " + ind +",你输了!")

    jason

    598***[email protected]

    8年前 (2018年07月16日)
  11. #0

    sprinkle

    117***[email protected]

    30

    原九九乘法表逆时针输出:

    <pre>for i in range(9,0,-1):
     for j in range (1,i):
     print("\t",end="")
     for k in range (i,10):
     print("%dx%d=%d" % (i,k,k*i), end="\t")
     print()

    sprinkle

    117***[email protected]

    8年前 (2018年07月21日)
  12. #0

    sprinkle

    117***[email protected]

    38

    彩票游戏

    import random
    t1="开始游戏"
    t2="结束游戏"
    print(t1.center(50,"*"))
    data1=[]
    money=int(input("输入投入的金额:"))
    print("你现在余额为:%d元"%money)
    while 1:
     for i in range(6):
     n = random.choice([0, 1])
     data1.append(n)
     if money<2:
     print("你的余额不足,请充值")
     m=input("输入投入的金额:")
     if int(m)==0:
     break
     else:
     money=int(m)
     while 1:
     j=int(input("输入购买彩票数量"))
     if money-j*2<0:
     print("购买后余额不足,请重新输入")
     else:
     money = money - j * 2
     print("你现在余额为:%d元" % money)
     break
     print("提示:中奖数据有六位数,每位数为0或者1")
     n2=input("请猜测中奖数据:(输入的数字为0或1)")
     print(str(data1))
     f=[]
     for x in n2:
     f.append(x)
     f1 = str(f)
     f2 = f1.split("'")
     f3 = "".join(f2)
     print("你猜测的数据为:", f3)
     if f3==str(data1):
     print("中奖数字为:",data1)
     print("恭喜你中大奖啦")
     money=money+j*100
     print("你现在余额为:%d元" % money)
     else:
     print("中奖数字为:", data1)
     print("没有中奖,请继续加油")
     con = input("请问还要继续么?结束请输入no,继续请任意输入字符:")
     if con=="no":
     break
     data1=[]
    print(t2.center(50,"*"))
    print("你的余额为:%d元"%money)

    sprinkle

    117***[email protected]

    8年前 (2018年07月21日)
  13. #0

    dzr

    lei***[email protected]

    27

    生成直观的九连环解法:

    #!/usr/bin/python
    x = ["-θ","-θ","-θ","-θ","-θ","-θ","-θ","-θ","-θ"]
    y = ["—","—","—","—","—","—","—","—","—"]
    def down(n, l): #拆解
     v = len(l) #计算数列个数用于改变数列对应位置
     if n>2:
     down(n-2, l) #拆下n-2的环
     l[v-n] = "—" #将v-n位"-θ"改为"—" 表示拆下
     for x in l: #输出列表每一个元素
     print(x,end=' ')
     print() #换行
     up(n-2, l) #装上n-2位
     down(n-1, l)#拆下n-1位, 后面同理
     if n==2:
     l[v-2], l[v-1] ="—","—"
     for x in l:
     print(x,end=' ')
     print()
     if n<2:
     l[v-1] = "—"
     for x in l:
     print(x,end=' ')
     print()
    def up(n, l):
     v = len(l)
     if n>2:
     up(n-1, l)
     down(n-2, l)
     l[v-n] = "-θ"
     for x in l:
     print(x,end=' ')
     print()
     up(n-2, l)
     if n==2:
     l[v-2], l[v-1] = "-θ","-θ"
     for x in l:
     print(x,end=' ')
     print()
     if n<2:
     l[v-1] ="-θ"
     for x in l:
     print(x,end=' ')
     print()
    print("拆解\n")
    for i in x:
     print(i,end=' ')
    print()
    down(9, x)
    print('---------------------------------\n','装上\n')
    for i in y:
     print(i,end=' ')
    print()
    up(9, y)
    print("结束")

    九连环拆解,递归算法

     def down(n):
     if n>2:
     down(n-2)
     print('卸下',n,'环')
     up(n-2)
     down(n-1)
     if n==2:
     print('卸下 {},{} 环'.format(n,n-1)) 
     if n<2:
     print('卸下',n,'环') 
     
    def up(n):
     if n>2:
     up(n-1)
     down(n-2)
     print("装上",n,"环")
     up(n-2)
     if n==2:
     print("装上 %d,%d 环" % (n,n-1))
     
     if n<2:
     print("装上",n,"环")
    print("拆解")
    down(2)
    print('---------------------------------\n','装上')
    up(3)
    print("结束")

    dzr

    lei***[email protected]

    8年前 (2018年09月17日)
  14. #0

    Yota Togashi

    116***[email protected]

    21

    选择排序python版:

    a=[1,5,4,2,2,21,12,7,0]
    b=list(set(a)) # 建立新的列表,嵌套的是集合(除去冗余元素并自动排序)
    c=[] # 建立空列表,用来存放选择排序的数据
    for j in b: #集合列表中选择元素
     for i in a: #列表中选择元素,
     if i ==j:
     c.append(i)
    print(c)
    '''
    我输入的列表元素集合有:1,2,4,5,12,21(已排好序并除去冗余)
    其中我依次选择集合中的各个数据,与原来列表的元素相比
    如果相等,我就把a集合的相对应的数据存到空列表里
    '''

    当然,有一种更方便的排序方式:

    a=[1,2,5,8,3,6,6,6,6,6]
    a.sort()
    print(a)
    Yota Togashi

    Yota Togashi

    116***[email protected]

    8年前 (2018年11月23日)
  15. #0

    哈哈哈

    146***[email protected]

    24

    一个四位数 abcd,满足 abcd * 4 = dcba,求这个数:

    for i in list(range(1000,2500)):
     num2 = i*4
     a = i //1000
     b = i % 1000//100
     c = i % 1000%100//10 
     d = i % 10 
     e = num2 //1000
     f = num2 % 1000//100
     g = num2 % 1000%100//10 
     h = num2 % 10 
     if a==h:
     if b==g:
     if c== f:
     if d==e:
     print(num2,end=',')

    哈哈哈

    146***[email protected]

    7年前 (2019年02月22日)
  16. #0

    大宝v947

    shg***[email protected]

    45

    楼上的 "一个四位数 abcd,满足 abcd * 4 = dcba,求这个数:"

    有另一种处理方式,供参考

    for i in range(1000,9999):
     a = i//1000
     b = i%1000//100
     c = i%1000%100//10
     d = i%1000%100%10
     if i*4 == d*1000+c*100+b*10+a:
     print(i,i,'*',4,'=',d*1000+c*100+b*10+a)
    

    大宝v947

    shg***[email protected]

    6年前 (2021年01月13日)
  17. #0

    Cai0029

    cai***[email protected]

    29

    冒泡排序,python 版本-20220411

    解析:很经典的排序方式,从数组中的第0个元素开始,与后面一个元素进行比较,如果前面的元素大于后面的元素,就调换位置,循环到最后(即:a0与a1比较得到结果后,a1与a2比较...),最大的元素被换到数组最末尾,剔除掉最后一个元素,在余下的数组元素中进行上述操作,到最后,整个数组呈现从小到大的排序

    # python 冒泡排序
    def paixu(li) :
     mx = 0
     for ad in range(len(li) - 1):
     for x in range(len(li) - 1 - ad):
     mx = max(li[x],li[x+1])
     if li[x] > li[x + 1]:li[x],li[x + 1]=li[x + 1],li[x]
     
     print(li)
    paixu([4165,233454,44,5554,44,7557,6434,500,2000])

    2022年4月11日在他人的基础上修改了,谢谢啦

    下面是另一种排序方式:逐一挑出最小值,将最小值在原列表中删除,将最小值在新列表中添加,直到最后一个值(最大值)为止,到最后将新列表赋值给原列表,整个数组呈现从小到大的排序

    # python 其他排序
    list1=([4165,233454,44,5554,44,7557,6434,500,2000])
    list2=[]
    while len(list1):
     list2.append(min(list1))
     list1.remove(min(list1))
    list1=list2
    print(list1)

    Cai0029

    cai***[email protected]

    4年前 (2022年04月11日)

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /