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!
Related
I am trying to make a shopping list, however every time I delete an item it leaves a big gap and looks very awkward, please can someone help, I am still very new to it all and I have only been learning a month or two so a simple answer would be very much appreciated:
def subtract(user):
x = 0
while x == False:
answer = input("What would you like to subtract?")
if answer in user:
user = user.replace(answer,"")
y = 0
print("your list is:" + user)
add_or_subtract(user)
x == True
break
else:
print ("sorry, I do not recognise this, please try again.")
def add(user):
x = 0
while x == False:
answer = input(str("what would you like to add?".lower()))
if answer in user:
print ("sorry, this is already in the list")
else:
user = user + "\n" + answer
print ("Your list is: " + user)
answer = input("are you finished adding?".lower())
if answer in ("yes", "yea", "ye"):
answer1 = input("do you want to subtract or finish?")
if answer1 in ("subtract"):
subtract(user)
x == True
break
elif answer1 in ("finish"):
print (user)
x == True
break
else:
print("Sorry I do not recognise this")
def add_or_subtract(user):
x = 0
while x == False:
answer = input ("do you want to add or subtract or finish?".lower())
if answer in ("add","addition"):
add(user)
x == True
break
elif answer in ("subtract","takeaway"):
subtract (user)
x == True
break
elif answer in ("complete", "finish"):
print ("your final list is: " + user)
x == True
break
else:
print ("sorry i do not recognise this")
def initial(user):
x = 0
while x == False:
user = input("please type out your first item:".lower())
content = input(str("your first item is "+ user + " are you content with that?".lower()))
if content in "no":
user = ""
continue
elif content in "yes":
add_or_subtract(user)
x == True
break
shopping = ""
initial(shopping)
Also is there a better way of doing this, I feel like there is, could I use a list to record all the items and is there a way I can store the existing list into a database and then re-use that when updating?
The reason why you have a gap is because you are forgetting the \n character (newline character), so when replacing put '\n' before answer:
def subtract(user):
x = 0
while x == False:
answer = input("What would you like to subtract?")
if answer in user:
user = user.replace('\n'+answer,"") # where it is edited
y = 0
print("your list is:" + user)
add_or_subtract(user)
x == True
break
else:
print ("sorry, I do not recognise this, please try again.")
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)
I want the user to be able to quit this program at any point by typing in "quit".
Is there a way to do this with one instance of a break statement, or do I need to add a break to every "if y ==" statement in my code?
fruits = []
notfruits = []
print(fruits)
print(notfruits)
while len(fruits) < 3 or len(notfruits) < 3: # replaced `and` with `or`
print("Please enter fruits or notfruits:") #
y = str(input(": ")) # moved the input here
if y == "fruits":
while len(fruits) < 3:
x = str(input(": "))
x = x.strip()
if x in notfruits:
print(x + " is not a fruit!")
elif x in fruits:
print(x + " is already in the list!")
else:
fruits.append(x)
print(fruits)
elif y == "notfruits":
while len(notfruits) < 3:
x = str(input(": "))
x = x.strip()
if x in fruits:
print(x + " is a fruit!")
elif x in notfruits:
print(x + " is already in the list!")
else:
notfruits.append(x)
print(notfruits)
elif y == "clearfruits":
del fruits[:]
elif y == "clearnotfruits":
del notfruits[:]
elif y == "quit":
break
else:
print("Not a valid option!")
Create a function, use it each time you taker an input, call "exit()" to leave
For example
import sys
def check_quit(inp):
if inp == 'quit':
sys.exit(0)
You can use
import sys
sys.exit(0)
to immediately stop executing further program statements, so something like
elif y == "quit":
import sys
sys.exit(0)
should work.
Documentation: https://docs.python.org/3.5/library/sys.html#sys.exit
I think that both writing a function and using sys.exit are overkill for what OP asked, depending whether you're trying to break out of the loop or exit the program entirely
Specifically regarding your question, you can break right after your input() and it will exit the loop without executing the rest of the run. (BTW, you don't need to cast input to a string, input is a string by default)
y = input(": ")
if y.lower() == "quit":
break
if y == "fruits":
What i want to accomplish is when you input a letter and if the letter is correct there will be an automatic response that it was correct but it will not be the same response every time a letter of the correct answer inputted.
I made a list of responses and placed a random function for the list
reaction=['good job','lucky guess!',you\'re on a roll]
react=random.choice(reaction)
I tried placing it after the
for letter in rand:
rand_list.append(letter)
but this is not what I want because what this does is it gives the same response over and over again on each correct letter you input and would change at the next word that you'll be guessing.
The complete code is:
import random
alphabeth = 'abcdefghijklmnopqrstuvwxyz'
rand_list = []
guessed_list = []
def prepWord():
global rand, guessed_list, blank, rand_list,good,react_good
react_good = ['Good job!', 'Lucky guess!', 'Took you a while to guess that letter!', 'You\'re on a roll!']
words = ['note', 'pencil', 'paper','foo']
rand = random.choice(words)
guessed_list = []
blank = ['_']*len(rand)
rand_list = []
for letter in rand:
rand_list.append(letter)
startPlay()
def startPlay():
print('Welcome to Hangman. You have 8 tires to guess the secret word.')
gameQ = input('Ready to play Hangman? y or n: ')
if gameQ == 'y' or gameQ == 'Y':
print('Guess the letters:')
print(blank)
checkAnswer()
elif gameQ == 'n' or gameQ == 'N':
print('goodbye')
print('*********************')
else:
print('Invalid answer. Please try again')
startPlay()
def playAgain():
again = input('Would you like to play again? y or n --> ')
if again == 'y':
prepWord()
elif again == 'n':
print('Thanks for playing')
else:
print('Invalid answer. Please type y or n only')
print(' ')
playAgain()
def checkAnswer():
tries = 0
x = True
while x:
answer = input('').lower()
if answer not in guessed_list:
guessed_list.append(answer)
if len(answer)>1:
print('One letter at a time.')
elif answer not in alphabeth:
print('Invalid character, please try again.')
else:
if answer in rand:
print("The letter {} is in the word.".format(answer))
indices = [b for b, letter in enumerate(rand_list) if letter == answer]
for b in indices:
blank[b] = answer
print (blank)
else:
print ("I'm sorry the letter {} is not in the word. Please try again.".format(answer))
tries +=1
if tries
if tries == 8:
print('Game over. You are out of tries')
playAgain()
else:
print('Letter {} already used. Try another.'.format(answer))
if '_' not in blank:
print('You guessed the secret word. You win!')
final_word = 'The secret word is '
for letter in blank:
final_word += letter.upper()
print(final_word)
print('')
x = False
playAgain()
prepWord()
You have to call random each time you want a new message. Calling it once and saving the result means your react variable never changes. The following defines the reaction list at the top for easy editing, but has this line in checkAnswer() that calls random.choice every time a correct letter is entered print(random.choice(reaction)).
import random
alphabeth = 'abcdefghijklmnopqrstuvwxyz'
rand_list = []
guessed_list = []
reaction=["good job","lucky guess!","you're on a roll"]
def prepWord():
global rand, guessed_list, blank, rand_list,good,react_good
react_good = ['Good job!', 'Lucky guess!', 'Took you a while to guess that letter!', 'You\'re on a roll!']
words = ['note', 'pencil', 'paper','foo']
rand = random.choice(words)
guessed_list = []
blank = ['_']*len(rand)
rand_list = []
for letter in rand:
rand_list.append(letter)
startPlay()
def startPlay():
print('Welcome to Hangman. You have 8 tires to guess the secret word.')
gameQ = input('Ready to play Hangman? y or n: ')
if gameQ == 'y' or gameQ == 'Y':
print('Guess the letters:')
print(blank)
checkAnswer()
elif gameQ == 'n' or gameQ == 'N':
print('goodbye')
print('*********************')
else:
print('Invalid answer. Please try again')
startPlay()
def playAgain():
again = input('Would you like to play again? y or n --> ')
if again == 'y':
prepWord()
elif again == 'n':
print('Thanks for playing')
else:
print('Invalid answer. Please type y or n only')
print(' ')
playAgain()
def checkAnswer():
tries = 0
x = True
while x:
answer = input('').lower()
if answer not in guessed_list:
guessed_list.append(answer)
if len(answer)>1:
print('One letter at a time.')
elif answer not in alphabeth:
print('Invalid character, please try again.')
else:
if answer in rand:
print("The letter {} is in the word.".format(answer))
print(random.choice(reaction))
indices = [b for b, letter in enumerate(rand_list) if letter == answer]
for b in indices:
blank[b] = answer
print (blank)
else:
print ("I'm sorry the letter {} is not in the word. Please try again.".format(answer))
tries +=1
if tries == 8:
print('Game over. You are out of tries')
playAgain()
else:
print('Letter {} already used. Try another.'.format(answer))
if '_' not in blank:
print('You guessed the secret word. You win!')
final_word = 'The secret word is '
for letter in blank:
final_word += letter.upper()
print(final_word)
print('')
x = False
playAgain()
prepWord()
I rewrote some of your code. I'm posting it here so hopefully looking at the difference will be helpful to you. Some of the changes are:
No recursion: while it can be very powerful, it's usually safer to use a loop. For example in startPlay() every time the user enters an invalid character you open another nested startPlay() function. This could lead to many nested functions loaded at once. Worse startPlay() can call checkAnswer() which can call playAgain() which can call prepWord() which can call startPlay(). The longer the user plays, the more memory your program will take. It will eventually crash.
No global variables that change. While defining global variables at the top of the script can be useful, calling globals and editing them in a function is risky and makes your code harder to debug and reuse. It's better to pass what is needed from function to function. Some might argue against defining any variables at the top, but I find it useful. Especially if someone else will customize the details, but does not need to understand how the code works.
Some details working with lists and strings are different. You don't need to define the alphabet, that already exists as string.ascii_lowercase. You can check for characters in a string directly with the equivalent of if 'p' in 'python': so you never have to convert the chosen word into a list. You can covert lists back to strings with join like " ".join(blank) which converts blank from a list to a string with a space between each element of blank. Using a different string before the join would change the character inserted between each element.
I hope this helps you. You can do whatever you want with this code:
import random
import string
# Global and on top for easy editing, not changed in any function
words = ['note', 'pencil', 'paper','foo']
react_good = ["Good job!",
"Lucky guess!",
"Took you a while to guess that letter!",
"You're on a roll!"]
def game():
games = 0
while start(games): # Checks if they want to play.
games += 1
play_game()
def play_game(): # returns True if won and returns False if lost.
rand_word = random.choice(words) # Choose the word to use.
blank = ['_']*len(rand_word)
guessed = []
tries = 0
while True: # Not infinite, ends when a return statement is called
print("")
print(" ".join(blank)) # Converting to string first looks better
answer = input('Guess a letter: ').strip().lower() # remove whitespace
if answer == 'exit' or answer == 'quit':
return False # Exit Game
elif len(answer) != 1:
print('One letter at a time.')
elif answer not in string.ascii_lowercase: # same as alphabet string
print('Invalid character, please try again.')
elif answer in guessed:
print('Letter {} already used. Try another.'.format(answer))
elif answer in rand_word: # Correct Guess
# Update progress
indices = [i for i, x in enumerate(rand_word) if x == answer]
for i in indices:
blank[i] = answer
# Check if they have won
if blank == list(rand_word): # Or could convert blank to a string
print('You guessed the secret word. You win!')
print('The secret word is ' + rand_word.upper())
print('')
return True # Exit Game
guessed.append(answer)
print("The letter {} is in the word.".format(answer))
print(random.choice(react_good))
else: # Incorrect Guess
tries += 1
# Check if they have lost.
if tries >= 8:
print('Game over. You are out of tries')
return False # Exit Game
print ("I'm sorry the letter {} is not in the word. Please try again.".format(answer))
guessed.append(answer)
def start(games = 0): # Gives different messages for first time
if games == 0: # If first time
print('Welcome to Hangman. You have 8 tires to guess the secret word.')
# Loops until they give a valid answer and a return statement is called
while True:
# Get answer
if games > 0: # or just 'if games' works too
game_q = input('Would you like to play again? y or n --> ')
else:
game_q = input('Ready to play Hangman? y or n: ')
# Check answer
if game_q.lower() == 'y':
return True
elif game_q.lower() == 'n':
if games > 0:
print('Thanks for playing')
else:
print('goodbye')
print('*********************')
return False
else:
print('Invalid answer. Please try again')
game()