Python循环

作者: 小_源 | 来源:发表于2018-08-14 21:25 被阅读15次

循环

  • 能执行同一件事很多次

while循环

while 条件:
    要重复做的事情
  • 例1:打印10遍我喜欢你
i = 1
while i <= 10:#循环条件
    print("我喜欢你")
    i+=1#每一次循环i都加上1。直到i=11的时候,不满足循环的条件。循环停止

上述代码运行结果为:


image

while循环嵌套

  • while循环里面有while循环
i = 1#控制外面while循环
while i <= 9:
    j = 1#控制里面的while循环
    while j <= i:#while循环里面有while循环
        print("%d*%d=%d"%(j,i,i*j),end="\t")#加一个end可以让print打印不换行
        j+=1
    print("")#打印空目的就是为了换行
    i+=1

上述代码运行结果为:


image

死循环

  • 会无休无止的执行下去
while True:
    要重复做的事情

for循环

  • 跟while循环一样for也可作为循环。比while更简单
for i in 字符串、元组、列表、range():
    要重复做的事情
else:
    不满足循环条件会执行
  • 循环遍历字符串
name = "python"
for i in name:
    print(i)#会打印字符串中每一个字符

上述代码运行结果为:


image
  • range(start,end,step)

    • start:起始值,循环包括起始值
    • end:终止值,循环不包括终止值
    • step:步长
  • 步长为1

for i in range(1,5,1):#起始值:1 终止值:5 步长:1
    print(i)

上述代码运行结果为:


image
  • 步长为2
for i in range(1,5,2):#起始值:1 终止值:5 步长:2
    print(i)#每隔2打印一次

上述代码运行结果为:


image

for循环嵌套

  • for循环里面有for循环
for i in range(1,10):#步长默认为1
    for j in range(1,i+1):#i最大值是9 要9*9所有要加上1
        print("%d*%d=%d"%(j,i,i*j),end="\t")
    print("")#换行

上述代码运行结果为:


image

break和continue

  • 只能用在循环,break结束循环
  • 只能用在循环,continue 结束本次循环,接着执行下一次循环
  • break
for i in range(1,10):
    if i == 6:#当i等于6的时候循环直接结束
        break
    print(i)

'''
break同样适用while循环
i = 1
while i < 10:
    if i == 6:
        break
    print(i)
    i+=1
'''

上述代码运行结果为:


image
  • continue
for i in range(1,10):
    if i == 6:#当i等于6的时候循环本次循环,接着执行下一次循环
        continue
    print(i)

'''
continue同样适用while循环
i = 0
while i < 9:
    i+=1
    if i == 6:
        continue
    print(i)
'''

上述代码运行结果为:


image
image

相关文章

网友评论

    本文标题:Python循环

    本文链接:https://www.haomeiwen.com/subject/tnrpbftx.html