作业(必做题):
1. 使用while循环输出1 2 3 4 5 6 8 9 10
1 print('strart')
2 count = 0
3 while count < 10:
4 if count == 7:
5 count += 1
6 continue
7 else:
8 print(count)
2. 求1-100的所有数的和
1 #方法一:
2 print(sum(range(1,101)))
3
4
5 #方法二:
6 n = 1
7 i = 0
8 while(n<101):
9 i += n
10 n += 1
11 print(i)
12 #最后一个值为最终结果
13
14 #方法三:
15 n = 1
16 for i in range(0,100):
17 n += (i+1)
18 print(n)
19 #最后一个值为最终结果
20
21 # 方法四:
22 print(sum([n for n in range(0,101)]))
3. 输出 1-100 内的所有奇数
1 # 方法一:
2 # for n in range(1,101,2):
3 # print(n)
4
5 #方法二:
6 # for n in range(1,101):
7 # if n % 2 != 0:
8 # print(n)
9
10 #方法三:
11 print(list(n for n in range(0,101) if n % 2 != 0))
4. 输出 1-100 内的所有偶数
1 #方法一:
2 for n in range(1,101):
3 if n % 2 == 0:
4 print(n)
5
6 #方法二:
7 n = 1
8 while n <= 100:
9 if n % 2 == 0:
10 print(n)
11 n += 1
12
13 #方法三:
14 for n in range(2,101,2):
15 print(n)
5. 求1-2+3-4+5 ... 99的所有数的和
x = 1
y = 0
while x < 100:
if x % 2 == 0:
y -= x
else:
y += x
x += 1
print(y)
6. 用户登陆(三次机会重试)
username = "juck"
password = "123"
count=0
tag=True
while tag:
if count == 3:
print('输错三次退出')
break
inp_name=input('请输入您的账号:')
inp_pwd=input('请输入您的密码:')
if inp_name == username and inp_pwd == password:
print('登录成功')
break
else:
print('账号名或密码错误')
count+=1
7:猜年龄游戏
要求:
允许用户最多尝试3次,3次都没猜对的话,就直接退出,如果猜对了,打印恭喜信息并退出
age = 18
count = 0
while count < 3:
if count == 3:
print('输错三次退出')
break
guess_age = input('请输入您的年龄:')
if age == int(guess_age):
print('恭喜您猜对了,请退出')
break
else:
print('您还有%s次机会'%str(2-count))
count += 1
8:猜年龄游戏升级版(选做题)
要求:
允许用户最多尝试3次
每尝试3次后,如果还没猜对,就
问用户是否还想继续玩,如果回答Y或y, 就继续让其猜3次,以此往复,如果回答N或n,就退出程序
如何猜对了,就直接退出cont
tom_age = 99
count = 1
while count < 4:
guess = input('guess age: ').strip()
if guess.isdigit():
guess = int(guess)
if tom_age == guess:
print('猜对了')
break
else:
print('猜错了')
count += 1
if count == 4:
choice = input('是否想继续玩,输入y或Y则继续玩')
if choice == 'y' and choice == 'Y':
count = 1
else:
break
else:
print('输入有误')