if判断,while循环的使用
1.猜年龄
示例代码:
user_lisa = 18 # 定义一个年龄 count = 0 # 循环次数 while count < 3: # 循环的次数小于3次 user = input('please your enter username:').strip() # 用户输入,去两边空格 if user.isdigit(): # 如果输入的是数字字符串的情况下 user = int(user) # 转换成整型 if user == user_lisa: # 用户输入的值和定义的值相等时,退出整个程序 print('you got it') exit() elif user > user_lisa: # 用户输入的值大于定义的值,提示输小点 print('try smaller') else: user < user_lisa # 用户输入的值小于定义的值,提示输大点 print('try bigger') else: print('try again') # 如果用户输入的不是数字,提示重试 count += 1 # 循环的次数自加1 print('too many times') # 提示次数太多
2、用户登陆
方法一:
count = 0 user_name = 'lisa' pwd = '123' while count <3: username =input('please enter your username:') password =input('please enter your password:') if username == user_name and password == pwd: while True: user_cmd = input('Please enter your cmd:').strip() print('The cmd is %s'%user_cmd) if user_cmd == 'q': break break else: print('login failed') count += 1
方法二:
count = 0 user_name = 'lisa' pwd = '123' while count <3: username =input('please enter your username:') password =input('please enter your password:') if username == user_name and password == pwd: while True: user_cmd = input('Please enter your cmd:').strip() print('The cmd is %s'%user_cmd) if user_cmd == 'q': exit() else: print('login failed') count += 1
3、使用while循环输出1、2、3、4、5、6、8、9、10
# 使用while循环输出1、2、3、4、5、6、8、9、10 count = 1 # 定义初始值 while count < 11: # 当count小于11时,执行以下代码 if count == 7: # 当count等于7时,count自加1,且退本次循环 count += 1 continue print(count) # 打印count的值 count += 1 # count自加1
输出结果:
1 2 3 4 5 6 8 9 10