python入门基础2 if语句 while循环 for循环
Posted luxiaoma
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python入门基础2 if语句 while循环 for循环相关的知识,希望对你有一定的参考价值。
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循环的主要内容,如果未能解决你的问题,请参考以下文章
Python语法基础03(if语句,while循环与for循环)