(1)用户登录验证
import getpass
name=input("请输入用户名:")
pwd=getpass.getpass("请输入密码:")
if name=="xiaoming" and pwd=="123":
print("welcome you!!!")
else:
print("用户名或密码错误!")
(2)猜年龄游戏
age=18
userage=int(input("请输入年龄:"))
if age<userage:
print("猜大了!!!")
elif age>userage:
print("猜小了!!!")
else:
print("恭喜你猜对啦!!!")
2、表达式 for
例子:(1)输出循环10次
for i in range(10):
print("i:",i)
输出结果为:
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
(2)输出循环10次,遇到5的不走了,直接跳入下一次循环
for i in range(10):
if i==5:
continue
print("i:",i)
输出结果为:
i: 0
i: 1
i: 2
i: 3
i: 4
i: 6
i: 7
i: 8
i: 9
(3)输出循环10次,遇到5就不走了,直接退出
for i in range(10):
if i==5:
break
print("i:",i)
输出结果为:
i: 0
i: 1
i: 2
i: 3
i: 4
3、表达式while
猜年龄游戏加强版(猜对就退出,否则一直在猜)
方法一
age=18
userage=int(input("请输入年龄:"))
while True:
if age<userage:
print("猜大了!!")
userage = int(input("请输入年龄:"))
elif age>userage:
print("猜小了!!")
userage = int(input("请输入年龄:"))
else:
print("恭喜你猜对了!!")
break
方法二
age=18
userage=0
while age!=userage:
userage=int(input("请输入年龄:"))
if age<userage:
print("猜大了!!")
#userage = int(input("请输入年龄:"))
elif age>userage:
print("猜小了!!")
#userage = int(input("请输入年龄:"))
else:
print("恭喜你猜对了!!")
# break
不过好像都差不多呢。。。。。。。(欢迎大家指教!!)
示例练习:
-
登录接口编写
-
输入用户名密码
-
认证成功后显示欢迎信息
-
输错三次后直接退出
username="xiaoming" pwd="123" count=1 while count<=3: ueser = input("请输入用户名:") password = input("请输入密码:") if username!=ueser and password!=pwd: print("用户名和密码均错误!") count+=1 elif username!=ueser and password==pwd: print("用户名错误!!") count+=1 elif username==ueser and password!=pwd: print("密码错误!!") count+=1 else : print("登录成功,欢迎%s"%username) break
-
-
有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
count=0 for i in range(1,5): for j in range(1,5): for k in range(1,5): if i!=j and i!=k and j !=k: count+=1 print("%d%d%d"%(i,j,k)) print("count=%d"% count) 结果为: 123 124 132 134 142 143 213 214 231 234 241 243 312 314 321 324 341 342 412 413 421 423 431 432 count=24
感谢Alex li老师提供的资料!!!
来源:https://www.cnblogs.com/pythonbigdata/p/8377933.html