Python中if语句触发SyntaxError语法错误的求助
解决Python if语句的SyntaxError语法错误
错误原因
你代码里的or if是明显的语法错误——Python的逻辑运算符or后面直接跟布尔判断表达式就行,不需要重复写if关键字,这就是触发SyntaxError的根本原因。
修复后的基础代码
把所有or if改成or,保留原有的判断逻辑,就能正常运行:
from time import sleep # 补充导入sleep模块,避免运行报错 sleep(1) print("Did lunch start before or after 12:00pm?") while True: lunch_time = input() if lunch_time == "before" or lunch_time == "Before": avgrams *= 0.98 STDEV *= 0.98 break elif lunch_time == "after" or lunch_time == "After": break else: sleep(1) print("Sorry, I don't understand.") sleep(1) print("Please only answer with 'before' or 'after' (with no punctuation).")
更简洁的优化方案
可以把输入内容转成小写(同时去掉首尾空格),这样不用重复判断大小写,代码更简洁健壮,还能兼容用户输入的空格、大小写变体:
from time import sleep sleep(1) print("Did lunch start before or after 12:00pm?") while True: # 转小写+去首尾空格,兼容用户输入的大小写、空格 lunch_time = input().strip().lower() if lunch_time == "before": avgrams *= 0.98 STDEV *= 0.98 break elif lunch_time == "after": break else: sleep(1) print("Sorry, I don't understand.") sleep(1) print("Please only answer with 'before' or 'after' (with no punctuation).")
内容的提问来源于stack exchange,提问作者Morten
相关产品推荐
相关产品推荐

