0

我是编程新手,我正在尝试为用户选择退出“是”或“y”或“否”或“n”,但我在尝试这样做时运气最差。有人可以帮我指出我的错误并提示更好的方法吗?我非常感谢您的帮助。谢谢你。

编辑

我为我模糊的帖子道歉。让我在我的问题上更清楚一点。使用两个 while 循环在循环中执行我的程序,我想让用户选择是要离开还是重做程序。然而,该程序没有正确退出,即使我已经声明“n”专门设置为终止程序。但是,无论我输入“y”还是“n”,当我请求或不请求重做主程序时,代码都会循环返回。

我对我的循环到底出了什么问题感到困惑,因为当我输入“n”时它应该关闭。我的循环退出到底有什么问题?

我的编码

while True:
# Blah Blah Blah. Main program inserted here.
while True:
    replay = input("Do another Calculation? (y/n)").lower()
    if replay in ('y','n'):
        break
    print("Invalid input.")
    if replay == 'y':
        continue
    else:
        print("Good bye")
        exit()
4

2 回答 2

1

.lower应该是.lower().lower()是一个函数,不带括号调用它不会做任何事情:

>>> string = 'No'
>>> string.lower
<built-in method lower of str object at 0x1005b2c60>
>>> x = string.lower
>>> x
<built-in method lower of str object at 0x1005b2c60>
>>> x = string.lower()
>>> x
'no'
>>> 

此外,您正在检查replay == input(...). 你只想要一个=分配:

>>> result = 0
>>> result == 4
False
>>> result = 4
>>> result == 4
True
>>> 

在第二个循环中,您也有一个不需要的:after 。print replaywhile True

这是一个建议:不要使用replay in ("no, "n")非常unpythonic的 using ,而是使用内置方法startswith(char)查看它是否以该字符开头:

>>> string = "NO"
>>> string.lower().startswith("n")
True
>>> string = "yeS"
>>> string.lower().startswith("y")
True
>>> 

这也适用于naw, oryeah等​​输入。

这是您编辑的代码:

a = int(input("Enter the first number :"))
b = int(input("Enter the second number :"))
print("sum ---" + str(a+b))
print("difference ---" + str(a-b))
print("product ---" + str(a*b))
print("division ---" + str(a/b))
input()
while True:
    print("Do you want to try again?")
    while True:
        replay = input("Do another Calculation? 'y' for yes. 'n' for no.").lower()
        print(replay)
        if replay.startswith('y') == True:
            break
        if replay.startswith('n') == True:
            exit()
        else:
            print("I don't understand what you wrote. Please put in a better answer, such as 'Yes' or 'No'")
于 2014-05-03T02:41:45.600 回答
1

我看到一些语法错误:

1)print replay应该是print(replay)

2)if replay in ("yes","y")应该是if replay in ("yes","y"):

3)if replay in ("no","n") 应该是if replay in ("no","n"):

于 2014-05-03T02:46:57.597 回答