Why is my code not working? I am following UDEMY's 100 days of code and it is essentially the same as the instructor but I wanted to have keyword named arguments. First of all it's not printing the correct turn_left after each turn and it's not stopping the game.
from random import randint
EASY_LEVEL_TURNS = 10
HARD_LEVEL_TURNS = 5
def check_answer(user_guess, correct_answer, tracking_turns):
"""
Checks answer with guess.
"""
if user_guess > correct_answer:
print("Too high")
return tracking_turns - 1
elif user_guess < correct_answer:
print("Too low")
return tracking_turns - 1
elif user_guess == correct_answer:
print(f"Right the answer is {correct_answer}")
def set_difficulty(game_level):
"""
Sets game difficulty
"""
if game_level == "easy":
return EASY_LEVEL_TURNS
elif game_level == "hard":
return HARD_LEVEL_TURNS
def game():
"""
Setting up the game
"""
guess = 0
answer = randint(1, 100)
print("Welcome to the number guessing game!")
print("I am thinking of a number between 1 to 100")
level = input("How difficult would you like the game to be? Easy or Hard ").lower()
turn_left = set_difficulty(game_level=level)
while guess != answer:
print(f"You have {turn_left} attempts to guess the answer.")
guess = int(input("What is your guess? "))
answer_checked = check_answer(user_guess=guess, correct_answer=answer,
tracking_turns=turn_left)
if turn_left == 0:
print("You have ran out of terms")
return
game()
You can modify your game function like this, mainly by updating the turn_left value and setting the end-of-function condition
def game():
"""
Setting up the game
"""
guess = 0
answer = randint(1, 100)
print("Welcome to the number guessing game!")
print("I am thinking of a number between 1 to 100")
level = input("How difficult would you like the game to be? Easy or Hard ").lower()
turn_left = set_difficulty(game_level=level)
while guess != answer:
print(f"You have {turn_left} attempts to guess the answer.")
guess = int(input("What is your guess? "))
turn_left = check_answer(user_guess=guess, correct_answer=answer,
tracking_turns=turn_left)
if turn_left == 0:
print("You have ran out of terms")
return
elif not turn_left:
return
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()
SUPER new to programming so bear with me, please. I am taking my first ever programming class and for a project, I was given a list of requirements I need to fulfill, creating a simple number guessing game has been the only thing I've not had a lot of trouble with so I decided to give it a go.
(i need 1 class, function, dictionary or list, for loop, and while loop) What I, well at least have tried to make is a guessing game that gives a limit of 2 guesss for a # between 0 and 10, any help would be greatly appreciated. :)
import random
class Player:
player = ""
playerscore = 0
def gamestart(self):
self.number = random.randint(0,7)
self.guesss = 0
self.list = []
self.limit = 3
print()
print("Guess what number I'm thinking off")
print()
print("Might even give you a hit if you do well enough")
print()
while self.limit > 0:
self.player_guess = int(input("Well? What are you waiting for? Start guessing:"))
print()
if self.player_guess > 7 or self.player_guess < 0:
print("Wow that was a terrible guess, think harder or we might be here all week long")
print("also,", self.player_guess , "is not in the range...")
print("Becareful though, you only have", self.limit, "guesss left")
elif self.player_guess > self.number:
self.guesss += 1
self.limit-= 1
print("WRONG")
print(self.player, "You only have", self.limit, "guesss left")
self.list.append(self.player_guess)
elif self.player_guess < self.number:
self.guesss += 1
self.limit -= 1
print("oh oh... wrong again!")
print()
print(self.player, "You only have", self.limit, "guesss left.")
self.list.append(self.player_guess)
else:
self.limit -= 1
self.playerscore += 1
self.list.append(self.player_guess)
print()
print("wow, you actually got it right")
print()
print(self.player_guess, "IS THE CORRECT ANSWER!")
print()
print("you only had",self.limit,"left too...")
print("Lets see all the numbers you guessed")
print()
for i in self.list:
print(i)
self.list.clear()
I found the question confusing, however the following code should work as a number guessing game, hope I answered your question.
import random
game = "true"
guesses = 2
while game == "true":
comp_number = int(random.uniform(1,8))
print("I have randomly selected a number between 1 and 7 (inclusive), you have 2 attempts to guess the number.")
while guesses > 0:
if guesses == 2:
turn = "first"
else:
turn = "final"
guess = int(input("Please submit your "+turn+" guess:"))
while guess < 1 or guess > 7:
print("Invalid guess, remember my number is between 1 and 7 (inclusive)")
guess = int(input("Resubmit a valid guess:"))
if guess == comp_number:
print("Congratulations you guessed my number, you win!")
if str(input("Would you like to play again? Please enter Y or N.")) == "Y":
guesses = 2
game = "true"
else:
game = "false"
break
else:
print("Incorrect number, try again.")
guesses -= 1
print("You where unable to guess my number, I win!")
if str(input("Would you like to play again? Please enter Y or N.")) == "Y":
guesses = 2
game = "true"
else:
game = "false"
break
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!
With my guess the number program, when I try to run it tells me the the variable "number" is not defined. I would appreciate it and be thankful if someone came to my aid in this!
import random
guesses = 0
def higher(guesses):
print("Lower")
guesses = guesses + 1
def lower(guesses):
print("Higher")
guesses = guesses + 1
def correct(guesses):
print("You got it correct!")
print("It was {0}".format(number))
guesses = guesses + 1
print ("It took you {0} guesses".format(guesses))
def _main_(guesses):
print("Welcome to guess the number")
number = random.randint(1, 100)
while True:
guess = int(input("Guess a number: "))
if guess > number:
higher(guesses)
elif guess < number:
lower(guesses)
elif guess == number:
correct(guesses)
while True:
answer = input("Would you like to play again? Y or N: ")
if answer == "Y":
break
elif answer == "N":
exit()
else:
exit()
_main_(guesses)
Your problem is that number is not defined in the function correct. number is defined in _main_. When you call correct in _main_, it does not get access to number.
This is the fixed version of your code:
import random
guesses = 0
number = random.randint(1, 100)
def higher(guesses):
print("Lower")
guesses = guesses + 1
def lower(guesses):
print("Higher")
guesses = guesses + 1
def correct(guesses):
print("You got it correct!")
print("It was {0}".format(number))
guesses = guesses + 1
print ("It took you {0} guesses".format(guesses))
def _main_(guesses):
print("Welcome to guess the number")
while True:
guess = int(input("Guess a number: "))
if guess > number:
higher(guesses)
elif guess < number:
lower(guesses)
elif guess == number:
correct(guesses)
while True:
answer = input("Would you like to play again? Y or N: ")
if answer == "Y":
break
elif answer == "N":
exit()
else:
exit()
_main_(guesses)
What I changed is I moved the definition of number to the top, which allowed it to be accessed by all functions in the module.
Also, your code style is not very good. Firstly, do not name your main function _main_, instead use main. Additionally, you don't need a function to print out 'lower' and 'higher.' Here is some improved code:
import random
def main():
number = random.randint(1, 100)
guesses = 0
while True:
guessed_num = int(input('Guess the number: '))
guesses += 1
if guessed_num > number:
print('Guess lower!')
elif guessed_num < number:
print('Guess higher!')
else:
print('Correct!')
print('The number was {}'.format(number))
print('It took you {} guesses.'.format(guesses))
break
main()
Your specific problem is that the variable number is not defined in function correct(). It can be solved by passing number as an argument to correct().
But even if you correct that problem, your program has another major issue. You have defined guesses globally, but you still pass guesses as an argument to lower(), higher() and correct(). This creates a duplicate variable guesses inside the scope of these functions and each time you call either of these functions, it is this duplicate variable that is being incremented and not the one you created globally. So no matter how many guesses the user takes, it will always print
You took 1 guesses.
Solution:
Define the functions lower() and higher() with no arguments. Tell those functions thatSo ultimately this code should work:
import random
guesses = 0
def higher():
global guesses
print("Lower")
guesses = guesses + 1
def lower():
global guesses
print("Higher")
guesses = guesses + 1
def correct(number):
global guesses
print("You got it correct!")
print("It was {0}".format(number))
guesses = guesses + 1
print ("It took you {0} guesses".format(guesses))
def _main_():
print("Welcome to guess the number")
guesses = 0
number = random.randint(1, 100)
while True:
guess = int(input("Guess a number: "))
if guess > number:
higher()
elif guess < number:
lower()
elif guess == number:
correct(number)
while True:
answer = input("Would you like to play again? Y or N: ")
if answer == "Y":
_main_()
elif answer == "N":
exit()
else:
exit()
_main_()
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I wanted to create a guessing game to get more comfortable programming, The user has up to 100 guesses(yes more than enough). If the number is too high or too low it have them type in a new input, if its correct it will print correct.Now I simply want to have it setup to where I ask them would they like to play again. I think I have an idea of to set it up, by separating them into two functions?
I am aware that is not currently a function but should put this as a fucntion and then put my question as an if statement in its own function?
import random
randNum = random.randrange(1,21)
numguesses = 0
while numguesses < 100:
numguesses = numguesses + 1
userguess = int(input("What is your guess [1 through 20]?"))
if userguess < 1:
print("Too Low")
print("Please enter a valid guess [1-20]!")
elif userguess > 20:
print("Too High")
elif userguess == randNum:
print("Correct")
print("you used",numguesses,"number of guesses")
Here's a simple way to do as you asked.I made a function and when you get the thing correct it asks if you want to play again and if you enter "yes" then it resets the vars and runs the loop again. If you enter anything but "yes" then it breaks the loop which ends the program.
import random
def main():
randNum = random.randrange(1,21)
numguesses = 0
while numguesses < 100:
numguesses = numguesses + 1
userguess = int(input("What is your guess [1 through 20]?"))
if userguess < 1:
print("Too Low")
print("Please enter a valid guess [1-20]!")
elif userguess > 20:
print("Too High")
elif userguess == randNum:
print("Correct")
print("you used",numguesses,"number of guesses")
x = input("would you like to play again?")
if x == "yes":
main()
else:
break
main()
Here is another way to do
import random
randNum = random.randrange(1,21)
numguesses = 0
maxGuess = 100
print("Guessing number Game - max attempts: " + str(maxGuess))
while True:
numguesses +=1
userguess = int(input("What is your guess [1 through 20]? "))
if userguess < randNum:
print("Too Low")
elif userguess > randNum:
print("Too High")
else:
print("Correct. You used ",numguesses," number of guesses")
break
if maxGuess==numguesses:
print("Maximum attempts reached. Correct answer: " + str(randNum))
break
import random
randNum = random.randrange(1, 21)
guess = 0
response = ['too low', 'invalid guess', 'too hight', 'correct']
def respond(guess):
do_break = None # is assigned True if user gets correct answer
if guess < randNum:
print(response[0])
elif guess > randNum:
print(response[2])
elif guess < 1:
print(response[1])
elif guess == randNum:
print(response[3])
do_continue = input('do you want to continue? yes or no')
if do_continue == 'yes':
# if player wants to play again start loop again
Guess()
else:
# if player does'nt want to play end game
do_break = True # tells program to break the loop
# same as ''if do_break == True''
if do_break:
#returns instructions for loop to end
return True
def Guess(guess=guess):
# while loops only have accesse to variables of direct parent
# which is why i directly assigned the guess variable to the Fucntion
while guess < 100:
guess -= 1
user_guess = int(input('What is your guess [1 through 20]?'))
# here the respond function is called then checked for a return
# statement (note i don't know wheter this is good practice or not)
if respond(user_guess):
# gets instructions from respond function to end loop then ends it
break
Guess()
Yet another way with two while loops
answer = 'yes'
while answer == 'yes':
while numguesses < 100:
numguesses = numguesses + 1
userguess = int(input("What is your guess [1 through 20]?"))
if userguess < 1:
print("Too Low")
print("Please enter a valid guess [1-20]!")
elif userguess > 20:
print("Too High")
elif userguess == randNum:
print("Correct")
print("you used",numguesses,"number of guesses")
break #Stop while loop if user guest, hop to the first loop with answer var
answer = raw_input("Would you like to continue? yes or no\n>")