python--if,while,break,continue
if
你在生活中是不是经常遇到各种选择,比如玩色子,猜大小,比如走那条路回家。python程序中也会遇到这种情况,这就用到了 if 语句
_username = 'zou' _password = 'abc123' username = input("username:") password = input("password:") if _username == username and _password == password: print("Welcome user {name} login...".format(name=username)) else: print("Invalid username or password!")
money = int(input("请输入你兜里的钱:")) if money > 500: print("吃啤酒吃炸鸡. 生活美滋滋") elif money > 300: print("盖浇饭走起") elif money > 50: print("方便面走起") else: print("减肥走起")
while
在生活中,我们遇到过循环的事情吧?比如循环听歌,在程序中,循环也是存在的,
count=0 while True: print("count:",count) count=count+1
陷入了死循环,在实际项目中要避免出现死循环,True 的T必须是大写
age_of_oldboy = 56 while True: guess_age = int(input('guess age:')) if guess_age == age_of_oldboy: print("yes, you got it. ") elif guess_age > age_of_oldboy: print("think smaller...") else: print("thing bigger...")
一直可以输入,对或错都不结束
age_of_oldboy = 56 while True: guess_age = int(input('guess age:')) if guess_age == age_of_oldboy: print("yes, you got it. ") break elif guess_age > age_of_oldboy: print("think smaller...") else: print("thing bigger...")
加了个break,输入正确时退出
break 结束循环. 停止当前本层循环
age_of_oldboy = 56 count = 0 while count < 3: guess_age = int(input('guess age:')) if guess_age == age_of_oldboy: print("yes, you got it. ") break elif guess_age > age_of_oldboy: print("think smaller...") else: print("thing bigger...") count = count + 1
输错三次退出循环
age_of_oldboy = 56 count = 0 while count < 3: guess_age = int(input('guess age:')) if guess_age == age_of_oldboy: print("yes, you got it. ") break elif guess_age > age_of_oldboy: print("think smaller...") else: print("thing bigger...") count = count + 1 else: print("you have tried too many times...")
当程序正常执行完会执行最后一个else,如果中间遇到break,不执行else
while True: s = input("请开始说:") if s == 'q': break # 停止当前循环 # 过滤掉马化腾 if "马化腾" in s: # 在xxx中出现了xx print("你输入的内容非法. 不能输出") continue # 停止当前本次循环.继续执行下一次循环 print("喷的内容是:" + s)
count = 1 while count <= 10: print(count) count = count + 1 if count == 5: break # 彻底停止循环. 不会执行后面的else else: # while条件不成立的时候执行 print("这里是else")
continue:停止本次循环,继续执行下一次循环
分类:
python基础
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)