cannot fix this "else" statement error - python-3.x

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

Related

Python program won't append more than one value

Whenever I try to append(guesses) to the all_guesses variable it seemingly replaces the existing value from the previous loop. I want the program to record down all the player's number of guesses per game round but it only record the most recent value. I made sure the variable isn't in the while loop so that it doesn't overwrite it, so what's wrong? I'm really new to python programming so I can't seem to figure this out. Each time I run the loop the guessed and all_guesses values are reset to their original.
This is a snippet of my program:
def main():
guesses = 0
guessed = []
all_guesses = []
guess = input('\nPlease guess a letter: ').lower()
letter = 'abcdefghi'
answer = random.choice(letter)
while len(guess) != 1 or guess not in letter:
print("\nInvalid entry! One alphabet only.")
guess = input('Please guess a letter: ')
while len(guess) < 2 and guess in letter:
if guess in guessed:
guess = input("\nYou've already guessed that! Try again: ").lower()
else:
if guess == answer:
guesses = guesses + 1
played = played + 1
print("\nCongratulations, that is correct!")
replay = input('Would you like to play again? Type y/n: ').lower()
all_guesses.append(guesses)
The short answer would be that all_guesses needs to be a global defined outside of main and the replay logic also needs to wrapped around main.
You seem to be missing logic, as you never modify guessed but expect to find things in there. And there are dead ends and other missing parts to the code. As best as I can guess, this is roughly what you're trying to do:
from random import choice
from string import ascii_lowercase as LETTERS
all_guesses = []
def main():
guessed = []
answer = choice(LETTERS)
guess = input('\nPlease guess a letter: ').lower()
while len(guess) != 1 or guess not in LETTERS:
print("\nInvalid entry! One alphabet only.")
guess = input('Please guess a letter: ').lower()
while len(guess) == 1 and guess in LETTERS:
if guess in guessed:
guess = input("\nYou've already guessed that! Try again: ").lower()
continue
guessed.append(guess)
if guess == answer:
print("\nCongratulations, that is correct!")
break
guess = input("\nIt's not that letter. Try again: ").lower()
all_guesses.append(len(guessed))
while True:
main()
replay = input('Would you like to play again? Type y/n: ').lower()
if replay == 'n':
break
print(all_guesses)

Set IF statment to check for specific characters, breaks while loop when using any character instead

I am new to python. I was making a guess the random number game, and I run into issues when having both int and str as inputs, I want the user to exit the program when pressing Q or q, while the game to check for numbers as well. After hours of googling and rewriting this is what I came up with:
#! Python3
import random
upper = 10
number = random.randint(1, upper)
print(number) #TODO: THIS LINE FOR TESTING ONLY
print("Guess a number between 1 and {}. Press Q to quit!".format(upper))
total_guesses = 0
guess = 0
while guess != number:
total_guesses += 1
guess = input()
if guess.isalpha():
if guess == "q" or "Q":
break
elif guess != "q" or "Q":
print("Please type in a valid guess.")
guess = 0
if guess.isnumeric():
guess = int(guess)
if guess == number:
print("Good job! You guessed the number in {} tries!.".format(total_guesses))
break
if guess < number:
print("Guess Higher!")
if guess > number:
print("Guess lower!")
else:
print("Valid inputs only")
guess = 0
This code ALMOST works as intended; issues I have now is that at line 13 and 14 the loop breaks every time when any letter is typed, even though I set the if statement to only check for Q or q, and I can't understand why this is doing it. Any help is appreciated!
if guess == 'q' or "Q":
The way this line is read by python is -
if guess == "q":
and also -
if "Q":
"Q" is a character, which means it's truthy. if "Q" returns True. Try:
if guess == "q" or guess == "Q":
if you feels that's too much, other options include -
if guess in ["Q", "q"]:
if guess.upper() == "Q":

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)))

How to trace the input error in my hangman program?

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.

Resources