[英]How to loop this code back to the beginning?
如果用户输入是,有人可以帮助我将此代码循环回到开头,如果用户输入否,则可以结束程序吗?
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")
使用继续来继续循环并中断以退出循环。
if ans == ("Yes") :
continue
else ans == ("No"):
print ("Goodbye")
break
或者,您可以不使用if ans == ("Yes")
:
else ans == ("No"):
print ("Goodbye")
break
甚至更好的是,您可以更改while循环以检查ans
变量,而不是while True:
将while True
更改为while ans == "Yes"
。 在循环之前,您必须将ans
定义为“ Yes”( ans = "Yes
),这样,它将自动运行一次,但会提示用户继续。
或者,您可以这样做
ans = input()
if ans == "No":
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.