首页 > 解决方案 > 我的程序中有一个 else ,我不明白为什么 if 语句只是通过它

问题描述

就像我在标题中所说的那样,我正在构建一个只会成倍增加的程序,但我想问用户他们是否想继续。好吧,我一切正常,但 if 语句的“else”只是通过了它。

def restart():
    pass

def multiply():
    while True:
        try:
            a = int(input("enter something: ", ))
            b = int(input("enter something: ", ))
            sum = a * b
            print(sum)
            restart()
            continuing = input("Would you like to continue: ", )
            if(continuing == "yes" or "no"):
                if(continuing == "yes"):
                    multiply()
                elif(continuing == "no"):
                    break
            else:
                restart()
            break
        except ValueError:
            print("you have to enter a number sorry you have to start over")
            multiply()
            break

multiply()

我试图弄乱休息,但它并没有解决它。有任何想法吗?

标签: python

解决方案


你永远不会转向 else 语句,因为:

if(continuing == "yes" or "no"):

在您的or语句中,即使 continue == "yes" 为 False,"no" 始终为 True,因为它不是像 "" 这样的空字符串,您应该使用 continue == "no",例如:

if(continuing == "yes" or continuing == "no"):

和整个代码:

def restart():
    pass

def multiply():
    while True:
        try:
            a = int(input("enter something: ", ))
            b = int(input("enter something: ", ))
            sum = a * b
            print(sum)
            restart()
            continuing = input("Would you like to continue: ", )
            if(continuing == "yes" or continuing == "no"):
                if(continuing == "yes"):
                    multiply()
                elif(continuing == "no"):
                    break
            else:
                restart()
            break
        except ValueError:
            print("you have to enter a number sorry you have to start over")
            multiply()
            break

multiply()

推荐阅读