Python练习题(1)
<1> 使用while循环输出数字 1 2 3 4 5 6 8 9 10
1 a = 0 2 while a < 10: 3 a = a + 1 4 if a == 7: 5 pass 6 else: 7 print(a)
<2>求1-100的所有数的和
1 a = 0 2 b = 0 3 while a < 100: 4 a = a + 1 #每循环一次,a会自动加一 5 b = b + a #每次循环b会记录当前a的值,并与a相加 6 print(b)
<3>输出1-100以内的所有奇数
1 a = 0 2 while a < 100: 3 a = a +1 4 if a % 2 == 0: #如果除2求于等于0 5 pass #pass占位,什么都不做 6 else: #否则输出奇数 7 print(a)
<4>输出1-100以内的所有偶数
1 a = 0 2 while a < 100: 3 a = a +1 4 if a % 2 == 0: 5 print(a)
<5>求1-2+3-4+5-6+7 ... 99的所有数的和
1 # -*- coding:utf-8 -*- 2 #求1-2+3-4+5...99的所有数的和 3 ''' 4 找规律奇数是加,偶数是减 5 ''' 6 a = 1 7 b = 0 8 while a <100: 9 temp = a % 2 10 if temp ==0: 11 b = b - a 12 else: 13 b = b + a 14 a += 1 15 print(b)