程序开发的原则:
写重复代码 是可耻的行为;
1.while 条件:
执行代码...
#循环打印0-100
count = 0
while count <= 100:
print("loop ",count)
count += 1
print("-------end-------")
#打印偶数
count = 0
while count <= 100:
if count % 2 == 0:
print("loop ",count)
count += 1
print("-------end-------")
#第50次不打印,第60-80打印对应值的平方
count = 0
while count <= 100:
if count == 50:
pass #过
elif count >= 60 and count <= 80:
print(count*count)
else:
print(count)
count += 1
print("-------end-------")
-----------------------------------------------------
2.死循环 永远运行的程序
#死循环
count = 0
while True:
print("forever 21 ",count)
count += 1
循环终止语句:
break 完全终止循环
continue 终止本次循环
count = 0
while count <= 100:
print("loop ",count)
if count == 5:
break
count += 1
print("-----out of while loop-----")
----------------------------------------------------
#玩猜年龄3次就退出了
age = 26
count = 0
while count < 3:
age_guess = int(input("猜年龄:"))
if age_guess == age:
print("猜对了!")
break
elif age_guess < age:
print("try bigger")
else:
print("try smaller")
count += 1
#玩猜年龄3次后问是否还要玩
age = 26
count = 0
while count < 3:
age_guess = int(input("猜年龄:"))
if age_guess == age:
print("猜对了!")
break
elif age_guess < age:
print("try bigger")
else:
print("try smaller")
count += 1
if count == 3:
again = input("还想玩吗:")
if again == 'y':
count = 0
----------------------------------------------
3.python中
while...else
else 作用 while 中间没有被 break 中止的话,就会执行 else 后面的语句
作用:可以让你知道你的程序 中间是否被break过;
count = 0
while count <= 5:
count += 1
print("loop ",count)
else:
print("循环正常执行完了")
print("-------end-------")
loop 1
loop 2
loop 3
loop 4
loop 5
loop 6
循环正常执行完了
-------end-------
----------------------------------------------------
总结:
1.while语句 pass
2.死循环
3.break
4.continue
5.while...else...