【python之路4】循环语句之while

时间:2020-12-14 13:46:45

补充:

n = 1
while n<=10:
print(n)
n += 1
else:
print("进入else") #else语句会执行,条件不满足进入else n = 1
while n<=10:
print(n)
n += 1
if n==5:
break
else:
print("进入else") #else语句不执行,因为是通过break退出的循环,没有经过条件判断,所以不会出现条件不满足的情况

for i in s:

  print(i)

else:

  print("结束")

for循环同样可以带else,同样的自然结束循环时执行,如果是break退出的循环也不会执行else后面的语句

1、while 循环语句

#!/usr/bin/env python
# -*- coding:utf-8 -*- import time
bol = True
while bol:
print '1'
time.sleep(1)
bol = False print 'hello,world!'

2、无限的输出数字

#!/usr/bin/env python
# -*- coding:utf-8 -*- import time
n = 0
while True:
n = n + 1
time.sleep(1)
print n

3、打印输出10个数字

#!/usr/bin/env python
# -*- coding:utf-8 -*-
bol = True
n = 0
while bol:
n = n + 1
if n == 10:
bol = False
print n
print "end"

4、break跳出当前循环语句继续向下运行

#!/usr/bin/env python
# -*- coding:utf-8 -*-
n = 0
while True:
n = n + 1
print n
if n == 10:
break print "end"

5、continue退出本次循环,继续下次循环,循环输出1,2,3,4,5,6,8,9,10

#!/usr/bin/env python
# -*- coding:utf-8 -*-
i = 0
while i < 10:
i += 1
if i == 7:
continue
print i
#!/usr/bin/env python
# -*- coding:utf-8 -*-
n = 0
while True:
n += 1
if n == 7:
n += 1
continue
print n
if n == 10:
break
#!/usr/bin/env python
# -*- coding:utf-8 -*-
i = 1
while i <= 10:
if i != 7:
print i
i += 1

6、求1-100的和

#!/usr/bin/env python
# -*- coding:utf-8 -*-
i = 1
sum = 0
while True:
sum += i
if i == 100:
break
i += 1
print sum

7、输出 1-100 内的所有奇数

#!/usr/bin/env python
# -*- coding:utf-8 -*- #输出 1-100 内的所有奇数
i = 1
while True:
if i % 2 == 1:
print i
if i == 100:
break
i += 1

8、输出 1-100 内的所有偶数

#!/usr/bin/env python
# -*- coding:utf-8 -*- #输出 1-100 内的所有偶数
i = 1
while True:
if i % 2 == 0:
print i
if i == 100:
break
i += 1

9、求1-2+3-4+5 ... 99的所有数的和

#!/usr/bin/env python
# -*- coding:utf-8 -*- #求1-2+3-4+5 ... 99的所有数的和
i = 1
sum = 0
while True:
if i % 2 == 1:
sum += i
elif i % 2 == 0:
sum -= i
if i == 100:
break
i += 1
print sum

10、用户登陆(三次机会重试)

#!/usr/bin/env python
# -*- coding:utf-8 -*- #用户登陆(三次机会重试)
n = 0
while True:
psw = raw_input("Enter Password:")
if psw != '123456':
print "Sorry,Error Password!"
n = n + 1
if n == 3:
print "you try 3 times,the programe is over!"
break
else:
print "Congratulations!Password is right!"
break

  

#!/usr/bin/env python# -*- coding:utf-8 -*-
#输出 1-100 内的所有奇数i = 1while True:if i % 2 == 1:print iif i == 100:breaki += 1