Could someone look at my code and see why I'm getting a syntax error on line 41, please?''' This is program that gives the user the option of playing a number guessing
game where they have the option of unlimited guesses between 1 and 100 or only
5 guesses.
'''
menu = """
1. Play Game unlimited guesses
2. Play Game with 5 guesses
0. Exit
"""
choice = None
Set the Loop
while (choice != 0):
print (menu)
gameCode = int(input("Would you like to play a game?"))
if (gameCode == 1):
print ("Guess a number between 1 & 100:")
x = random.randint (1, 100)
guess = int(input())
while (guess != x):
if (guess < x):
guess = int(input("Your guess is too low, try again:"))
count = count+1
elif (guess > x):
guess = int(input("Your guess is too high, try again:"))
count = count+1
elif (guess == x):
print ("Congratulations, you guessed the number in", count,
"attempts!")
elif (gameCode == 2):
for i in range (1,6,1):
guess = int(input("Enter a guess between 1 and 100:")
if (guess == x):
print ("You got it!")
else:
print ("Sorry, incorrect!)
if (guess == x):
print ("You won!")
else:
print ("You lost!")
elif (guess == 0):
break
else:
print ("You entered an invalid game code. Goodbye!")
After correcting some errors it looks like this:
import random
menu = """
1. Play Game unlimited guesses
2. Play Game with 5 guesses
0. Exit
"""
choice = None
while (choice != 0):
print (menu)
gameCode = int(input("Would you like to play a game?"))
if (gameCode == 1):
count=0
print ("Guess a number between 1 & 100:")
x = random.randint (1, 100)
guess = int(input())
while (guess != x):
count = count+1
if (guess < x):
guess = int(input("Your guess is too low, try again:"))
elif (guess > x):
guess = int(input("Your guess is too high, try again:"))
print(f"Congratulations, you guessed the number in {count} attempts!")
elif (gameCode == 2):
for i in range (1,6,1):
guess = int(input("Enter a guess between 1 and 100:"))
if (guess == x):
print ("You got it!")
else:
print ("Sorry, incorrect!")
elif (gameCode == 0):
break
else:
print ("You entered an invalid game code. Goodbye!")
Related
I started to make a number guessing game. Here is the code I wrote:
import random
print('Hello what is your name?')
NamePlayer = input()
print('Well, ' + NamePlayer + ' I am thinking of a number between 1 and 20')
randomnumber = random.randint(1, 20)
print('Take a guess.')
for Guesstaken in range(1, 7):
Guess = int(input())
if Guess < randomnumber:
print('Too low, take another guess!')
elif Guess > randomnumber:
print('Too high, take another guess!')
else:
break
if Guess == randomnumber:
print('Damnn are you a mindreader, ' + NamePlayer)
else:
print('You are wrong')
The problem is that for the last iteration I get the print for the condition that is met inside of the for loop, as well as the print outside of the loop. Of course I don't want the print 'Too high, take another guess' or something like that if it is the last guess.
How can I only print 'Damnn are you a mindreader' or 'You are wrong' for the last iteration?
You can store number of guesses in a var like N.
N = 7
for Guesstaken in range(1, N):
Guess = int(input())
if Guesstaken == N - 1:
break
if Guess < randomnumber:
print('Too low, take another guess!')
elif Guess > randomnumber:
print('Too high, take another guess!')
else:
break
if Guess == randomnumber:
print('Damnn are you a mindreader, ' + NamePlayer)
else:
print('You are wrong')
It would be better if you had a line to print rules of game, I wasn't sure how many tries you wanted to give. your program counted from 1.....6 and it was just 6 steps so i made it loop 7 times as this
for Guesstaken in range(7):
Guess = int(input())
if Guess < randomnumber and Guesstaken<6:
print('Too low, take another guess!')
elif Guess > randomnumber and Guesstaken<6:
print('Too high, take another guess!')
else:
break
import random
number_of_trials=6
c=0
print('Hello what is your name?')
NamePlayer = input()
print('Well, ' + NamePlayer + ' I am thinking of a number between 1 and 20')
randomnumber = random.randint(1, 20)
print('Take a guess.')
for Guesstaken in range(1, number_of_trials+1):
c+=1
Guess = int(input())
if Guess < randomnumber and c!=number_of_trials:
print('Too low, take another guess!')
elif Guess > randomnumber and c!=number_of_trials:
print('Too high, take another guess!')
else:
break
if Guess == randomnumber:
print('Damnn are you a mindreader, ' + NamePlayer)
else:
print('You are wrong')
here c is a counter to see if the number_of_trials are reached. It will help in not displaying 'Too high, take another guess' or something like that if it is the last guess.
The main loop in your code is to be repeated while there is going to be another guess.
You also want to only print out the "too high" or "too low" messages if there is another guess going to happen.
An alternative is to test for a correct answer or too many guesses and change the state of another_guess before those messages are printed.
For example:
import random
NamePlayer = input('Hello what is your name? ')
print(f'Well, {NamePlayer} I am thinking of a number between 1 and 20')
randomnumber = random.randint(1, 20)
print('Take a guess.')
another_guess = True
guesses = []
while another_guess:
Guess = int(input())
guesses.append(Guess)
if Guess == randomnumber:
another_guess = False
if len(guesses) == 6:
another_guess = False
if another_guess and Guess < randomnumber:
print('Too low, take another guess!')
elif another_guess and Guess > randomnumber:
print('Too high, take another guess!')
if Guess == randomnumber:
print('Damnn, are you a mind reader, ' + NamePlayer)
else:
print('You are wrong')
If you had ambition to take this game and add graphical user interface it might be beneficial to separate out the UI, game state, game logic.
For example:
"""Guess a number game"""
from dataclasses import dataclass, field
from enum import IntEnum
import random
def main():
cli = UI()
player_name = cli.ask_name()
game = Game(Scoreboard(), cli, player_name)
game.play()
class GuessState(IntEnum):
"""Possible states of guess"""
LOW = -1
CORRECT = 0
HIGH = 1
class UI:
"""Handle UI interaction to make it easy to move to different UI"""
def ask_name(self):
"""Ask the players name"""
return input("Hello, what is your name? ")
def ask_guess(self, max_choice):
"""
Ask for guess value. Check input is a valid value before returning
"""
while True:
try:
choice = int(input("Enter guess: "))
if 0 < choice < max_choice + 1:
return choice
print(f"Please enter a guess between 1 and {max_choice}")
except ValueError:
print("You entered something other than a number")
def display_welcome(self, player_name, max_choice, max_guesses):
"""Welcome message and rules"""
print(f"Welcome, {player_name}")
print(f"I am thinking of a number between 1 and {max_choice}.")
print(f"Can you guess it within {max_guesses} guesses?")
def display_turn_result(self, value, result):
"""Display the guessed value and if they are too high or low"""
if result == GuessState.LOW:
print(f"{value} is lower than the number I am thinking of!")
elif result == GuessState.HIGH:
print(f"{value} is higher than the number I am thinking of!")
def display_goodbye(self, player_name, scoreboard):
"""Game over message"""
if scoreboard.any_correct_guesses():
print(f"{player_name} are you a mindreader!")
else:
print(f"You didn't get the number, {player_name}. Please try again")
#dataclass
class Scoreboard:
"""Keep track of the guesses and if active for more guesses"""
guesses: list = field(default_factory=list)
game_active: bool = True
def add_guess(self, choice, state):
"""Add the value and state of a guess"""
self.guesses.append((choice, state))
def get_last_guess(self):
"""Return the value and state of the last guess"""
return self.guesses[-1]
def get_guess_count(self):
"""Return how many guess have been had"""
return len(self.guesses)
def any_correct_guesses(self):
"""Return True if there has been a correct guess"""
return GuessState.CORRECT in [state[1] for state in self.guesses]
def to_display(self, ui: UI):
"""Display the turn result in the UI"""
guess_value, guess_state = self.get_last_guess()
ui.display_turn_result(guess_value, guess_state)
#dataclass
class Game:
"""Game logic"""
scoreboard: Scoreboard
ui: UI
player_name: str
max_rounds: int = 6
max_number: int = 20
def play(self):
"""Play the game"""
self.ui.display_welcome(self.player_name, self.max_number, self.max_rounds)
target_number = random.randint(1, self.max_number)
print("For testing here is the target number:", target_number)
while self.scoreboard.game_active:
self.turn(target_number)
if self.scoreboard.game_active:
self.scoreboard.to_display(self.ui)
self.ui.display_goodbye(self.player_name, self.scoreboard)
def turn(self, target_number):
"""Play a turn"""
choice = self.ui.ask_guess(self.max_number)
if choice == target_number:
self.scoreboard.add_guess(choice, GuessState(0))
self.scoreboard.game_active = False
elif choice < target_number:
self.scoreboard.add_guess(choice, GuessState(-1))
elif choice > target_number:
self.scoreboard.add_guess(choice, GuessState(1))
if self.scoreboard.get_guess_count() == 6:
self.scoreboard.game_active = False
if __name__ == "__main__":
main()
Heres the copy of my code :) this game is part of my personal activity.
so after purchasing a clue (from: def game_hints) i want to return to def Game_process.
import random
SCORE = 0
ROUNDS = 1
def player_stats():
print(f"SCORE: {SCORE} | ROUNDS: {ROUNDS}")
def game_hints(USER_GUESS, Mystery_NUM):
print("Would you like purchase a hint for 5 points? [1/2]: ")
USER_HINT = int(input())
global SCORE
if USER_HINT == 1:
SCORE= SCORE - 5
if USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 0:
print("Mystery Num is even and try a smaller guess")
elif USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a smaller guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a larger guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a larger guess")
def Game_Process():
global ROUNDS
while True:
if ROUNDS <= 10:
Mystery_NUM = random.randrange(10)
print(Mystery_NUM) #remove before final product
print("Guess the num [1-10]: ")
USER_GUESS = int(input())
if USER_GUESS == Mystery_NUM:
print("\nGood Job! +5 Coins!")
global SCORE
SCORE = SCORE + 10
ROUNDS += 1
player_stats()
else:
print("Wrong! Try Again")
game_hints(USER_GUESS, Mystery_NUM)
else:
print("Game Over!")
Game()
def Game():
user_opt = input("\"Welcome to Guess Game\" \nPress [Y] to Play or [N] to Exit: ").lower()
if user_opt == "n":
print("Good bye!")
exit()
elif user_opt == "y":
Game_Process()
else:
print("Invalid Input! [1/2]")
Game()
Game()
As shown below, this is the fuction for the hints. I was able to call this function but the only problem is that the after this fuction is done, it changes the Myster_Num.
def game_hints(USER_GUESS, Mystery_NUM):
print("Would you like purchase a hint for 5 points? [1/2]: ")
USER_HINT = int(input())
global SCORE
if USER_HINT == 1:
SCORE= SCORE - 5
if USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a smaller guess")
elif USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 1:
print("Secret Num is odd and try a smaller guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a larger guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a larger guess")
First, you must remove the else statement in the game_hints function because it restarts a full GameProcess and therefore indeed recompute a mysterious number.
Then, when you exit game_hints and come back to GameProcess, you must not come back to the big loop because it will indeed recompute a mysterious number. The solution is to have an inner loop inside each round that you exit only if the player guessed the correct value using the break keyword.
def Game_Process():
SCORE = 0
ROUNDS = 1
while True:
if ROUNDS <= 10:
Mystery_NUM = random.randrange(10)
print(Mystery_NUM) # remove before final product
while True:
print("Guess the num [1-10]: ")
USER_GUESS = int(input())
if USER_GUESS == Mystery_NUM:
print("\nGood Job! +5 Coins!")
SCORE = SCORE + 10
ROUNDS += 1
player_stats()
break
else:
print("Wrong! Try Again")
game_hints(USER_GUESS, Mystery_NUM)
else:
print("Game Over!")
Game()
Hi i am unsure on how to add a second player for this number guessing game whereby after player 1 makes a guess, then player 2 makes a guess. like between every guess. I am only able to make it so that the player 2 guesses after player 1 guesses finish all of his choices(code below) if anyone is able to tell me if what i am looking for is possible or if there is any advice, it would be greatly appreciated. thanks in advance.
def main():
import random
n = random.randint(1, 99)
chances = 5
guess = int(input("Player 1 please enter an integer from 1 to 99, you have 5 chances: "))
while n != "guess":
chances -=1
if chances ==0:
print("out of chances")
break
if guess < n:
print("guess is low")
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print ("guess is high")
guess = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it")
break
import random
n1 = random.randint(1, 99)
chances1 = 0
guess1 = int(input("Player 2 please enter an integer from 1 to 99, you have 5 chances "))
while n1 != "guess":
chances1 +=1
if chances1 ==5:
print("out of chances")
break
if guess1 < n1:
print("guess is low")
guess1 = int(input("Enter an integer from 1 to 99: "))
elif guess > n1:
print ("guess is high")
guess1 = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it")
break
retry=input("would you like to play again? (please choose either 'yes' or 'no')")
if retry == "yes":
main()
else:
print("Okay. have a nice day! :D ")
main()
to achieve this I would use a while loop and a variable to detect which players turn it is. Like this:
import random
random_number = random.randint(1, 99)
player_chances = 5
current_player = 1
while player_chances > 0:
if current_player == 1:
guess = int(input("Player 1 please enter an integer from 1 to 99, {} chances left. ".format(player_chances)))
player_chances -= 1
current_player = 2
if guess < random_number:
print("->guess is too low")
elif guess > random_number:
print("->guess is too high")
else:
print("CONGRATULATIONS! You guessed it! Player 1 wins!")
break
else:
guess = int(input("Player 2 please enter an integer from 1 to 99, {} chances left. ".format(player_chances)))
player_chances -= 1
current_player = 1
if guess < random_number:
print("->guess is too low")
elif guess > random_number:
print("->guess is too high")
else:
print("CONGRATULATIONS! You guessed it! Player 1 wins!")
break
print("####")
print("Out of chances! The number was {}.".format(random_number))
print("####")
To make this possible in an efficient way I would have created a player class as such:
class Player:
def __init__(self,name):
self.name = name
self.getNumberOfTrys = 0
self.guess = 0
def getNumberOfTrys(self):
return self.getNumberOfTrys
def getPlayerName(self):
return self.name
def play(self):
try:
self.guess = int(input("Enter an integer from 1 to 99: "))
self.getNumberOfTrys+=1
return self.guess
except Exception as error:
print(error)
return None
this class is responsible to create the player with the number of tries,his guess and his name.
the logic will be going through the list of players (you can add as much as you want) and perform the game logic as follows:
import random
p1 = Player("Player 1")
p2 = Player("Player 2")
players = []
players.append(p1)
players.append(p2)
n1 = random.randint(1, 99)
NUMBER_OF_TRIES = 5
print(n1)
while players:
for player in players:
print(player.getPlayerName() + " turn, you have " + str(NUMBER_OF_TRIES - player.getNumberOfTries) + " turns left")
guess = player.play()
if guess < n1:
print("guess is low")
elif guess > n1:
print ("guess is high")
else:
print(player.getPlayerName()," you guessed it")
players.clear()
break
if player.getNumberOfTries == NUMBER_OF_TRIES:
print(player.getPlayerName(), " out of chances")
players.remove(player)
Basically, create a list of players then go through each one and apply the game logic (getting input, comparing and checking number of tries)
after a player loses, we should remove him from the list and if a player wins we can clear the list and thus exiting the game.
Here is the full code:
class Player:
def __init__(self,name):
self.name = name
self.getNumberOfTries = 0
self.guess = 0
def getNumberOfTries(self):
return self.getNumberOfTries
def getPlayerName(self):
return self.name
def play(self):
try:
self.guess = int(input("Enter an integer from 1 to 99: "))
self.getNumberOfTries+=1
return self.guess
except Exception as error:
print(error)
return None
import random
p1 = Player("Player 1")
p2 = Player("Player 2")
players = []
players.append(p1) #addding player
players.append(p2)
n1 = random.randint(1, 99)
NUMBER_OF_TRIES = 5
print(n1) #for debug
while players:
for player in players:
print(player.getPlayerName() + " turn, you have " + str(NUMBER_OF_TRIES - player.getNumberOfTries) + " turns left")
guess = player.play()
if guess < n1:
print("guess is low")
elif guess > n1:
print ("guess is high")
else:
print(player.getPlayerName()," you guessed it")
players.clear() # exit game
break #exit loop
if player.getNumberOfTries == NUMBER_OF_TRIES:
print(player.getPlayerName(), " out of chances")
players.remove(player)
Hope I got your question right, and excuse me If there is any errors or typos, I just created something fast that you can be inspired by. I highly suggest you get into OOP, it very simple and it can make your life much easier :)
All the best!
In my option 2 section of my code my loop isn't functioning properly and i can not figure out why. It keeps asking for an input again. I tried moving the input outside of the loop but that didn't work either.
import random
def display_menu():
print("Welcome to my Guess the Number Program!")
print("1. You guess the number")
print("2. You type a number for the computer to guess.")
print("3. Exit")
print()
def main():
display_menu()
option = int(input("Enter a menu option: "))
User pics a number randomly generated by the computer until user gets
the correct answer.
Outputs user guesses and number of attempts until guessed correct
if option == 1:
number = random.randint(1,10)
counter = 0
while True:
try:
guess = input("Guess a number between 1 and 10: ")
guess = int(guess)
print()
if guess < 1 or guess > 10:
raise ValueError()
counter += 1
if guess > number:
print("Too high.")
print()
elif guess < number:
print("Too low.")
print()
else:
print("You guessed it!")
print("You guessed the number in", counter, "attempts!")
break
except ValueError:
print(guess, "is not a valid guess")
print()
Option 2., User enters a number for the computer to guess.
Computer guesses a number within the range given.
Outputs computer guesses and number of guesses until computer gets
the correct number.
if option == 2:
print("Computer guess my number")
print()
while True:
try:
my_num = input("Enter a number between 1 and 10 for the computer to guess: ")
my_num = int(my_num)
counter = 0
counter += 1
print()
comp = random.randint(1,10)
if my_num < 1 or my_num > 10:
raise ValueError()
if comp > my_num:
print("Computer guessed", comp,"to High")
elif comp < my_num:
print("Computer guessed", comp,"to Low")
else:
print("Computer guessed the right number!" , comp)
print("Computer guessed the right number in", counter, "attempts!")
break
except ValueError:
print(my_num, "is not a valid entry")
print()
continue
"""
Ends game
"""
if option == 3:
print("Goodbye")
if __name__ == '__main__':
main()
You should ask for input before the loop. counter should be initialised before the loop too.
if option == 2:
print("Computer guess my number")
print()
# these three lines will be run once before the loop
my_num = input("Enter a number between 1 and 10 for the computer to guess: ")
my_num = int(my_num)
counter = 0
while True:
try:
comp = random.randint(1,10)
counter += 1
print()
if my_num < 1 or my_num > 10:
raise ValueError()
if comp > my_num:
print("Computer guessed", comp,"to High")
elif comp < my_num:
print("Computer guessed", comp,"to Low")
else:
print("Computer guessed the right number!" , comp)
print("Computer guessed the right number in", counter, "attempts!")
break
except ValueError:
print(my_num, "is not a valid entry")
print()
continue
As an aside, instead of randomly guessing, you can improve the computer's guessing by using binary search, where the number of tries has an upper bound.
I need to generate a random number from 1 to 9 and ask the user to guess it. I tell the user if its too high, low, or correct. I can't figure out how to keep the game going until they guess it correctly, and once they get it right they must type in exit to stop the game. I also need to print out how many guesses it took for them in the end. Here's my code so far:
import random
while True:
try:
userGuess = int(input("Guess a number between 1 and 9 (including 1 and 9):"))
randomNumber = random.randint(1,9)
print (randomNumber)
except:
print ("Sorry, that is an invalid answer.")
continue
else:
break
if int(userGuess) > randomNumber:
print ("Wrong, too high.")
elif int(userGuess) < randomNumber:
print ("Wrong, too low.")
elif int(userGuess) == randomNumber:
print ("You got it right!")
import random
x = random.randint(1,9)
print x
while (True):
answer=input("please give a number: ")
if ( answer != x):
print ("this is not the number: ")
else:
print ("You got it right!")
break
Here is the solution for your problem from:
Guessing Game One Solutions
import random
number = random.randint(1,9)
guess = 0
count = 0
while guess != number and guess != "exit":
guess = input("What's your guess?")
if guess == "exit":
break
guess = int(guess)
count += 1
if guess < number:
print("Too low!")
elif guess > number:
print("Too high!")
else:
print("You got it!")
print("And it only took you",count,"tries!")
from random import randint
while 1:
print("\nRandom number between 1 and 9 created.")
randomNumber = randint(1,9)
while 1:
userGuess = input("Guess a number between 1 and 9 (including 1 and 9). \nDigit 'stop' if you want to close the program: ")
if userGuess == "stop":
quit()
else:
try:
userGuess = int(userGuess)
if userGuess > randomNumber:
print ("Wrong, too high.")
elif userGuess < randomNumber:
print ("Wrong, too low.")
else:
print ("You got it right!")
break
except:
print("Invalid selection! Insert another value.")