python——循环

 

循环:for循环和while循环

 

一、for循环

 

1.  for循环的格式: for x in 一个list或tuple

 1 >>> for x in [1,2,3]:
 2 ...   print(x)
 3 ...
 4 1
 5 2
 6 3
 7 >>> for x in (0,1,2):
 8 ...   print(x)
 9 ...
10 0
11 1
12 2
13 >>> n=[1,2,3]
14 >>> for x in n:
15 ...   print(x)
16 ...
17 1
18 2
19 3
20 >>>

 

 

2.  若要计算1-100的整数之和,用一个list直接给出1-100的整数太麻烦,可以用range()函数直接生成一个序列,如:

1 >>> range(1,101)
2 range(1, 101)
3 >>> list(range(1,101))
4 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]

 

要注意:range(x)生成的序列是从0到x,如:

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

 

计算1-100的整数之和:

1 >>> for x in range(101):
2 ...   sum=sum+x
3 ...
4 >>> print(sum)
5 5050

 

 

二、while循环

 

while循环的格式:while 条件,只要满足条件,就不断循环,条件不满足时退出循环

如:计算100以内的偶数之和

1 >>> n=100
2 >>> sum=0
3 >>> while n>0:
4 ...   sum=sum+n
5 ...   n=n-2
6 ...
7 >>> print(sum)
8 2550

 

 

三、break语句:提前退出循环

如:

 1 >>> sum=0
 2 >>> n=1
 3 >>> while n<=100:
 4 ...   if n>5:
 5 ...     break
 6 ...   sum=sum+n
 7 ...   n=n+1
 8 ...
 9 >>> print(sum)
10 15

 

 

四、continue语句:跳过本次循环,执行下一次循环

如:

1 >>> n = 0
2 >>> while n < 10:
3 . . .    n = n + 1
4 . . .    if n % 2 == 0: # 如果n是偶数,执行continue语句
5 . . .        continue # continue语句会直接继续下一轮循环,后续的print()语句不会执行
6 . . .    print(n)

 

posted @ 2020-12-18 13:37  CannedDream  阅读(96)  评论(0编辑  收藏  举报