重复直到给出正确答案

时间:2017-01-11 21:12:05

标签: python python-2.7 if-statement while-loop

这是我制作的代码,它只是整个大事的一小部分。如何将其置于while循环中以便重复"Invalid answer, try again."直到给出正确的答案?我已经尝试了很多个小时看着循环但是不能这样做。如果你实际上会运行代码,那么显然会出现错误,因为你没有路径等等。

以下是代码:

shortestpath = raw_input("Give the shortest path? (Y/N)")
if shortestpath == "Y" or shortestpath == "y":
    answer = min(path1, path2, path3, path4, path5, path6, path7, path8, path9)
    print "The shortest path is: "
    print answer
    if answer == path1:
        print "a,f,e"
    elif answer == path2:
        print "a,c,f,e"
    elif answer == path3:
        print "a,f,c,d,e"
    elif answer == path4:
        print "a,f,c,b,d,e"
    elif answer == path5:
        print "a,c,d,e"
    elif answer == path6:
        print "a,c,b,d,e"
    elif answer == path7:
        print "a,b,c,f,e"
    elif answer == path8:
        print "a,b,c,d,e"
    elif answer == path9:
        print "a,b,d,e"
elif shortestpath == "N" or shortestpath == "n":
    print "End of program."
else:
    print "Invalid answer, try again."

2 个答案:

答案 0 :(得分:0)

将代码包装在while循环中。一旦您的代码达到正确答案,您就可以使用break

退出循环
while True:
    shortestpath = raw_input("Give the shortest path? (Y/N)")
    if shortestpath == "Y" or shortestpath == "y":
        answer = min(path1, path2, path3, path4, path5, path6, path7, path8, path9)
        print "The shortest path is: "
        print answer
        if answer == path1:
            print "a,f,e"
        elif answer == path2:
            print "a,c,f,e"
        elif answer == path3:
            print "a,f,c,d,e"
        elif answer == path4:
            print "a,f,c,b,d,e"
        elif answer == path5:
            print "a,c,d,e"
        elif answer == path6:
            print "a,c,b,d,e"
        elif answer == path7:
            print "a,b,c,f,e"
        elif answer == path8:
            print "a,b,c,d,e"
        elif answer == path9:
            print "a,b,d,e"
        break
    elif shortestpath == "N" or shortestpath == "n":
        print "End of program."
        break
    else:
        print "Invalid answer, try again."

答案 1 :(得分:0)

def get_answer(prompt,options):
    while True:
        result = raw_input(prompt)
        if result in options: return result
        print "Got unexpected input ... please try again"

selected_option = get_answer("Would you like to _____?",options=["y","Y","n","N"])
相关问题