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")
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:
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
Related
I'm a newbie and am working on this Dictionary program. After receiving a word the program retrieves the definition and then the program ends. How do I get the program to loop back to receive another input?
I've tried using a while True: but it doesn't seem to work...thanks!
**data = json.load(open("Teaching/data.json"))
**def dictionary(word):
word = word.lower()
if word in data:
return data[word]
elif len(get_close_matches(word, data.keys()))>0:
yn = input("Did you mean %s instead? Enter 'Y' for yes, 'N' for no: " % get_close_matches(word, data.keys())[0])
if yn == 'Y':
return data[get_close_matches(word, data.keys())[0]]
elif yn == 'N':
return "The word doesn't exist. Please try again!"
else:
return "I don't understand."
else:
return ("Please try again.")
word = input("Enter a word: ")
output = dictionary(word)
if type(output) == list:
for item in output:
print(item)
else:
print(output)****
You can do it by using the while loop. After receiving an input it will go through the full code, then will wait for another input and that goes in infinity. Note that the input() must be under the while True:
def dictionary(word):
word = word.lower()
if word in data:
return data[word]
elif len(get_close_matches(word, data.keys()))>0:
yn = input("Did you mean %s instead? Enter 'Y' for yes, 'N' for no: " % get_close_matches(word, data.keys())[0])
if yn == 'Y':
return data[get_close_matches(word, data.keys())[0]]
elif yn == 'N':
return "The word doesn't exist. Please try again!"
else:
return "I don't understand."
else:
return ("Please try again.")
while True:
word = input("Enter a word: ")
output = dictionary(word)
if type(output) == list:
for item in output:
print(item)
else:
print(output)
i successfully ran the following code, but i was wondering whether i can
add while loop to my code to make my program ask for another word after the user enters a word.
import json
from difflib import get_close_matches
data = json.load(open("data.json"))
def meaning(w):
w = w.lower()
if w in data:
return data[w]
elif len(get_close_matches(w, data.keys())) > 0:
answer = input("Did you mean %s instead. Press Y if yes or Press N if no: " % get_close_matches(w, data.keys())[0])
if answer == "Y":
return data[get_close_matches(w, data.keys())[0]]
elif answer == "N":
return "The word doesn't exist. Please Check again."
else:
return "The word doesn't exist in english dictionary."
else:
return "The word doesn't exist. Please Check again."
word = input("Enter a word: ")
output = meaning(word)
if type(output) == list:
for items in output:
print(items)
else:
print(output)
input()
i am expecting the program to ask the user to enter another word after he enters a word and gets a result.
You can do something like this:
import json
from difflib import get_close_matches
data = json.load(open("data.json"))
def meaning(w):
w = w.lower()
if w in data:
return data[w]
elif len(get_close_matches(w, data.keys())) > 0:
answer = input("Did you mean %s instead. Press Y if yes or Press N if no: " % get_close_matches(w, data.keys())[0])
if answer == "Y":
return data[get_close_matches(w, data.keys())[0]]
elif answer == "N":
return "The word doesn't exist. Please Check again."
else:
return "The word doesn't exist in english dictionary."
else:
return "The word doesn't exist. Please Check again."
word = ""
while word != "q":
word = input("Enter a word or q to quit: ")
output = meaning(word)
if type(output) == list:
for items in output:
print(items)
else:
print(output)
This will keep looping until you enter q. I'm not sure what your json looks like so you may need some modification based on what the meaning function is doing.
Put a while loop around the code that asks for the input and processes it. Check for the end string and break out of the loop when you get it.
while True:
word = input("Enter a word: ")
if word == 'q':
break
output = meaning(word)
if type(output) == list:
for items in output:
print(items)
else:
print(output)
So I'm trying to figure out how I can make this simple little program to go back to the raw_input if the user inputs something else then "yes" or "no".
a = raw_input("test: ")
while True:
if a == "yes":
print("yeyeye")
break
elif a == "no":
print("nonono")
break
else:
print("yes or no idiot")
This is what I got so far, I'm new and it's hard to understand. Thanks in advance.
As #DavidG mentioned, just add your raw_input statement in loop:
while True:
a = raw_input("Enter: ")
if a == "yes":
print("You have entered Yes")
break
elif a == "no":
print("You have entered No")
break
else:
print("yes or no idiot")
Simply you can put the first instruction inside the loop; in this way, every time the user inserts a value different to yes or no you can print a message and wait to a new input.
while True:
a = raw_input("test: ")
if a == "yes":
print("yeyeye")
break
elif a == "no":
print("nonono")
break
else:
print("yes or no idiot")
Describe a condition checker for while and read input everytime when your condition is not meet. Inline returns are good for low quantity conditions but when your choice count is too much or condition in condition situations appear, inline returns are becoming trouble.
Thats why you must use condition checkers(like cloop) instead of inline returns.
cloop=True
while cloop:
a = raw_input("test: ")
if a == "yes":
print("yeyeye")
cloop=False
elif a == "no":
print("nonono")
cloop=False
else:
print("yes or no idiot")
cloop=True
I have created a code in which the user will input their choice which will continue in a loop if the variable 'contin' equals "yes". When the user enters the choice "no" or any other input it will print their overall answers or the error message and end the loop. Instead it then repeats the beginning of the function (in this case it's whether the user wanted to continue or not). Is there a way for me to prevent this from happening?
This is the code:
def userinput():
while True:
contin = input("Do you wish to continue the game? If so enter 'yes'. If not enter 'no'.")
if contin == 'yes':
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"']
guess = input("What symbol do you wish to change? ")
symbol_dictionary[guess] = input("Input what letter you wish to change the symbol to.(Make sure the letter is in capitals.) ")
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"'])
elif contin == ('no'):
print ("These were your overall answers:")
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"'])
if symbol_dictionary == {"#": "A","+":"C", "/":"Q", "0":"U", "8":"I",
"4":"R", "&":"E",'"':'D', "3":"L", "*":"M",
"%":"N", "2":"S", ":":"T", "1":"O",",":"J",
"$":"K", "!":"H", "7":"Z", "-":"Y", ".":"G",
"'":"W",")":"F", "6":"B", "5":"X", "9":"V"}:
print("Well done! You have completed the game!")
else:
print("Please enter a valid input.")
All you need to do is exit the function; add a return in your no branch:
elif contin == ('no'):
print ("These were your overall answers:")
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"'])
if symbol_dictionary == {"#": "A","+":"C", "/":"Q", "0":"U", "8":"I",
"4":"R", "&":"E",'"':'D', "3":"L", "*":"M",
"%":"N", "2":"S", ":":"T", "1":"O",",":"J",
"$":"K", "!":"H", "7":"Z", "-":"Y", ".":"G",
"'":"W",")":"F", "6":"B", "5":"X", "9":"V"}:
print("Well done! You have completed the game!")
# exit the function
return
Just add a break or a return at the end of the elif statement:
print("Well done! You have completed the game!")
break # or return
This will exit the loop. Break makes more sense in this context.
from sys import exit
def answer():
answer = raw_input("> ")
if answer == "Yes" or answer == "yes":
#going to next
joint()
elif answer == "No" or answer == "no":
print "You still have something, I know..."
again()
else:
fubar()
def again():
again = raw_input("> ")
if again == "Yes" or again == "yes":
#going to next
joint()
elif again == "No" or again == "no":
print "You still have something, I know..."
else:
fubar()
def fuck():
print "Fubar'd!"
def joint():
print "To be continue..."
def question():
print "Hi duuuude..."
raw_input("To say 'Hi' press Enter")
print "Can you help me?"
answer()
question()
Hi, can you help me with this? I`m trying to repeat the function "answer", when I get answer "NO". Im want to escape function "again"... And also is there a way to escape "answer == "Yes" or answer == "yes": " so no matter I write capital or small letter to accept the answer and not to write like a noob "Yes" or "yes"?
This is usually achieved with a while loop.
Edit: As pointed out, while loops are nice and clear, and avoid recursion limits.
Never thought a simple answer would generate so many votes....
Lets give you an example
while True:
ans = raw_input("Enter only y or n to continue").strip().lower()
if ans == "y":
print "Done!"
break
elif ans == "n":
print "No?"
else:
print "Not valid input."
The simplest solution to your problem is remove your again function, and recurse:
def answer():
ans = raw_input("> ")
if ans == "Yes" or ans == "yes":
#going to next
joint()
elif ans == "No" or ans == "no":
print "You still have something, I know..."
answer() # again()
else:
fubar()
I had to rename your answer variable to ans so that it didn't clash with the function name.
For the second question, you want either:
if answer.lower() == "yes":
or
if answer in ("Yes", "yes"):