pythonif语句如何循环_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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值