How to trace the input error in my hangman program? - python-3.5

I have an error in the input section of the code. Normally it is working well but in this code, I do not know why this is showing error.
print("Welcome to the game, Hangman!")
print("I am thinking of a word that is ",len(secretWord)," letters long.")
print("-------------")
n=8
G_new=''
k=''
while n>0 and secretWord!=G_new:
print("You have ",n," guesses left.")
G_old=[G_new,]
print("Available letters: ",getAvailableLetters (G_old)
**k=input("Please guess a letter: ")** #error in this line
g=k.lower()
G_new=G_old+[g,]
if isWordGuessed(secretWord, G_new)==True and g not in G_old:
print("Good guess: ",getGuessedWord(secretWord, G_new))
elif isWordGuessed(secretWord, G_new)==True and g in G_old:
print("Oops! You've already guessed that letter: ",getGuessedWord(secretWord, G_old))
else:
print("Oops! That letter is not in my word: ",getGuessedWord(secretWord, G_old))
n-=1
print("-------------")
if n==0 and secretWord!=G_new:
print("Sorry, you ran out of guesses. The word was ",str(secretWord),".")
elif n>=0 and secretWord==G_new:
print("Congratulations, you won!")

Count the ( and ):
print("Available letters: ",getAvailableLetters (G_old)
1 2 2 1????
As a general rule, if you get a syntax error that says "unexpected" or whatever, the error is invariably NEVER on the line in the error message - it's actually somewhere EARLIER, where you made a typo. The specified error location is merely the first place where the parser realized there IS a problem.

Related

Trying to exit from a program is not working

I'm currently teaching myself python from books, YouTube, etc. Recently, I've started from Python Tutorial - Python for Beginners [Full Course]. I've been trying to make some bigger programs by myself (learning from python documentation) than the ones in this video. Hence, this is my question:
I'm trying to find a solution for how to exit from a function the_func after pressing keys (n, q ,e). Unfortunately, after choosing an option to not try again, the loop is still running. This is the output copied from the terminal:
Guess the secret number: 1
Guess the secret number: 2
Guess the secret number: 3
Sorry, you are loser!
-------------------------
Would you tray again? Y/N
y
Guess the secret number: 9
The secret number was 9.
You are won!
-------------------------
Would you tray again? Y/N
n
Thank you!
Guess the secret number:
You can see that even after choosing n, it's starting again.
This is the code:
# Guessing Game
def the_func() :
again = 'Would you tray again? Y/N'
scecret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = int(input("Guess the secret number: "))
guess_count += 1
if guess == scecret_number:
print(f"The secret number was {scecret_number}.\nYou are won!")
break
else:
print("Sorry, you are loser!")
print("-" * int(len(again)), "\n")
print(again)
answer = input(" ")
while True:
if answer.lower() == "y":
the_func()
#elif answer.lower() == "n":
if answer.lower() in {'n', 'q', 'e'}:
print("Thank you!")
#return
break
# else:
# print("Sorry, that was an invalid command!")
the_func()
the_func()
Any help is appreciated.
The problem you are experiencing is known as Recursion. In simple words, the function is getting called repeatedly at the end of it. Here's the example that might clear it more to you:
def foo()
while True:
print('xyz')
break
foo() # Calling the function at the end causes recursion, i.e., infinite looping of the function (unless 'it is returned before the call')
foo()
You might ask, what is the solution?
As said above, you can prevent infinite recursion of a function (if you want to), by implicit returning the function using return.
Your answer is present in your code only. Let me show you where:
while True:
if answer.lower() == "y":
the_func()
#elif answer.lower() == "n":
if answer.lower() in {'n', 'q', 'e'}: # I would use 'elif' here, if the above 'if' statement did not have the calling of the same function. But, here, using 'if' or 'elif' doesn't matter really.
print("Thank you!")
return
#break
#else:
#print("Sorry, that was an invalid command!")
I hope you understood what you are doing wrong, and if you have any doubts, just add a comment and I would help as fast as I can.
Haaa.. DONE, So what we need
while True:
if answer.lower() == "y":
return the_func() ***# <= add return to the_func()***
if answer.lower() in {'n', 'q', 'quit', 'e', 'exit'}:
print("Thank you!")
return
#the_func() #<== mark as comment, and func not will bee looped again the_func()
the_func()
However, #Alex thank you!

I dont know how to program one part of a word guess program

I am creating a guess a letter game in python. the program chooses a random word from a file and the user has the amount of letters to guess the letters to the word. There is one part I am having trouble coding. I need to display the word as dashes and after every guess change the dashed word to include the correctly guessed letters in their corresponding position. So the output looks something like this.
Welcome to Guess a Letter!
Your word has 10 letters
You have 10 incorrect guesses.
Here is the word:
Enter a letter: e
Awe, shucks. You missed with that letter
Enter a letter: a
You got a hit! Here's what the word looks like now:
-------a-a
Enter a letter: o
Awe, shucks. You missed with that letter
Enter a letter: u
Awe, shucks. You missed with that letter
Enter a letter: i
You got a hit! Here's what the word looks like now:
---i---a-a
Enter a letter: y
You got a hit! Here's what the word looks like now:
-y-i---a-a
Enter a letter: t
You got a hit! Here's what the word looks like now:
-y-i-t-ata
Enter a letter: l
You got a hit! Here's what the word looks like now:
ly-i-t-ata
Enter a letter: s
You got a hit! Here's what the word looks like now:
lysist-ata
Enter a letter: r
You got a hit! Here's what the word looks like now:
lysistrata
You won!
Great job!
so here is what i have so far
import random
def pick_word_from_file():
'''Read a file of words and return one word at random'''
file = open("wordlist.txt", 'r')
words = file.readlines()
file.close()
global word #globalizes the variable "word"
word = random.choice(words).strip("\n")
global guesses
guesses = len(word) #number of guesses user has according to number of letters
print(word)
def dashed_word(): #this function turns the word into dashes
global hidden_word #globalizes the variable "hidden_word"
hidden_word = ""
for letter in word: #this for loop changes all the letters of the word to dashes
if letter != " ":
hidden_word = hidden_word + "-"
print(hidden_word)
list(hidden_word)
def game_intro(): #introduces word game rules
print("Welcome to Guess a Word!\n")
print("Your word has",len(word),"letters")
print("You have",len(word),"incorrect guesses.")
print("Only guess with lower case letters please!")
def game(): #this is the main games function
global guess
for letter in range(len(word)):
guess = input("Please enter a lowercase letter as your guess: ") #asks user for lowercase letter as their guess
new_hidden_word = ''
random_int = 0
int(random_int)
for i in range(len(word)):
if guess == word[i:i+1]:
print("Lucky guess!")
print(guess, "is in position", i+1)
hidden_word[i] = guess
hidden_word.join(' ')
print(hidden_word)
random_int = 1
if random_int == 0:
print("Unlucky")
def main(): #this runs all the functions in order
pick_word_from_file()
game_intro()
dashed_word()
game()
main()
Just need help with what is in the game() function
Since strings a immutable, I would use a list to keep track of the guesses and then transfer that to a string in order to print it out. Here is your code modified to reflect those changes :
import random
def pick_word_from_file():
'''Read a file of words and return one word at random'''
file = open("wordlist.txt", 'r')
words = file.readlines()
file.close()
global word #globalizes the variable "word"
word = random.choice(words).strip("\n")
global guesses
guesses = len(word) #number of guesses user has according to number of letters
print(word)
def dashed_word(): #this function turns the word into dashes
global hidden_word #globalizes the variable "hidden_word"
hidden_word = []
for letter in word: #this for loop changes all the letters of the word to dashes
if letter != " ":
hidden_word.append ("-")
print_out = ''
print(print_out.join (hidden_word))
def game_intro(): #introduces word game rules
print("Welcome to Guess a Word!\n")
print("Your word has",len(word),"letters")
print("You have",len(word),"incorrect guesses.")
print("Only guess with lower case letters please!")
def game(): #this is the main games function
global guess
for letter in range(len(word)):
guess = input("Please enter a lowercase letter as your guess: ") #asks user for lowercase letter as their guess
new_hidden_word = ''
random_int = 0
int(random_int)
for i in range(len(word)):
if guess == word[i:i+1]:
print("Lucky guess!")
print(guess, "is in position", i+1)
hidden_word[i] = guess
print_out = ''
print(print_out.join (hidden_word))
random_int = 1
if random_int == 0:
print("Unlucky")
def main(): #this runs all the functions in order
pick_word_from_file()
game_intro()
dashed_word()
game()
main()
I group all functions into one so we don't need to declare global variables. I also add something:
use .lower() to accept uppercase input
a statement telling user how many guesses left
win and lose condition
import random
def game():
# pick_word_from_file()
# using with to close the file automatically
with open("wordlist.txt") as f:
wordlist = f.readlines()
word = random.choice(wordlist).strip("\n")
# game_intro()
print("Welcome to Guess a Word!\n")
print("Your word has", len(word), "letters")
# why we need to say incorrect guesses from the start?
# print("You have", len(word), "incorrect guesses.")
# dashed_word()
# use a list to save letters because string is immutable
hidden_word = ["-" for w in word]
print("".join(hidden_word))
# number of guesses equal to length of word
for guesses in range(len(word)):
# tell user how many guesses left
print(f"You have {len(word) - guesses} guesses left.")
# use .lower() so user can also input uppercase letter
guess = input("Please enter a letter as your guess: ").lower()
change = False
for i in range(len(word)):
if word[i] == guess:
hidden_word[i] = guess
change = True
if change:
print("You got a hit! Here's what the word looks like now:")
print("".join(hidden_word))
else:
print("Awe, shucks. You missed with that letter.")
if "".join(hidden_word) == word:
print("You won! Great job!")
break
# you lose when you are out of guesses
else:
print("You lose.")
game()
Output:
"""
Welcome to Guess a Word!
Your word has 10 letters
----------
You have 10 guesses left.
Please enter a letter as your guess: E
Awe, shucks. You missed with that letter.
You have 9 guesses left.
Please enter a letter as your guess: A
You got a hit! Here's what the word looks like now:
-------a-a
You have 8 guesses left.
Please enter a letter as your guess: O
Awe, shucks. You missed with that letter.
You have 7 guesses left.
Please enter a letter as your guess: U
Awe, shucks. You missed with that letter.
You have 6 guesses left.
Please enter a letter as your guess: I
You got a hit! Here's what the word looks like now:
---i---a-a
You have 5 guesses left.
Please enter a letter as your guess: Y
You got a hit! Here's what the word looks like now:
-y-i---a-a
You have 4 guesses left.
Please enter a letter as your guess: T
You got a hit! Here's what the word looks like now:
-y-i-t-ata
You have 3 guesses left.
Please enter a letter as your guess: L
You got a hit! Here's what the word looks like now:
ly-i-t-ata
You have 2 guesses left.
Please enter a letter as your guess: S
You got a hit! Here's what the word looks like now:
lysist-ata
You have 1 guesses left.
Please enter a letter as your guess: R
You got a hit! Here's what the word looks like now:
lysistrata
You won! Great job!
"""

Python hangman script will not work if there are spaces

current code -
string = input("Enter word")
guessed= False
alphabet = 'abcdefghijklmnopqrstuvwxyz'
guesses=[]
while guessed== False:
char = input("Enter one letter :").lower()
if len(char) == 1:
if char not in alphabet:
print("Error you have not entered a letter")
elif char in guesses:
print("Letter has been guessed before")
elif char not in string:
print("Sorry this letter is not part of the word")
guesses.append(char)
elif char in string:
print("Well done")
guesses.append(char)
else:
print("Error")
else:
print("Only 1 character should be entered")
status= ''
if guessed == False:
for letter in string:
if letter in guesses:
status+=letter
if status==string:
print("Congratulations you have won")
guessed=True
else:
status+='_'
print(status)
If the word is "hello world" and the user guessed the words correctly the output below is displayed:
Well done
hello_world
Enter one letter :
The user is asked again to enter another letter even though the word is found. Im not sure on how to fix this.
I would add an extra condition for spaces like this
for letter in string:
if letter in guesses:
status+=letter
if status==string:
print("Congratulations you have won")
guessed=True
elif letter == ' ':
status += ' '
else:
status+='_'
This way the user sees that there are actually two words but does not have to enter a space explicitly.
Output
Enter one letter :h
Well done
h____ _____
Enter one letter :e
Well done
he___ _____
...
Enter one letter :d
Well done
Congratulations you have won
hello world
hello world contains a space, and yet space is not allowed as a guessed letter, so even if the user guesses all the right letters, the status will at best become hello_world, which is not equal to hello world, leaving the game unfinished.

Syntax Error on while command in python 3 program

I am a beginner in python 3. Made a program. it was working fine but then i change it a bit and now its giving syntax error on line 2 of give code.I have only uploaded a patch of total code
i tired retyping it. I also tried executing it on different IDEs. But nothing worked
print('You have a total of {} guesses'.format(len(answer))
while count < len(answer):
guess = input('Enter the letter: ') #input of the guesses
guess = guess.lower() # all words are in lowercase
count += 1
print('You have {} guesses left'.format(len(answer)-count) #to tell the total guess left
# we need to iterate over the answer to check guess in answer
for i in range(len(answer)):
if answer[i] == guess:
display[i] = guess #replacing corresponding '_' with letter
print(' '.join(display))
if display == answer: #to check and stop unneccessary repitations
break
if display == answer:
print('You Won!!!!')
else:
print('You Lost!!!!')
again = input('Do you want to play again(Y/N)?' )
if again.lower() == 'n':
is_again = False
print('Good Bye!!!')
it is giving a syntax error on while command. it is like this:
while count < len(answer):
^
SyntaxError: invalid syntax
You're missing a parenthesis! The line:
print('You have {} guesses left'.format(len(answer)-count)
^----------------------------------------------------?
^-----------------^
^------^
is missing a matching parenthesis for the print. It should be:
print('You have {} guesses left'.format(len(answer)-count))
Your first line is missing a parenthesis as well:
print('You have a total of {} guesses'.format(len(answer))
Should be:
print('You have a total of {} guesses'.format(len(answer)))

cannot fix this "else" statement error

the second "else" statement gives a syntax error. I don't understand why. what is wrong with the code?
Pardon me, still a beginner
while True:
guess = input("Guess a letter or the whole word: ")
if guess == word:
print("Yaye, you've won and have saved my neck!")
break
else:
for letter in letters:
if letter in letters:
continue
else:
guesses -= 1
word_guess(guesses)
if guesses == 0:
break
You can see in the Python 3 flow control documentation an example of an if statement. It can only have one else statement because that is what is run when all other cases (if and elif) didn't match. When are you expecting the second else to run?
As was pointed out in another answer, indentation in python matters.
Is this perhaps the indentation you are looking for?
while True:
guess = input("Guess a letter or the whole word: ")
if guess == word:
print("Yaye, you've won and have saved my neck!")
break
else:
for letter in letters:
if letter in letters:
continue
else:
guesses -= 1
word_guess(guesses)
if guesses == 0:
break

Resources