900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > python入门基础2 if语句 while循环 for循环

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

时间:2018-10-20 06:55:18

相关推荐

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。