1、使用while循环输入 1 2 3 4 5 6 8 9 10
count=0 while count<10: count=count+1 if count==7: continue print(count)
2、求1-100的所有数的和
count=1 sum=0 while count<=100: sum=sum+count count=count+1 print(sum)
3、输出 1-100 内的所有奇数
count=1 while count<=100: if count%2==1: print(count) count=count+1
4、输出 1-100 内的所有偶数
count=1 while count<=100: if count%2==0: print(count) count=count+1
5、求1-2+3-4+5 ... 99的所有数的和
count=1 sum=0 sign=1 while abs(count)<100: sum=sum+sign*count count=count+1 sign=-sign print(sum)
6、用户登陆(三次机会重试)
n=0 flag=True while flag: name=input("please input your name:") password=input("please input your password:") if n<3: change=input("want to change?(Y or N):") if change=='N' or n>=3: flag=False if change=='Y': n+=1 if n>=3: print("")
ps:这一题我按照自己的理解写的,就是首先判断用户输入的次数是不是超过3次,如果没有可以提示要不要重新修改用户名和密码,当用户输入N 或者重复输入次数多于三次时,就终止输入~
修改(一):
就是得先有一个确定的用户名和密码,当用户输入的时候也可以进行判断
(其实上面的方法也可行,就是让用户自己判断需不需要重新输入用户名和密码,但机会也是只有三次~)
name_answer='xuanxuan' password_answer='123' name=input("please input your name: ") password=input("please input your password:") count=0 while count<3: if name==name_answer and password == password_answer: print("Congratulations!") break else: name=input("please input the right name:") password=input("please input your right password:") count=count+1
修改(二):
其实可以方法二可以更简洁,就是把输入放在循环体里面~
name_answer='xuanxuan' password_answer='123' count=0 while count<3: name=input("please input your name: ") password=input("please input your password:") if name==name_answer and password == password_answer: print("Congratulations!") break else: print("Error,try again") count=count+1