while小用
1.使用while打印1 2 3 4 5 6 8 9 10
#!/usr/bin/env python #encoding: utf-8 num = 1 while num < 11: if num == 7: print else: print num num = num + 1
执行结果:
[root@localhost zuoye]# python 1.py 1 2 3 4 5 6 8 9 10
2.求1到100的和
#!/usr/bin/env python #encoding: utf-8 num = 1 sum = 0 flag = True while flag: sum = sum + num if num == 100: flag = False print sum num = num + 1
执行结果:
[root@localhost zuoye]# python 2.py 5050
3.求1到100奇数的和
#!/usr/bin/env python #encoding: utf-8 num = 1 sum = 0 flag = True while flag: sum = sum + num if num == 99: flag = False print sum num = num + 2
执行结果:
[root@localhost zuoye]# python 3.py 2500
4.求1到100偶数的和
#!/usr/bin/env python #encoding: utf-8 num = 2 sum = 0 flag = True while flag: sum = sum + num if num == 100: flag = False print sum num = num + 2
执行结果:
[root@localhost zuoye]# python 4.py 2550
5.求和1-2+3-4......+99-100
#!/usr/bin/env python #encoding: utf-8 num = 1 sum = 0 flag = True while flag: if num%2 == 1: sum = sum + num if num == 99: flag = False print sum else: sum = sum - num num = num + 1
执行结果:
[root@localhost zuoye]# python 5.py 50
6.用户登录,三次机会重试
#!/usr/bin/env python #encoding: utf-8 flag = True num = 1 while flag: Name = raw_input('please enter you name: ') Passwd = int(raw_input('please enter you passwd: ')) if Name == "kebi" and Passwd == 123: print "密码正确" flag = False else: num = num + 1 if num == 4: flag = False print "对不起,已经三次输入错误。"
执行结果:
一次答对: [root@localhost zuoye]# python 6.py please enter you name: kebi please enter you passwd: 123 密码正确 两次答对: [root@localhost zuoye]# python 6.py please enter you name: 4356 please enter you passwd: 3456 please enter you name: kebi please enter you passwd: 123 密码正确 三次达错: [root@localhost zuoye]# python 6.py please enter you name: 123 please enter you passwd: 123 please enter you name: 123 please enter you passwd: 123 please enter you name: 123 please enter you passwd: 123 对不起,已经三次输入错误。
注意:在2.7.2中测试