Python Beginner - Number Guessing Game print issue - python

I'm having an issue simply with print("Out of Guesses!\nYou Lose, Try Again!"). Whenever, the player runs out of guesses it prints out all print print statements twice here's the output:
Too Low!
Out of Guesses!
You Lose, Try Again!
Too Low!
When it should just print:
Out of Guesses!
You Lose, Try Again!
Code:
import random
number = random.randint(0,20)
player = ""
guess_count = 0
guess_limit = 5
out_guesses = False
while player != number and not out_guesses:
if guess_count < guess_limit:
player = int(input("Input Your Guess: "))
guess_count += 1
else:
out_guesses = True
print("Out of Guesses!\nYou Lose, Try Again!")
if player == number:
print("You Win!")
if player < number:
print("Too Low!")
if player > number:
print("Too High!")

In out_guesses scenario :
if player == number:
print("You Win!")
if player < number:
print("Too Low!")
if player > number:
print("Too High!")
This code block is getting executed twice instead of one. You've to stop it by logic. Here is a sample :
import random
number = random.randint(0, 20)
player = ""
guess_count = 0
guess_limit = 5
while player != number:
if guess_count < guess_limit:
player = int(input("Input Your Guess: "))
guess_count += 1
if player == number:
print("You Win!")
if player < number:
print("Too Low!")
if player > number:
print("Too High!")
else:
print("Out of Guesses!\nYou Lose, Try Again!")
break

Related

How can I make my program repeat execute many times?

I have a program that works fine, however I need to make it so that it can execute again when the if statement regarding playing again is satisfied.
import random
n=random.randint(0,10)
print(n)
number= int(input('Guess what the number is'))
count=0
while number !=n:
count=count+1
number= int(input('Guess what the number is'))
if number< n:
print("that is too low")
elif number>n:
print("That is too high")
else:
print("You got it right in"+ " "+str(count+1)+" "+ "tries")
print(count+1)
yesorno= str(input('Do you want to play again? y or n'))
if yesorno=="y":
number= int(input('Guess what the number is'))
elif yesorno=="n":
print("Goodbye")
If you don't want an ugly big while loop, use functions. It makes your code cleaner.
import random
def play():
input("Guess a number between 1 and 10: ")
random_number = random.randint(1, 10)
guess = None
attempts = 0
while guess != random_number:
guess = int(input("Pick a number from 1 to 10: "))
attempts += 1
if guess < random_number:
print("TOO LOW!")
elif guess > random_number:
print("TOO HIGH!")
print("YOU GOT IT! The number was {}, you got it in {} attempts.".format(random_number, attempts))
def main():
play()
while input("Play again? (y/n) ").lower() != "n":
play()
main() # Call the main function
import random
n=random.randint(0,10)
count = 0
while True:
count=count+1
number= int(input('Guess what the number is'))
if number< n:
print("that is too low")
elif number>n:
print("That is too high")
else:
print("You got it right in"+ " "+str(count)+" "+ "tries")
print(count)
yesorno= str(input('Do you want to play again? y or n'))
if yesorno=="y":
n=random.randint(0,10)
count = 0
elif yesorno=="n":
print("Goodbye")
break
import random
n=random.randint(0,10)
print(n)
count=0
while True:
count=count+1
number= int(input('Guess what the number is '))
if number< n:
print("that is too low")
elif number>n:
print("That is too high")
elif number == n:
print("You got it right in"+ " "+str(count+1)+" "+ "tries")
print(count+1)
yesorno= str(input('Do you want to play again? y or n'))
if yesorno=="n":
print("Goodbye")
break
Use a while loop with a condition that will always be true, like while True:.
To stop this infinite loop, use the break statement within the while loop.
If user inputs "y", the loop will continue because it has not been told the break.

Trying to build a random number guessing game but print statements are tripping me up

I'm completely new to python as of 2 weeks ago. I'm trying to build a random number guessing game. If the guess is wrong, I want the system to return if the number is higher or lower but I keep getting either number is lower or higher repeated over and over. If the guess it right, it says I lost.
import random
random_number = random.randint(0,10)
guess = int
guess_count = 0
guess_limit = 5
out_of_guesses = False
while guess != random_number and not(out_of_guesses):
if guess_count < guess_limit:
guess = (int(input("Enter guess: ")))
guess_count += 1
if guess < random_number:
print("Number is higher")
if guess > random_number:
print("Number is lower")
else:
out_of_guesses = True
if out_of_guesses:
print("Out of guesses, YOU SUCK!")
else:
print("You win")
if guess_count < guess_limit:
guess = (int(input("Enter guess: ")))
guess_count += 1
if guess < random_number:
print("Number is higher")
if guess > random_number:
print("Number is lower")
else:
out_of_guesses = True
In this sample your else statement refers back to the last "if", that means that if your guess is not higher than random_number, it will always set out_of_guesses to true.
I don't want to spoil the answer since learning python is a fun experience. I would read up a bit more on control flow in python. This could be a good starting point.
Just indent the guess ... random number statements:
import random
random_number = random.randint(0,10)
guess = int
guess_count = 0
guess_limit = 5
out_of_guesses = False
while guess != random_number and not(out_of_guesses):
if guess_count < guess_limit:
guess = int(input("Enter guess: "))
guess_count += 1
if guess < random_number:
print("Number is higher")
if guess > random_number:
print("Number is lower")
else:
out_of_guesses = True
if out_of_guesses:
print("Out of guesses, YOU SUCK!")
else:
print("You win")
So, at this moment, you don't have the right identation. The else statement as it is right now will connect with if guess > random_number:
This means that if the guess is lower then random_number than out_of_guesses will become True, because the logic is the following:
if guess > random_number: # This returns False
else # This will happen if the guess is not grater then random_number
out_of_guesses = True
So your code should look like this:
import random
random_number = random.randint(0,10)
guess = int
guess_count = 0
guess_limit = 5
out_of_guesses = False
while guess != random_number and not(out_of_guesses):
if guess_count < guess_limit:
guess = (int(input("Enter guess: ")))
guess_count += 1
if guess < random_number:
print("Number is higher")
if guess > random_number:
print("Number is lower")
else:
out_of_guesses = True
if out_of_guesses:
print("Out of guesses, YOU SUCK!")
else:
print("You win")

im unable to break the loop when the timer comes to an end

from time import *
import threading
def countdown():
global my_timer
my_timer = 5
for x in range(5):
my_timer = my_timer - 1
sleep(1)
print("Time is up! Sorry!")
countdown_thread = threading.Thread(target = countdown)
countdown_thread.start()
while my_timer > 0:
again="yes"
while again=="yes":
difficulty = input("Difficulty? easy, medium or hard? ")
if difficulty == "easy":
player1=int(input("Player 1 please enter a number from 1 to 99: "))
guess= eval(input("Player 2 please enter your guess between 1 and 99 "))
count=1
lives=int(7)
if guess==player1:
print("You rock! You guessed the number in" , count , "tries!")
while guess !=player1:
count+=1
if lives == 1:
print(" No more lives, GAME OVER")
break
elif guess > player1 + 10:
print("Too high!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
elif guess < player1 - 10:
print("Too low!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
elif guess > player1:
print("Getting warm but still high!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
elif guess < player1:
print("Getting warm but still Low!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
if guess==player1 or lives !=0:
print("You rock! You guessed the number in" , count , "tries!")
if guess == player1 or lives==1:
again=str(input("Do you want to play again, type yes or no "))
if again == "no":
print("Bye")
break
elif again == "yes":
continue
elif difficulty == "medium":
player1=int(input("Player 1 please enter a number from 1 to 199: "))
guess= eval(input("Player 2 please enter your guess between 1 and 199 "))
count=1
lives=int(10)
if guess==player1:
print("You rock! You guessed the number in" , count , "tries!")
while guess !=player1:
count+=1
if lives == 1:
print(" No more lives, GAME OVER")
break
elif guess > player1 + 20:
print("Too high!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
elif guess < player1 - 20:
print("Too low!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
elif guess > player1:
print("Getting warm but still high!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
elif guess < player1:
print("Getting warm but still Low!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
if guess==player1 or lives !=0:
print("You rock! You guessed the number in" , count , "tries!")
if guess == player1 or lives==1:
again=str(input("Do you want to play again, type yes or no "))
if again == "no":
print("Bye")
break
elif again == "yes":
continue
elif difficulty == "hard":
player1=int(input("Player 1 please enter a number from 1 to 299: "))
guess= eval(input("Player 2 please enter your guess between 1 and 299 "))
count=1
lives=int(14)
if guess==player1:
print("You rock! You guessed the number in" , count , "tries!")
while guess !=player1:
count+=1
if lives == 1:
print(" No more lives, GAME OVER")
break
elif guess > player1 + 30:
print("Too high!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
elif guess < player1 - 30:
print("Too low!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
elif guess > player1:
print("Getting warm but still high!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
elif guess < player1:
print("Getting warm but still Low!")
lives-=1
print("lives remaining: ", lives)
guess = eval(input("Try again "))
if guess==player1 or lives !=0:
print("You rock! You guessed the number in" , count , "tries!")
if guess == player1 or lives==1:
again=str(input("Do you want to play again, type yes or no "))
if again == "no":
print("Bye")
break
elif again == "yes":
continue
I'm unable to make break the loop when my timer comes to an end.
I tried to include if my_timer==0 break but it doesn't really work for some reason, and the program just continues on.
I'm really confused by this; can you help me to understand?
Unfortunately I can't comment as I don't have a reputation greater than 50 due to being relatively new here.
I don't have a solution as to why the timer is not stopping the program when it runs out but I think I know the reason.
I think it is due to the fact that upon first entering the while my_timer>0:, my_timer is greater than 0 which means it goes onto the next while loop which then runs your main body. This means the my_timer variable isn't continuously checked until the second while loop is re-checked. So basically you can't break from the first loop until you break out of the second loop after the timer has finished.
When I ran your code I also found a couple issues:
1)Even if I answer "no" to playing again, if the timer is still running then I am put into the game to select a difficulty again
2)If the timer ends and I answer "yes" to playing again I can continue playing as long as I like
3)After selecting a difficulty, I can still specify a number outside the range you want.
Although the following code does not solve the problem of the timer not stopping the game.
It will stop after the timer runs out even if I choose "yes" to playing again and it will break and stop the timer if i choose no to playing again. I also think the code is a little neater as it has less repitition.
import threading
import time
def countdown():
global my_timer
global stop_thread
while True:
time.sleep(1)
my_timer -= 1
if my_timer == 0:
print("Time is up! Sorry!")
break
elif stop_thread:
break
def process_guess(lives, guess, player1, boundary):
player2_lives = lives
guess_count = 1
while guess != player1:
guess_count += 1
if guess > player1 + boundary:
print("Too high!")
elif guess < player1 - boundary:
print("Too low!")
elif guess > player1:
print("Getting warm but still high!")
elif guess < player1:
print("Getting warm but still Low!")
player2_lives -= 1
if player2_lives <= 0:
print(" No more lives, GAME OVER")
return None
else:
print("lives remaining: ", player2_lives)
guess = eval(input("Try again "))
else:
if lives != 0:
print("You rock! You guessed the number in", guess_count, "tries!")
if lives >= 1:
again = str(input("Do you want to play again?, type yes or no "))
if again == "no":
print("Bye")
return None
elif again == "yes":
return True
def guessing_game():
countdown_thread = threading.Thread(target=countdown)
countdown_thread.start()
while my_timer > 0:
global stop_thread
guess_result = None
while True:
difficulty = input("Difficulty? easy, medium or hard? ")
while difficulty not in ["easy", "medium", "hard"]:
difficulty = input("Difficulty? easy, medium or hard? ")
if difficulty == "easy":
boundary = 10
player1 = int(input("Player 1 please enter a number from 1 to 99: "))
guess = eval(input("Player 2 please enter your guess between 1 and 99 "))
lives = 7
guess_result = process_guess(lives=lives, guess=guess, player1=player1, boundary=boundary)
elif difficulty == "medium":
boundary = 20
player1 = int(input("Player 1 please enter a number from 1 to 199: "))
guess = eval(input("Player 2 please enter your guess between 1 and 199 "))
lives = 10
guess_result = process_guess(lives=lives, guess=guess, player1=player1, boundary=boundary)
elif difficulty == "hard":
boundary = 30
player1 = int(input("Player 1 please enter a number from 1 to 299: "))
guess = eval(input("Player 2 please enter your guess between 1 and 299 "))
lives = 14
guess_result = process_guess(lives=lives, guess=guess, player1=player1, boundary=boundary)
break
if guess_result:
continue
else:
stop_thread = True
break
if __name__ == "__main__":
my_timer = 5
stop_thread = False
guessing_game()
If you wanted to you could even reduce the first two while loops to one by using:
def guessing_game():
countdown_thread = threading.Thread(target=countdown)
countdown_thread.start()
global stop_thread
while True and my_timer > 0:
guess_result = None
difficulty = input("Difficulty? easy, medium or hard? ")
while difficulty not in ["easy", "medium", "hard"]:
difficulty = input("Difficulty? easy, medium or hard? ")
if difficulty == "easy":
boundary = 10
player1 = int(input("Player 1 please enter a number from 1 to 99: "))
guess = eval(input("Player 2 please enter your guess between 1 and 99 "))
lives = 7
guess_result = process_guess(lives=lives, guess=guess, player1=player1, boundary=boundary)
elif difficulty == "medium":
boundary = 20
player1 = int(input("Player 1 please enter a number from 1 to 199: "))
guess = eval(input("Player 2 please enter your guess between 1 and 199 "))
lives = 10
guess_result = process_guess(lives=lives, guess=guess, player1=player1, boundary=boundary)
elif difficulty == "hard":
boundary = 30
player1 = int(input("Player 1 please enter a number from 1 to 299: "))
guess = eval(input("Player 2 please enter your guess between 1 and 299 "))
lives = 14
guess_result = process_guess(lives=lives, guess=guess, player1=player1, boundary=boundary)
if guess_result:
continue
else:
break
stop_thread = True
To fix the problem of people being able to enter numbers outside the ones you specify you can use a while loop similar to how I have for specifying the difficulty. Alternatively you can use assertions but that's more for raising errors.
Hope that helps, sorry I couldn't make the timer stop the program.

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

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}.")

Categories

Resources