1. 使用while循环输出1 2 3 4 5 6 8 9 10
代码:
count=0
while count<10:
count += 1
if count ==7:
continue
print(count,end=" ")
效果:
2. 求1-100的所有数的和
代码:
s=0
i=0
while i<=100:
s+=i
i+=1
print(s)
效果:
3. 输出 1-100 内的所有奇数
代码:
i=0
while i<100:
i = i + 1
if i%2!=0:
print(i,end=" ")
效果:
4. 输出 1-100 内的所有偶数
代码:
i=0
while i<100:
i = i + 1
if i%2==0:
print(i,end=" ")
效果:
5. 求1-2+3-4+5 ... 99的所有数的和
代码:
s=0
i=1
while i<=99:
r=pow(-1,i+1)
s+=r*i
i+=1
print(s)
效果:
6. 用户登陆(三次机会重试)
代码:
old_name='king'
old_password='123'
count=0
while count<3:
name = input("请输入你的姓名:")
password = input("请输入你的密码:")
if name==old_name and password==old_password:
print("登录成功!")
break
else:
print("请输入正确的密码或姓名!")
count+=1
效果:
7:猜年龄游戏
代码:
old_age="20"
count=0
while count<3:
age = input("请输入你的猜测的年龄:")
if age==old_age:
print("太棒了!猜测正确!")
break
else:
print("好可惜!猜错了!")
count+=1
效果:
8:猜年龄游戏升级版(选做)
代码:
old_age="20"
count=0
while count<3:
age = input("请输入你的猜测的年龄:")
if age==old_age:
print("太棒了!猜测正确!")
break
else:
print("好可惜!猜错了!")
count+=1
if count==3:
choice=input("你还想继续猜吗?y/n")
if choice=="y":
count=0
continue
else:
break
效果:
9.for循环打印99乘法表
代码:
for i in range(1,10):
for j in range(1,i+1):
print(f'{j}*{i}={(i*j): ^2}',end=' ')
print("")
效果:
10.for循环打印金字塔
代码:
for i in range(1,6):
print(f'{"*"*(2*i-1): ^9}')
效果: