Player already guessed the number - python

I'm having difficulties telling the player that the player already guessed the number.
This is my code:
import random
number = random.randint (1, 100)
guess = int(input("\nCan you guess the number?\n\n"))
guessing = 1
def get_guess(already_guessed):
guess = input()
if guess in already_guessed:
print("You already guessed that number.")
else:
return guess
while guess != number:
if guess < number:
print("Your guess is too low.")
if guess > number:
print("Your guess is too high.")
if guess == number:
break
guess = get_guess(input("Try again.\n\n"))

You never updating your already_guessed variable you could add it to your get_guess function. And also you have too many input. Try that:
import random
number = random.randint (1, 100)
guess = int(input("\nCan you guess the number?\n\n"))
already_guessed = []
def get_guess(already_guessed):
if guess in already_guessed:
print("You already guessed that number.")
else:
already_guessed.append(guess)
return already_guessed
while guess != number:
if guess < number:
print("Your guess is too low.")
if guess > number:
print("Your guess is too high.")
if guess == number:
break
guess = int(input("Try again.\n\n"))
already_guessed = get_guess(already_guessed)

You don't maintain a list of guesses seen, but you try to use it.
You pass input in place of the already_guessed list at the end.
Your input statement flow is not consistent with game play.
Your termination doesn't tell the player that s/he won, and you use a redundant break statement.
import random
number = random.randint (1, 100)
guess = int(input("\nCan you guess the number?\n\n"))
guessing = 1
seen = []
def get_guess(already_guessed):
guess = int(raw_input("Your guess?"))
if guess in already_guessed:
print("You already guessed that number.")
else:
return guess
while guess != number:
seen.append(guess)
if guess < number:
print("Your guess is too low.")
elif guess > number:
print("Your guess is too high.")
guess = get_guess(seen)
print "You win!"

Related

While loop breaking after first nested question

I'm trying to get my program to work. It's a number guessing game where a user inputs their name, and then the program generates a number 1-100. From there they have to guess the number and the program tells them if their number is higher or lower.
If the user succeeded in guessing the number they have the option to play again. I've programmed this but it breaks after the first number input. Any idea where I went wrong?
import random
#importing the randoms
#getting the name from the user
message=("What is your name?")
name=input(message)
#challange message from user
print("Hello! ", name,"I have a number from 1 to 100! It is your job to try and guess it!")
gamestat=False
while gamestat==False:
#generate number
number = random.randint(1,101)
#start the game
guess = int(input("start to guess: "))
#GAME LOGIC
num_guesses = 1
while guess != number:
if guess > number:
print("lower")
guess = int(input("try again: "))
num_guesses +=1
if guess < number:
print ("higher")
guess = int(input("start to guess: "))
num_guesses +=1
print("congrats it took you", num_guesses, "tries")
message=("Would you like to play again? (yes or no)")
result=input(message)
if result == "no":
gamestat= True
Program indentation is not correct. Try using
import random
#importing the randoms
#getting the name from the user
message=("What is your name?")
name=input(message)
#challange message from user
print("Hello! ", name,"I have a number from 1 to 100! It is your job to try and guess it!")
gamestat=False
while gamestat==False:
#generate number
number = random.randint(1,101)
#start the game
guess = int(input("start to guess: "))
#GAME LOGIC
num_guesses = 1
while guess != number:
if guess > number:
print("lower")
guess = int(input("try again: "))
num_guesses +=1
if guess < number:
print ("higher")
guess = int(input("start to guess: "))
num_guesses +=1
print("congrats it took you", num_guesses, "tries")
message=("Would you like to play again? (yes or no)")
result=input(message)
if result == "no":
gamestat= True
Happy Coding!
As a comment already mentioned, it's an indentation issue.
if guess < number:
print ("higher")
guess = int(input("start to guess: "))
num_guesses +=1
This block is intended one tab to far, it resides under if guess > number and can thus never be reached.
Change your while loop to
while not gamestat:
# you can just invert it, same result as comparing to False
number = random.randint(1, 101)
# add some try except logic here and in the other inputs if the user doesn't input an int
guess = int(input("start to guess: "))
num_guesses = 1
while guess != number:
if guess > number:
print("lower")
guess = int(input("try again: "))
num_guesses += 1
if guess < number:
print("higher")
guess = int(input("start to guess: "))
num_guesses += 1
Here is your code after minor modifications.
One was indentation issue as pointed righty. Apart from this in guess< number block the message was start to guess which is not consistent with above which may cause ambiguity. Also you can remove the common part outside the if block.
import random
# importing the randoms
# getting the name from the user
message = ("What is your name?")
name = input(message)
# challange message from user
print("Hello! ", name, "I have a number from 1 to 100! It is your job to try and guess it!")
gamestat = False
while not gamestat:
# generate number
number = random.randint(1, 101)
# start the game
guess = int(input("start to guess: "))
# GAME LOGIC
num_guesses = 1
while guess != number:
if guess > number:
print("lower")
if guess < number:
print("higher")
guess = int(input("try again: "))
num_guesses += 1
if number == guess:
print("congrats it took you", num_guesses, "tries")
message = ("Would you like to play again? (yes or no)")
result = input(message)
if result == "no":
gamestat = True

I tried adding a simple play again feature to my guessing game

I tried to add a do you want to play again feature to my guessing game and it stopped working :( pls help. Im very new to python so i bet i have done many oblivious mistakes :S
import random
n = random.randint(1, 100)
play_game = input("Do you want to play ? Y/N :")
play_game = play_game.upper()
print("play_game")
while play_game == 'Y':
guess = int(input("Guess a number between 1 och 100: "))
while n != "gissning":
if guess < n:
print("You guessed to low")
guess = int(input("Guess a number between 1 och 100: "))
elif guess > n:
print ("You guessed to high")
guess = int(input("Guess a number between 1 och 100: "))
else:
print("Gratz you guessed it")
break
while play_game == 'Y':
# your game
play_game = input("Do you want to play again? Y/N :").upper()
Actually there are a few little problems in your code, but with a bit of logic you can figure it out.
First, you don't want three separated while loops, since when you quit one you'll never reach it again unless you restart your code. You actually want nested loops. The outer one will verify if the user wants to play again, while the inner one will keep asking guesses until it matches the random number.
And second, you want to compare n, the random number, to guess, the user's input. In your code you're comparing n != "gissning", which will never be true since n is a number and "gissning", a string.
With that in mind you can change your code a little bit and have something like:
import random
print("play_game")
play_game = input("Do you want to play ? Y/N :").upper()
highscore = 0
while play_game == 'Y':
n = random.randint(1, 100)
guess = int(input("Guess a number between 1 och 100: "))
score = 1
while n != guess:
if guess < n:
print("You guessed to low")
elif guess > n:
print("You guessed to high")
guess = int(input("Guess a number between 1 och 100: "))
score += 1
else:
print("Gratz you guessed it")
highscore = score if score < highscore or highscore == 0 else highscore
print('Your score this turn was', score)
print('Your highscore is', highscore)
play_game = input("Do you want to play again? Y/N :").upper()
Hope this helps you out. Good luck in your Python journey! Let us know if you have any further questions.
The next input prompt should be inside the outer-while loop. You also need to print the "Gratz you guessed it" along with the prompt and outside the inner-while loop when it's already n == guess.
import random
play_game = input("Do you want to play ? Y/N :")
play_game = play_game.upper()
while play_game == 'Y':
print("play_game")
n = random.randint(1, 100)
guess = int(input("Guess a number between 1 och 100: "))
while n != guess:
if guess < n:
print("You guessed to low")
guess = int(input("Guess a number between 1 och 100: "))
elif guess > n:
print ("You guessed to high")
guess = int(input("Guess a number between 1 och 100: "))
print("Gratz you guessed it")
play_game = input("Do you want to play ? Y/N :")
play_game = play_game.upper()

Guess the number game Python

So, im new to python and i have this challenge: I have to make the Guess the Number game, between me and computer. So this is where im at so far.
import random
the_number = random.randint(1, 4)
guess = 0
print(the_number)
while guess != the_number:
guess = int(input("Please enter a number: "))
if guess > the_number:
print("Player guess lower...\n")
elif guess < the_number:
print("Player guess higher...\n")
else:
print("Game Over! The number was", the_number,"The Player wins!")
break
guess = random.randint(1, 100)
if guess > the_number:
print("Computer guess lower...\n")
elif guess < the_number:
print("Computer guess higher...\n")
else:
print("Game Over! The number was", the_number,"The Computer wins!")
break
print("Thank you for playing")
I wanna know how to make this to not stop until one of us is right?
# Import random library
import random
# Assign random value between 1-100
secret_number = random.randint(1, 100)
# get the user guess
guess = int(input("Guess the secret number between 1-100: "))
# Loop untill guess not equal to secret number
while guess != secret_number:
if guess < secret_number:
print("Sorry, your guess is too low.")
else:
print("Sorry, your guess is too high.")
# guess the number again
guess = int(input("Guess the secret number between 1-100: "))
# This statement will execute after coming out of while loop
print("You guessed the number!")
You can do something like this to make the computer smarter.
import random
the_number = random.randint(1, 4)
guess = 0
print(the_number)
minPossible = 0
maxPossible = 100
while guess != the_number:
guess = int(input("Please enter a number: "))
if guess > the_number:
print("Player, guess lower...\n")
if guess < maxPossible:
maxPossible = guess - 1
elif guess < the_number:
print("Player, guess higher...\n")
if guess > minPossible:
minPossible = guess + 1
else:
print("Game Over! The number was", the_number, "The Player wins!")
break
guess = random.randint(minPossible, maxPossible)
if guess > the_number:
print("Computer, guess lower...\n")
maxPossible = guess - 1
elif guess < the_number:
print("Computer, guess higher...\n")
minPossible = guess + 1
else:
print("Game Over! The number was", the_number,"The Computer wins!")
print("Thank you for playing")
Your problem is the break statement at the end of the while loop. The code is iterating through the loop one time, then the break is ending the loop.
To get the desired output, you just need to tweak the code a bit, the break in the if statement for the computer is out of the loop of else, so it will stop the execution no matter what.
To counter this condition, you can move the break inside the else block. By doing this, the program will only break if either CPU or you correctly guess the right number.
One more thing i wanted to point out is you are printing the selecting number in the program, if it is a guessing game, isn't it supposed to be in the back-end of the code. By entering the printed number, you can win the game in the first iteration.
And just to point out, your program is selecting the number from (1, 4) but the computer is set to guess the number from (1, 100).
Kindly tick the answer if it is correct.
The modified code is -
import random
the_number = random.randint(1, 4)
guess = 0
while guess != the_number:
guess = int(input("Please enter a number: "))
if guess > the_number:
print("Player guess lower...\n")
elif guess < the_number:
print("Player guess higher...\n")
else:
print("Game Over! The number was", the_number,"The Player wins!")
break
guess = random.randint(1, 4)
if guess > the_number:
print("Computer guess lower...\n")
elif guess < the_number:
print("Computer guess higher...\n")
else:
print("Game Over! The number was", the_number,"The Computer wins!")
break
print("Thank you for playing")

In my guess the number it tells me my Number variable isnt defined

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

Python random number generator

The code works fine, but I can't figure out how to completely restart the program. I put continue in the code and I know that is not correct, because I want it to restart completely after you guess the correct number and it displays 'Congratulations! You guessed my number in _ guesses.
import random
guesses = 0
number = random.randint(1, 100)
print('I am thinking of a number between 1 and 100.')
while guesses < 100:
guess = int(input('Guess? '))
guesses = guesses + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
continue
if guess == number:
guesses = str(guesses)
print('Congratulations! You guessed my number in ' + guesses + ' guesses!')
If you want to keep on guessing and start the game automatically, you need to do a recursive call:
import random
def guess_func():
number = random.randint(1, 100)
guesses = 0
while True:
guess = int(raw_input("Enter your guess: "))
if guess < number:
print('Your guess is too low.')
guesses += 1
if guess > number:
print('Your guess is too high.')
guesses += 1
if guess == number:
print "Congratulations! You guessed my number in [{}] guesses".format(guesses)
print "Let's keep on guessing!"
return guess_func()
guess_func()
so like this:
while True:
guesses = 0
while guesses < 100:
if guesses == 100:
break
...
if guess == number:
print ...
yorn = input "do you want to try again?")
if yorn == 'n':
break
so just wrap your code in an outer while, obviously i skipped a lot of your code

Categories

Resources