python之while循环实战
1.用while循环打印数字1-10
2.求1-100数字的和
3.输出1-100之间所有的奇数
4.输出1-100之间所有的偶数
5.求1-2+3-4...+99-100的和
6.用户登录(三次机会重试)
一、用while循环打印数字1-10
方法一:将数字7打印成I am here
#!/usr/bin/python
# -*- coding:utf-8 -*-
num=0
while num < 10:
num+=1
if num == 7:
print 'I am here'
else:
print num
执行脚本结果如下:
[root@salt-master python]# python while-01.py
1
2
3
4
5
6
I am here
8
9
10
方法二:数字7不打印
[root@salt-master python]# cat while-02.py
#!/usr/bin/python
# -*- coding:utf-8 -*-
num=0
while num < 10:
num+=1
if num == 7:
continue #continue 退出当前循环,继续执行下一次循环,不退出整个循环
print num
执行脚本结果如下:
[root@salt-master python]# python while-02.py
1
2
3
4
5
6
8
9
10
方法三:数字7不打印
[root@salt-master python]# cat while-03.py
#!/usr/bin/python
# -*- coding:utf-8 -*-
num=0
while num < 10:
num+=1
if num == 7:
pass #没有退出本次循环,只是什么也不执行,这一点与continue是有区别的
else:
print num
执行脚本结果如下:
[root@salt-master python]# python while-03.py .
[root@salt-master python]# python while-03.py
1
2
3
4
5
6
8
9
10
二、打印数字1-100的和
方法一:用while循环
[root@salt-master python]# cat while-04.py
#!/usr/bin/python
# -*- coding:utf-8 -*-
def sum():
sum = 0
x=1
while x < 101:
sum = sum + x
x+=1
return sum
print sum()
执行脚本结果为:
[root@salt-master python]# python while-04.py
5050
方法二:for循环
[root@salt-master python]# cat for-01.py
#!/usr/bin/python
# -*- coding:utf-8 -*-
def sum():
sum = 0
for n in range(1,101):
sum = sum + n
return sum
print(sum())
执行脚本结果为:
[root@salt-master python]# python for-01.py
5050
三、输出1-100之间所有的奇数
方法一:用while循环
[root@salt-master python]# cat while-05.py
#!/usr/bin/python
# -*- coding:utf-8 -*-
a=1
while a < 101:
print a
a+=2
执行脚本结果为:
[root@salt-master python]# python while-05.py
1
3
5
7
9
...
19
21
...
47
49
...
91
93
95
97
99
方法二:
[root@salt-master python]# cat while-06.py
#!/usr/bin/python
# -*- coding:utf-8 -*-
a=1
while a < 101:
if a%2 == 1:
print a
a+=1
执行脚本结果为:
[root@salt-master python]# python while-05.py
1
3
5
7
9
...
19
21
...
47
49
...
91
93
95
97
99
四、输出1-100之间所有的偶数
[root@salt-master python]# cat while-07.py
#!/usr/bin/python
# -*- coding:utf-8 -*-
a=1
while a < 101:
if a%2 == 0:
print a
a+=1
五、求1-2+3-4...+99-100的和
[root@salt-master python]# cat while-08.py
#!/usr/bin/python
# -*- coding:utf-8 -*-
sum=0
a=1
while a < 100:
if a%2 == 0:
sum=sum-a #逢偶必减
if a%2 == 1:
sum=sum+a #逢奇必加
a+=1
print(sum)
执行脚本结果为:
[root@salt-master python]# python while-08.py
50
五、用户登录(三次机会重试)
i = 0
while i < 3:
username = input('请输入账号:')
password = int(input('请输入密码:'))
if username == 'zhangjunchao' and password == 123456:
print('登录成功')
else:
print('登录失败请重新登录')
i += 1
在pytharm3.6验证:
"D:\My Software\python3.6\python.exe" D:/saltstack-python/python/for-01.py
请输入账号:zhang
请输入密码:123456
登录失败请重新登录
请输入账号:jun
请输入密码:123456
登录失败请重新登录
请输入账号:zhangjunchao
请输入密码:123456
登录成功