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)
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)
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!
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()
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
I have a dictionary object;
secret = {"word" : secretWord}
secretWord being an argument for a string with a single word inside. I also have a string generating an asterisk (*) for every character in the secretWord. In my code I have input from the user which gives a letter.
What I wish to accomplish is to check within the dictionary object secretWord, and if so, replace any asterisk with the input where relevant. However I am not sure how to then save this as a new argument, and then use the next input on the new argument.
Sorry if my question/problem isn't clear, as I am struggling how to word it.
What I want to happen:
for example the secretWord could be 'PRECEDENCE'
>>>
WORD : **********
Guess a letter: e
**E*E*E**E
Guess a letter: p
P*E*E*E**E
etc
What happens:
>>>
WORD : **********
Guess a letter: e
**E*E*E**E
Guess a letter: p
P*********
etc
My current Code:
import random
import sys
def diction(secretWord, lives):
global guess
global secret
secret = {"word" : secretWord, "lives" : lives}
guess = len(secret["word"]) * "*"
print (secret["word"])
print ("WORD: ", guess)
fileName = input("Please insert file name: ")
def wordGuessed(guess, secret):
if guess == secret["word"]:
print ("word is guessed")
if guess != secret["word"]:
print ("word is not guessed")
def livesLeft(inpu):
if inpu not in secret["word"]:
secret["lives"] = secret["lives"] - 1
print("Lives left: ", secret["lives"])
if inpu in secret["word"]:
print("Correct guess")
print(secret["lives"])
def guessCheck(inpu):
for char in secret["word"].lstrip():
if char == inpu:
print (char, end= "")
elif char != secret["word"]:
print ("*", end="")
try:
f = open(fileName)
content = f.readlines()
except IOError as e :
f = None
print("Failed to open", fileName, "- program aborted")
sys.exit()
Run = True
while Run == True:
levelIn = input("Enter difficulty (easy, intermediate or hard): ").lower()
if levelIn == ("easy"):
lives = 10
elif levelIn == ("intermediate"):
lives = 8
elif levelIn == ("hard"):
lives = 5
else:
print("Please input a valid difficulty.")
break
secretWord = (random.choice(content))
secretWord = secretWord.replace("\n", "")
diction(secretWord, lives)
wordGuessed(guess, secret)
while secret["lives"] > 0:
inpu = input("Guess a letter: ").upper()
livesLeft(inpu)
guessCheck(inpu)
if secret["lives"] == 0:
print ("You have no lives left – you have been hung!")
print ("The word was,", secret["word"])
You need to track the guesses made so far, and use those to display the word. Use a set to track what the player already guessed at:
guessed = set()
So that you can do:
if inpu in guessed:
print('You already tried that letter!')
else:
guessed.add(inpu)
whenever a user makes a guess.
You can then use that set to display the word revealed so far:
for char in secret["word"].lstrip():
if char in guessed:
print (char, end="")
else:
print ("*", end="")