流程控制之while循环
1.什么是循环?(what)
循环是指重复做某一件事
2.为何要有循环?(why)
为了让计算机能像人一样重复去做某一件事
3.如何使用循环?(how)
#语法一:while条件
如:用户登录时信息输入错误是需要重新输入
name_bd="tony" pwd_bd=123 while True:name=input("please your name: ")pwd=input("plesse your password: ")if name == name_bd and pwd == pwd_bd:print("login successful")else:print("please input again")
输入这段代码后,会发现无论你登录是否成功,都是无限循环登录,所以要让登录成功后就结束循环应该:
name_bd="tony" pwd_bd="123" a=True while a:name=input("please your name: ")pwd=input("please your password: ")if name == name_bd and pwd == pwd_bd:print("login successful")a=Falseelse:print("please input again")
#语法二:while+break(break表示强制结束本层循环)
name_bd="tony" pwd_bd="123" while True:name=input("please your name: ")pwd=input("plesse your password: ")if name == name_bd and pwd == pwd_bd:print("login successful")breakelse:print("please input again")
这样也实现了登陆成功是终止循环
#语法三:while+continue(continue表示停止本次循环,直接进入下一次)
count=0 while count<10:if count ==5:count+=1continueprint(count)count+=1
#语法四:while+else(else会在while循环没有被break终止的情况下执行)
name_bd="tony" pwd_bd="123" count=0 while count<=2: name=input("please your name: ")pwd=input("plesse your password: ")if name == name_bd and pwd == pwd_bd:print("login successful")breakelse:print("please input again")count+=1 else:print("输错次数太多,请稍后")
#语法五:while循环的嵌套
name_bd="tony" pwd_bd="123" count=0while count<=2:name=input("please your name: ")pwd=input("plesse your password: ")if name == name_bd and pwd == pwd_bd:print("login successful")while True:print("1.浏览商品,2.添加购物车,3.支付,4.退出")choice=input("请输入你的选择: ")if choice=="1":print("正在浏览商品")if choice=="2":print("正在添加购物车")if choice=="3":print("正在支付")if choice=="4":breakbreakelse:print("please input again")count+=1 else:print("输错次数太多,请稍后")