为什么这段代码不重复? Python 3.3

时间:2013-10-19 20:43:11

标签: python

这是我在重复使用的序列时使用的代码,但它似乎没有工作,任何人都可以看到任何问题吗?代码是货币转换器。我正在使用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()

3 个答案:

答案 0 :(得分: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输入字符串的检查更改为不区分大小写,这是一种更加用户友好的方式。

答案 1 :(得分: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()

答案 2 :(得分:-1)

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