如何将此代码循环回到开头?

时间:2015-11-02 20:31:20

标签: python loops

如果用户输入yes并在用户输入no时结束程序,是否有人可以帮助我将此代码循环回到开头?

while True:
    print ("Hello, this is a program to check if a word is a palindrome or not.")
    word = input("Enter a word: ")
    word = word.casefold()
    revword = reversed(word)
    if list(word) == list(revword):
        print ("The word" ,word, "is a palindrome.")
    else:
        print("The word" ,word, "is not a palindrome.")
    print ("Would you like to check another word?")
    ans = input()
    if ans == ("Yes") :
      #here to return to beginning
    else ans == ("No"):
        print ("Goodbye")

2 个答案:

答案 0 :(得分:1)

使用continue继续循环并中断以退出它。

   if ans == ("Yes") :
      continue
    else ans == ("No"):
        print ("Goodbye")
        break

或者,您可以暂时离开if ans == ("Yes"),然后点击:

    else ans == ("No"):
        print ("Goodbye")
        break

甚至更好,您可以更改while循环以检查ans变量而不是while True:

答案 1 :(得分:1)

while True更改为ans == "Yes"。在循环之前,您必须将ans定义为“是”(ans = "Yes)。这样,它会自动运行一次,但会提示用户继续。

或者,您可以这样做

ans = input()
if ans == "No":
    break