4.pytho while 循环
1.使用while 循环输出1—10并停止循环:示例如下
kaishi = 1
while True:
print (kaishi)
if kaishi == 10:
break
kaishi = kaishi +1
while True:
print("1233")
time.sleep(0.5)
continue
print ("4566")
break : 用于跳出当前循环,并且break下面的代码,将不在执行
continue : 用于跳出本次循环,继续下一次循环
2.使用while循环算出1+2+3.....+100的求和算法
sum = 0
start = 1
while True:
# print (start)
sum = sum + start
if start == 100
break
start += 1
print (sum)
3.通过while循环输出123456 8910的例子
start = 1
while True:
if start ==7:
start += 1
continue
print (start)
if start ==10:
break
start += 1
4.通过while循环源源不断的输出:
import time
kaishi = 1
while True:
print(kaishi)
kaishi+= 1
time.sleep(1)
5.连续叠加循环:
import time
kaishi = 1
flang = True
while flang:
print(kaishi)
if kaishi == 10:
flang = False
kaishi+= 1
time.sleep(1)
print ('end')
6.持续循环1
import time
#a1 = True
while True:
print ('1')
time.sleep(1)
# a1 = False
print ('end')
7.输出1——100的所有数
start = 1
while True:
print (start)
if start == 100:
break
staet += 1
8.输出1———100所有的奇数和偶数(pass和print (start)调换)
start = 1
while start < 101:
temp = start % 2
if temp == 1:
print (start)
#pass
else:
pass
#print (start)
start += 1
9.求1-2+3-4+5......99的所有数的和(#注释的地方打开可以显示过程)
#s = ""
sum = 0
start = 1
while start < 100:
temp = start % 2
if temp == 1:
# if start == 1:
# s = str (start)
# else:
# s = s + "+" + str (start)
sum = sum + start
else:
# s = s + "-" + str (start)
sum = sum - start
start += 1
#print (s)
print (sum)