欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-07-14 23:35:46
...

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