neolee / wop-community

29 stars 19 forks source link

执行while语句时无法返回结果 #338

Closed WengShaowei closed 5 months ago

WengShaowei commented 10 months ago

关于assignment1改进CalcBot的问题,我刚开始执行以下语句时可以运行,但不知道为什么,后来执行同样的语句却无法返回结果,而是直接结束运行,跳到下一个环节。

class CalcBot(Bot):
    def __init__(self):
        self.q = "Through recent upgrade I can do calculation now. Input some arithmetic expression to try:"

    def run(self):
        self._say(self.q)
        while True:
            self.a = input()
            if self.a == "exit" or "quit":
                break
            else:
                result = simple_eval(self.a)
                return f"Done. Result = {result}"

image

andyhuang18 commented 10 months ago

@WengShaowei 嗨你好!我了解你写这段代码的含义,你希望可以持续计算算式,直到用户输入退出才退出循环。但是你的代码似乎直接break了,无法进行计算。按照while逻辑思路来讲,一定是到了break才会导致跳出循环了,问题实际上就出在

if self.a == "exit" or "quit":

这个判断语句会判断self.a是否和exit相等,但是并不会将其和quit比较。更可怕的是...or后连接的quit在计算机看来,一直会是一个true的返回值,而你用了or连接...那么不论前面的判断结果是如何,这个if条件总是true的。所以会进入这个条件,执行break。你应该将条件分开,像这样:

if self.a == "exit" or self.a == "quit":

更详细的,可以加入小写的判断:

if self.a.lower() == "exit" or self.a.lower() == "quit":

我觉得这是一个不错的问题,很多人会在if的判断上出现失误,感谢你的提问!如果还有问题欢迎继续提出来~

WengShaowei commented 10 months ago

感谢您的回答!是我在if的判断上出错了,但不知道为什么在按照您说的改进后,还是无法计算。

class CalcBot(Bot):
    def __init__(self):
        self.q = "Through recent upgrade I can do calculation now. Input some arithmetic expression to try:"

    def run(self):
        self._say(self.q)
        while True:
            self.a = input()
            if self.a.lower() == "exit" or self.a.lower() == "quit":
                break
            else:
                result = simple_eval(self.a)
                return f"Done. Result = {result}"

image

andyhuang18 commented 10 months ago

嗨 @WengShaowei ,收到你的问题了,我想可能是因为在这里直接return结果会导致内容被跳过了,可以用self._say(f"Done. Result = {result}")代替最后的内容。