为什么我的while循环n

2024-04-26 07:56:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我在让while循环工作时遇到了一个问题。我使用next=y命令来启动程序,但是在我编写while(next==y)以再次运行main函数的最后,这个位似乎不起作用。即使我输入'n'或任何不是'y'的东西,函数仍会重复。我的想法是,初始的next=y覆盖了所有内容,但我似乎无法删除它,否则代码只会运行并中断,什么都没有运行。你知道吗

next = "y"



def main():

            operator = input("Select a function and press enter (+, - , *, /) ")


            if(operator != "+" and operator != "-" and operator != "*"and operator >!= "/"):
        print(input("You must enter a valid operator "))
                        else:
        val1 = int(input("Select value 1 "))
        val2 = int(input("Select value 2 "))

    if(operator == "+"):
        print(add(val1, val2))
    elif(operator == "-"):
        print(sub(val1, val2))
    elif(operator == "*"):
        print(mult(val1, val2))
    else:
        print(div(val1, val2))

 next = (input("Would you like to do another calculation? (y/n): "))

 while(next == "y"):
    main()

我想这是一个简单的解决办法,但我不知道如何做到这一点。你知道吗


Tags: and函数inputifmainselectoperatorelse
3条回答

首先,您应该注意到next对于变量名来说是一个糟糕的选择,因为它覆盖了内置函数next——可以考虑像user_choice这样的东西

不管怎样,代码的结构应该是这样的:

def main():
    # Do calculations

choice = 'y'
while choice == 'y':
    main()
    choice = input("Would you like do another calculation? (y/n): ")

每次main()结束时,都会要求用户输入y / n,循环结束。如果选择是y,它将再次运行—否则,它将退出循环。你知道吗

声明

next = (input("Would you like to do another calculation? (y/n): "))

需要在while循环内移动。实际上,它只设置了一次。(您应该只看到一次提示。)

接下来是主函数中的局部变量。您可以使其成为全局的(坏习惯),或者在main函数的末尾添加return next。然后需要在循环中执行以下操作:

while next ==  'y':
    next = main()

相关问题 更多 >