码迷,mamicode.com
首页 > 编程语言 > 详细

python入门基础2 if语句 while循环 for循环

时间:2018-11-27 01:31:33      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:format   it!   big   print   more   ffffff   range   ...   密码   

if语句

判断用户名和密码是否正确:

_username="liulu"
_password="123456"

username=input("username:")
password=input("password:")

if username==_username and password==_password:
print("welcome {name} login...".format(name=username))
else:
print("invalid username and password!")


猜年龄:
my_age=23

guess_age=int(input("please guess my age:")) #因为input默认的是字符串,所以需要int
if guess_age==my_age:
print("you got it!")
elif guess_age>my_age:
print("think smaller...")
else:
print("think bigger...")


while循环
猜年龄,最多猜三次,猜不中不能再猜
my_age=23

count=0

while True: #True要大写 #可以简化为while count <3:
if count==3:
break
#break 可结束运行本次循环。continue是跳出本次循环。

guess_age=int(input("guess age:"))

if guess_age==my_age:
print("you got it")
break
elif guess_age>my_age:
print("think smaller...")
else:
print("think bigger...")

count+=1
else:
print("you have no more chance to guess...")


for循环
猜年龄,最多猜三次,猜不中不能再猜
my_age=23

for i in range(3)

guess_age=int(input("guess age:"))

if guess_age==my_age:
print("you got it")
break
elif guess_age>my_age:
print("think smaller...")
else:
print("think bigger...")

else:
print("you have no more chance to guess...")

步长
# 从0到10
for i in range(10):
print("loop",i)

# 只打02468
for i in range(0,10,2):
print("loop",i)

if 与 while 混合使用案例:
猜年龄,最多猜三次,猜不中询问是否继续猜,输入n后不再猜。
my_age=23

count=0

while count<3:

guess_age=int(input("guess age:"))

if guess_age==my_age:
print("you got it")
break
elif guess_age>my_age:
print("think smaller...")
else:
print("think bigger...")

count+=1

if count==3:
continue_confirm=input("would you like to keep guessing?")
if continue_confirm!="n":
count=0


for循环嵌套
for i in range(10):
print("------",i)
for j in range(10):
print(j)
if j>5:
break

 

python入门基础2 if语句 while循环 for循环

标签:format   it!   big   print   more   ffffff   range   ...   密码   

原文地址:https://www.cnblogs.com/luxiaoma/p/10023485.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!