Reputation:
Could anyone help me with looping this code back to the beginning if the user inputs yes and ending the program if the user inputs 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")
Upvotes: 0
Views: 2323
Reputation: 7100
Change while True
to while ans == "Yes"
. Before the loop, you have to define ans
as "Yes" (ans = "Yes
). That way, it will automatically run once, but will prompt the user to continue.
Alternatively, you could do this
ans = input()
if ans == "No":
break
Upvotes: 1
Reputation: 863
Use continue to continue your loop and break to exit it.
if ans == ("Yes") :
continue
else ans == ("No"):
print ("Goodbye")
break
Or, you could just leave off the if ans == ("Yes")
and just have this:
else ans == ("No"):
print ("Goodbye")
break
Or even better, you could change your while loop to check the ans
variable instead of doing while True:
Upvotes: 1