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)
Related
import json
import difflib
from difflib import get_close_matches
data = json.load(open("data.json"))
def Translate (w):
x= 3
while x != 0:
w = w.lower()
if w in data:
return data [w]
elif len(get_close_matches(w, data.keys())) > 0:
yn = input ("Did you mean %s Instead? Enter Y for yes, or no press N if not: "% get_close_matches(w, data.keys())[0])
if yn == "Y":
return data[get_close_matches(w, data.keys())[0]]
elif yn == "N":
return "The word doesn't exist. Please check your spelling."
elif w.upper() in data: #in case user enters words like USA or NATO
return data[w.upper()]
elif w.title() in data: #if user entered "texas" this will check for "Texas" as well.
return data[w.title()]
else:
return "The word doesn't exist. Please double check it."
word = input("Enter word:")
print(Translate(word))
x -= 1
This what I trying to add in:
if x == 0:
input(" Would you like to keep searching? Y or N?")
elif yn == "Y":
continue
x+=3
elif yn == "N":
return "Have a nice day."
I trying to add a while loop to keep searching until the user wants to stop.
I'm still new to python if anybody can help me thankyou in advance!
You can do it in the following way!
while True:
in_put=input("Enter your word here or simply press return to stop the program\t")
if in_put:
"""DO stuff here"""
print(in_put)
else:
break
Change the program accordingly for your task!
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)
I'm a step away from completing my binary converter, though it keeps on repeating, it's and endless loop.
def repeat1():
if choice == 'B' or choice == 'b':
while True:
x = input("Go on and enter a binary value: ")
try:
y = int(x, 2)
except ValueError:
print("Please enter a binary value, a binary value only consists of 1s and 0s")
print("")
else:
if len(x) > 50:
print("The number of characters that you have entered is", len(x))
print("Please enter a binary value within 50 characters")
z = len(x)
diff = z - 50
print("Please remove", diff, "characters")
print(" ")
else:
print(x, "in octal is", oct(y)[2:])
print(x, "in decimal is", y)
print(x, "in hexidecimal is", hex(y)[2:])
print(" ")
def tryagain1():
print("Type '1' to convert from the same number base")
print("Type '2' to convert from a different number base")
print("Type '3' to stop")
r = input("Would you like to try again? ")
print("")
if r == '1':
repeat1()
print("")
elif r == '2':
loop()
print("")
elif r == '3':
print("Thank you for using the BraCaLdOmbayNo Calculator!")
else:
print("You didn't enter any of the choices! Try again!")
tryagain1()
print("")
tryagain1()
I'm looking for a way to break the loop specifically on the line of code "elif r== '3':. I already tried putting 'break', but it doesn't seem to work. It keeps on asking the user to input a binary value even though they already want to stop. How do I break the loop?
elif r == '3':
print("Thank you for using the BraCaLdOmbayNo Calculator!")
return 0
else:
print("You didn't enter any of the choices! Try again!")
choice = try again()
if choice == 0:
return 0
print("")
tryagain1()
return is suppose to be used at the end of the Function or code when you have nothing else to do
I have written the Python code below (actually it's my solution for an exercise from page 80 of "Teach yourself Python in 24 hours").
The idea is: there are 4 seats around the table, the waiter knows for how much each seat ordered, enters those 4 amounts and gets a total.
If the raw_input provided is not a number (but a string) my code kicks the person out. The goal, however, is to give an error message ("this entry is not valid") and ask for the input again - until it's numeric. However, I can't figure out how to ask the user for the raw input again - because I am already inside a loop.
Thanks a lot for your advice!
def is_numeric(value):
try:
input = float(value)
except ValueError:
return False
else:
return True
total = 0
for seat in range(1,5):
print 'Note the amount for seat', seat, 'and'
myinput = raw_input("enter it here ['q' to quit]: ")
if myinput == 'q':
break
elif is_numeric(myinput):
floatinput = float(myinput)
total = total + floatinput
else:
print 'I\'m sorry, but {} isn\'t valid. Please try again'.format(myinput)
break
if myinput == 'q':
print "Goodbye!"
else:
total = round(total, 2)
print "*****\nTotal: ${}".format(total)
print "Goodbye!"
Generally, when you don't know how many times you want to run your loop the solution is a while loop.
for seat in range(1,5):
my_input = raw_input("Enter: ")
while not(my_input == 'q' or isnumeric(my_input)):
my_input = raw_imput("Please re-enter value")
if my_input == 'q':
break
else:
total += float(my_input)
As Patrick Haugh and SilentLupin suggested, a while loop is probably the best way. Another way is recursion- ie, calling the same function over and over until you get a valid input:
def is_numeric(value):
try:
input = float(value)
except ValueError:
return False
else:
return True
def is_q(value):
return value == 'q'
def is_valid(value, validators):
return any(validator(input) for validator in validators)
def get_valid_input(msg, validators):
value = raw_input(msg)
if not is_valid(value, validators):
print 'I\'m sorry, but {} isn\'t valid. Please try again'.format(value)
value = get_valid_input(msg, validators)
return value
total = 0
for seat in range(1,5):
print 'Note the amount for seat', seat, 'and'
myinput = get_valid_input("enter it here ['q' to quit]: ", [is_q, is_numeric])
if myinput == 'q':
break
elif is_numeric(myinput):
floatinput = float(myinput)
total = total + floatinput
if myinput == 'q':
print "Goodbye!"
else:
total = round(total, 2)
print "*****\nTotal: ${}".format(total)
print "Goodbye!"
In the above code, get_valid_input calls itself over and over again until one of the supplied validators produces something truthy.
total = 0
for seat in range(1,5):
incorrectInput = True
while(incorrectInput):
print 'Note the amount for seat', seat, 'and'
myinput = raw_input("enter it here ['q' to quit]: ")
if myinput == 'q':
print 'Goodbye'
quit()
elif is_numeric(myinput):
floatinput = float(myinput)
total = total + floatinput
incorrectInput = False
else:
print 'I\'m sorry, but {} isn\'t valid. Please try again'.format(myinput)
total = round(total, 2)
print "*****\nTotal: ${}".format(total)
print "Goodbye!"
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