用户登陆验证: if-else 判断
#!/usr/bin/env python # -*-coding:utf-8 -*- import getpass passwd='123456' name='sunhao' user_name=input('请输入用户名:') user_passwd=getpass.getpass('请输入你的密码:') if user_name==name and user_passwd==passswd:
print('Welcome user {_name} login.'.format(_name=user_name))
else:
print('Invalid username or password')
getpass模块在pycharm中不能用
猜年龄: while 循环
#!/usr/bin/env python # -*- coding:utf-8 -*- #Author:sun_96 age_of_me=26 count=0 #猜年龄最多只让猜5次 while count<5: guess_age=int(input('请输入要猜的年龄:')) if guess_age == age_of_me: print('恭喜你,猜对了!') elif guess_age < age_of_me: print("smaller") else: print('bigger') count+=1 if count ==5: continue_guess=input('是否继续:请输入yes or no') if continue_guess == 'yes': count=0 else: print("密码多次输错")
猜年龄: for 循环
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#!/usr/bin/env python # -*- coding:utf-8 -*- #Author:sun_96 age_of_me=26 count=0 #猜年龄最多只让猜5次 for i in range(10): guess_age=int(input('请输入要猜的年龄:')) if guess_age == age_of_me: print('恭喜你,猜对了!') elif guess_age < age_of_me: print("smaller") else: print('bigger') else: print("密码多次输错")
表达式for loop
最简单的循环10次
1 #_*_coding:utf-8_*_ 2 __author__ = 'sunhao' 3 4 for i in range(10): 5 6 print(i)
输入:
loop 0 loop 1 loop 2 loop 3 loop 4 loop 5 loop 6 loop 7 loop 8 loop 9
break 和 continue
for i in range(10): if i > 5: print('Break!') break #跳出整个循环 结束整个循环 print(i)
输出:
0 1 2 3 4 5 6 Break!
for i in range(10): if i < 5: print('Continue') continue #只是跳出本次循环
print(i)
输出:
continue!
continue!
continue!
continue!
continue!
5
6
7
8
9