Guess the number game Python - 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")

Related

My guessing game repeatedly prints in console if you guess incorrectly

I am new to python and built this for practice. How come if you guess incorrectly the print function runs repeatedly. Additionally, if you make a correct guess the corresponding print function doesn't run.
import random
print("Welcome to the Guessing Game")
rand = random.randint(1, 9)
count = 0
running = True
guess = int(input("Pick a number from 1 - 9"))
while guess != rand:
count += 1
if guess > rand:
print("Too High")
running = False
elif guess == rand:
print("Winner Winner Chicken Dinner")
print("You won in", count, "tries!")
running = False
elif guess < rand:
print("Too Low")
If the number is incorrect we need to ask the player to guess again. You can use break to avoid having an infinite loop, here after 5 guesses.
The conversion of the input to integer will throw an error if the entry is not a valid number. It would be good to implement error handling.
import random
print("Welcome to the Guessing Game")
rand = random.randint(1, 9)
count = 0
running = True
guess = int(input("Pick a number from 1 - 9"))
while guess != rand:
count += 1
if guess > rand:
print("Too High")
running = False
elif guess == rand:
print("Winner Winner Chicken Dinner")
print("You won in", count, "tries!")
running = False
break
elif guess < rand:
print("Too Low")
if i >= 5:
break
guess = int(input("Try again\nPick a number from 1 - 9"))
in the first while loop, when player guesses the correct number we need to break.
Also for counting the number of rounds that player played we need a new while loop based on count.
When we use count in our code we should ask player every time that he enters the wrong answer to guess again so i used input in the while
import random
print("Welcome to the Guessing Game:")
rand = random.randint(1, 9)
count = 0
while count!=5:
guess = int(input("Pick a number from 1 - 9:"))
count += 1
if guess > rand:
print("Too High")
elif guess == rand:
print("Winner Winner Chicken Dinner")
print("You won in", count, "tries!")
break
elif guess < rand:
print("Too Low")
print('you lost')

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

Stuck between errors

i am a absolute beginner and practicing with this project "guessing the number" i have wrote the following code and wanna know what kind of error i have made.
import random
guess_count = 3
number = random.randint(1, 9)
while guess_count > 0:
guess = int(input("Guess: "))
guess_count -= 1
if guess == number:
print("Congrats You Won!")
guess_count = 0
else:
print("You Lose, Better luck next time.")
print('')
print(f"The correct number was {number}.")
Output comes out to be this,
Guess: 2
You Lose, Better luck next time.
The correct number was 6.
Guess: 6
Congrats You Won!
Expected output for failure :
Guess: 3
Guess: 4
Guess: 5
You Lose, Better luck next time.
Use break to end the loop when the guess is correct.
Put the else: block on the while loop. It will be executed if the loop ends without a break, which happens when they run out of guesses.
import random
guess_count = 3
number = random.randint(1, 9)
while guess_count > 0:
guess = int(input("Guess: "))
guess_count -= 1
if guess == number:
print("Congrats You Won!")
break
else:
print("You Lose, Better luck next time.")
print('')
print(f"The correct number was {number}.")
import random
guess_count = 3
number = random.randint(1, 9)
while guess_count > 0:
guess = int(input("Guess: "))
guess_count -= 1
if guess == number:
print("Congrats You Won!")
guess_count = 0
else:
print("You Lose, Better luck next time.")
print('')
print("The correct number was ", number , " .")
Another way to format the problem, using a for loop instead:
import random
guess_count = 3
number = random.randint(1, 9)
for x in range(0, guess_count):
guess = int(input("Guess: "))
if guess == number:
print("Congrats You Won!")
break # exit loop
else:
print("You Lose, Better luck next time.")
print('')
if x == guess_count - 1:
print(f"The correct number was {number}.")

Modular Guess the game loop

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.

Player already guessed the number

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!"

Categories

Resources