p.MsoNormal { margin: 0pt; margin-bottom: .0001pt; text-align: justify; font-family: Calibri; font-size: 10.5000pt }
p.pre { margin: 0pt; margin-bottom: .0001pt; text-align: left; font-family: 宋体; font-size: 12.0000pt }
span.msoIns { text-decoration: underline; color: blue }
span.msoDel { text-decoration: line-through; color: red }
div.Section0 { }
p.MsoNormal { margin: 0pt; margin-bottom: .0001pt; text-align: justify; font-family: Calibri; font-size: 10.5000pt }
p.pre { margin: 0pt; margin-bottom: .0001pt; text-align: left; font-family: 宋体; font-size: 12.0000pt }
span.msoIns { text-decoration: underline; color: blue }
span.msoDel { text-decoration: line-through; color: red }
div.Section0 { }
1、使用while循环输出1 2 3 4 5 6 8 9 10
i = 0
while i < 10:
i = i + 1
if i == 7:
continue
print(i)
2、求1-100的所有数的和
a = 0
for i in range(1, 101):
a = a + i
print(a)
3、输出 1-100 内的所有奇数
for i in range(1, 101):
if i % 2 == 1:
print(i)
4、输出 1-100 内的所有偶数
for i in range(1,101):
if i % 2 == 0:
print(i)
5、求1-2+3-4+5 ... 99的所有数的和
有两种思路,第一种思路是奇数加、偶数减两种运算方式。
a = 0
for i in range(1, 100):
if i % 2 == 1:
a = a + i
elif i % 2 == 0:
a = a - i
print(a)
第二种,都是加,当偶数时,该数位负。
a = 0
for i in range(1,100):
if i % 2 == 0:
i = -i
a = a + i
print(a)
6、用户登陆(三次机会重试)
第一种种是for循环来控制错误次数。
import getpass
username = ‘alex‘
password = ‘123‘
for i in range(3):
user_inp = input(‘请输入你的用户名:‘)
pass_inp = getpass.getpass(‘请输入你的密码:‘)
if user_inp == username and pass_inp == password:
print(‘登陆成功!‘)
break
print(‘输入错误,请重新输入!‘)
第二种是用while循环。
import getpass
username = ‘alex‘
password = ‘123‘
a = 0
while a < 3:
user_inp = input(‘请输入你的用户名:‘)
pass_inp = getpass.getpass(‘请输入你的密码:‘)
if user_inp == username and pass_inp == password:
print(‘登陆成功!‘)
break
print(‘输入错误,请重新输入!‘)
a = a + 1