-1

这是我在重复我使用过的序列时使用的代码,但它似乎没有工作任何人都可以看到任何问题吗?该代码用于货币转换器。我使用 Python 3.3

userDoAgain = input("Would you like to use again? (Yes/No)\n")
if userDoAgain == "Yes":
        getChoice()
elif userDoAgain == "No":
        print("Thankyou for using this program, Scripted by PixelPuppet")
        import time
        time.sleep(3)
else:
        print("Error: You entered invalid information.")
        doagain()

编辑,这是其余的代码:

 if userChoice == "1":
 userUSD = float(input("Enter the amount of USD you wish to convert.\n"))


 UK = userUSD * 0.62

 print("USD", userUSD, "= ", UK, "UK")





elif userChoice == "2":
    UK = float(input("Enter the amount of UK Currency you wish to convert.\n"))

    userUSD = UK * 1.62

    print("UK", UK, "= ", userUSD, "USD")


    def doagain():

        userDoAgain = raw_input("Would you like to use again? (Yes/No)\n")
    if userDoAgain == "Yes":
            getChoice()
    elif userDoAgain == "No":
            print("Thankyou for using this program, Scripted by PixelPuppet")
            import time
            time.sleep(3)
    else:
            print("Error: You entered invalid information.")
            doagain()
4

3 回答 3

2

一般来说,在 Python 中使用递归来处理重复的控制流是一个坏主意。改用循环更容易,问题也更少。所以,与其定义一个函数doagain来确保你得到关于再次运行的问题的答案,我建议使用while循环。对于您将要重复的较大功能,我建议也使用循环。

def repeat_stuff():
    while True: # keep looping until told otherwise

        # do the actual stuff you want to do here, e.g. converting currencies
        do_stuff_once()

        while True: # ask about doing it again until we understand the answer
            userDoAgain = input("Would you like to use again? (Yes/No)\n")
            if userDoAgain.lower() == "yes":
                break               # go back to the outer loop
            elif userDoAgain.lower() == "no":
                print("Thank you for using this program")
                return              # exit the function
            else:
                print("Error: You entered invalid information.")

请注意,我已将yes/no输入字符串的检查更改为不区分大小写,这是一种更加用户友好的方式。

于 2013-10-19T21:12:48.247 回答
0

您正在使用递归(函数调用自身),而将要重复的代码包装在一个while循环中可能会更好。

这种用法的例子:

userContinue = "yes"

while (userContinue == "yes"):
    userInput = input("Type something: ")
    print("You typed in", userInput)
    userContinue = input("Type in something else? (yes/no): ").lower()
于 2013-10-19T21:05:17.510 回答
-1

可能您需要使用函数“raw_input”而不仅仅是输入。

于 2013-10-19T20:49:42.680 回答