首页 > 编程语言 > 详细

Python>循环

时间:2020-06-16 22:52:26      阅读:70      评论:0      收藏:0      [点我收藏+]
 1 #-*- coding = utf-8 -*-
 2 #@Time : 2020/6/16 20:52
 3 #@Authur : Agur Zheng
 4 #@File : loop_exercise.py
 5 #@Software : PyCharm
 6 
 7 # for循环,范围是包括起点不包括终点
 8 
 9 # 从0~4依次打印
10 for i in range(2,5):
11     print(i)
12 
13 # 从0~11,以3为步进值打印
14 for i in range(0,11,3):
15     print(i)
16 
17 for i in range(4):  # 不指定起始值默认从0开始
18     print(i)
19 
20 for i in range(-10,-100,-20):
21     print(i)
22 
23 # 循环范围是字符串
24 name = "AgurZheng"
25 for x in name:
26     print(x, end="\t")  #依次打印字符串name中的各个字符
27 print("")
28 
29 #循环范围是列表,
30 #len()函数获取对象长度,本例中是获取列表长度
31 names = ["花花","洋洋","小米","小明"]
32 for i in range(len(names)):
33     print(i, names[i], sep="-")
34 
35 # while循环
36 i = 0
37 while i < 5:
38     print("这是第%d次执行循环" % (i+1))
39     print(i)
40     i += 1
41 
42 # 1~100求和
43 i = 1
44 reult = 0
45 while i < 100:  #依次输出i+,在result中记录加上i的结果
46     print("%d + " % i,end="")
47     reult += i
48     i += 1
49 reult += 100
50 print("100 = %d" % reult)
51 
52 # 直接打印结果的1~100求和
53 sum = 0
54 n = 100
55 counter = 1
56 while counter <= 100:   #while循环里的计数器需要在循环外定义好才能使用,for循环的计数器不用
57     sum += counter
58     counter += 1
59 print("1到100的和是", sum)
60 
61 # while循环中else的使用
62 
63 counter = 0
64 while counter < 5:
65     print(counter, "小于5")
66     counter += 1
67 else:
68     print(counter, "等于或大于5")
69 
70 ‘‘‘
71 打印99乘法表,每行打印一个数字的所有乘法
72 flag_row表示行,flag_column表示列的计数器
73 ‘‘‘
74 flag_row = 1
75 while flag_row <= 9:
76     flag_column = 1
77     while flag_column <= flag_row:
78         product = flag_row * flag_column
79         print("%d * %d = %d"%(flag_row,flag_column, product), end="\t")
80         flag_column += 1
81     else:
82         print("")
83     flag_row += 1
84 
85 for row in range(1,10):
86     for column in range(1,(row+1)):
87         print("%d * %d = %d"%(row, column, (row*column)),end="\t")
88     print("")

 

Python>循环

原文:https://www.cnblogs.com/AgurZheng/p/13149516.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!