Python循环未从指定行启动,else语句失效问题求助
问题描述
开发带循环功能的计算器时,发现程序未从while numvars == "1"处按预期启动,反而直接执行e = int(input("What exponent do you want")),即使选择不使用指数也会触发该输入。将while改为if问题依旧,else语句无法正常工作,期望程序能回到numvars输入步骤重新运行。相关代码如下:
from math import sqrt numvars = input("how many numbers do you want? Please only pick a number 1-3. Only type out the numerical character") switch = True for x in numvars: while numvars == "1": if switch == True: a = int(input("What number would you like? Type ONLY the numerical character and not the word")) exponents = input("Want to use exponents? MUST BE written as 'yes' or 'no'") if exponents == "yes" or "Yes" or "YES" or "Y": root = input("Would you like to do a square root? yes or no") if root == "yes" or "Yes" or "YES" or "Y": e = int(input("What exponent do you want?")) b = a ** e c = sqrt(b) print(a, "was put to the power of", e, "giving the result", b) print(b, "was then square rooted giving", c) if root == "no" or "No" or "NO": e = int(input("What exponent do you want?")) b = a ** e print(a, "was put to the power of", e) print("Giving the final answer of", b) root = input("Would you like to do a square root? yes or no") if exponents == "no" or "No" or "NO" or "N": root = input("Would you like to do a square root? yes or no") if root == "yes" or "Yes" or "YES" or "N": b = sqrt(a) print(a, "was square rooted giving the answer of", b)
具体原因
布尔表达式写法完全错误
代码中所有类似if exponents == "yes" or "Yes" or "YES" or "Y"的判断都是无效的。Python中该表达式会被解析为(exponents == "yes") or ("Yes") or ("YES") or ("Y"),而非判断exponents等于其中任意一个值。由于非空字符串在布尔判断中为True,所以不管用户输入什么,这个条件都会成立,直接进入指数输入逻辑,哪怕选了"no"。同理,root相关的判断也存在同样问题。循环结构设计混乱冗余
- 外层
for x in numvars完全多余:numvars是用户输入的单个字符(如"1"),循环仅执行一次,无实际作用。 while numvars == "1"的循环逻辑失效:switch变量仅在第一次循环时为True,后续循环不会重新获取exponents值,但循环会持续执行,导致逻辑混乱。同时,该循环未包裹numvars输入步骤,无法实现回到初始输入的需求。
- 外层
代码执行路径冲突冗余
在exponents == "yes"的分支中,已完成root的询问与逻辑处理,但后续又重复执行root = input("Would you like to do a square root? yes or no"),引发额外输入请求,干扰正常流程。另外,exponents == "no"分支中的root判断还错误混入了"N"值,进一步导致逻辑判断失效。变量初始化存在漏洞
若后续循环中switch为False,exponents变量会未定义,直接触发报错,只是前面的布尔表达式错误掩盖了这个问题。
内容的提问来源于stack exchange,提问作者Ruby Rose

