While function in guessing game keeps looping, python - python

I'm a beginner in Python and I was wondering why this keeps looping, can someone help me out. When I print it out, it stays in a loop even tho I guessed the number right
import random
answer = random.randint(1,10)
lives = 5
out_of_lives = 0
print("Hi there! What is your name? ")
name = input()
print("Alright " + name + ", we're playing guess the number between 0 and 20.")
guess = int(input("Take a guess: "))
while (lives != 0) or (guess != answer):
if guess > answer:
print("Guess lower!")
lives = lives - 1
print("You have got", lives, "lives left")
guess = int(input('Try again, your new guess: '))
elif guess < answer:
print("Guess higher")
lives = lives - 1
print("You have got", lives , "lives left")
guess = int(input('Try again, your new guess: '))
elif guess == answer:
print("Good job, you guessed the number")
elif lives == 0:
print("Game over!, I was thinking about the number: ", answer)

Because you are not breaking the while loop.
One way to solve your problem is by inserting the conditions whether the user guessed the right number inside a main if condition of the guess is not the answer. And then break the loop when the user succeed. Like the following:
import random
answer = random.randint(1,10)
lives = 5
out_of_lives = 0
print("Hi there! What is your name? ")
name = input()
print("Alright " + name + ", we're playing guess the number between 0 and 20.")
guess = int(input("Take a guess: "))
while (lives > 1):
if guess != answer:
if guess > answer:
print("Guess lower!")
lives = lives - 1
print("You have got", lives, "lives left")
guess = int(input('Try again, your new guess: '))
elif guess < answer:
print("Guess higher")
lives = lives - 1
print("You have got", lives , "lives left")
guess = int(input('Try again, your new guess: '))
else:
print("Good job, you guessed the number")
break
print("Game over!, I was thinking about the number: ", answer)

yes this is because you also need to break the loop just where you want it to stop.

On the condition that the game is won, no adjustment to life or answers is set meaning you get stuck in the while loop.

It is because of the conditions of your while loop. You wrote that "Keep going if you have lives remain or you are wrong". So it will not stop when you still have lives even if you guessed correct, or it will not stop writing "Game over" as you did not guessed right. The right thing to do is to change the loop condition as: while (lives !=0) and (guess != answer):

Here's the correct code. Execute it. It'll solve your issue
import random
answer = random.randint(1,10)
lives = 5
out_of_lives = 0
print("Hi there! What is your name? ")
name = input()
print("Alright " + name + ", we're playing guess the number between 0 and 20.")
guess = int(input("Take a guess: "))
while(True):
if(lives==1):
print("Game over!, I was thinking about the number: ", answer)
break
else:
if guess == answer:
print("Good job, you guessed the number")
break
elif guess > answer:
print("Guess lower!")
lives = lives - 1
print("You have got", lives, "lives left")
guess = int(input('Try again, your new guess: '))
elif guess < answer:
print("Guess higher")
lives = lives - 1
print("You have got", lives , "lives left")
guess = int(input('Try again, your new guess: '))

Related

Counting Game Try/Except and calculating the users attempts

I am creating a python random counting game. I'm having some difficulties with certain parts. Can anyone here review my code? I'm having difficulty with trying to implement a try/except and a tries function that counts the user's attempts. I also have to verify that the number is a legitimate input and not a variable. So far I've gotten this far and its coming along good. I just need alittle help ironing out a few things. Thanks guys you rock.
Here is the code below:
import random
def main():
start_game()
play_again()
tries()
print("Welcome to the number guessing game")
print("I'm thinking of a number between 1 and 50")
def start_game():
secret_number = random.randint(1,50)
user_attempt_number = 1
user_guess = 0
while user_guess != secret_number and user_attempt_number < 5:
print("---Attempt", user_attempt_number)
user_input_text = input("Guess what number I am thinking of: ")
user_guess = int(user_input_text)
if user_guess > secret_number:
print("Too high")
elif user_guess < secret_number:
print("Too low")
else:
print("Right")
user_attempt_number += 1
if user_guess != secret_number:
print("You ran out of attempts. The correct number was"
+str(secret_number)+ ".")
def play_again():
while True:
play_again = input("Do you want to play again?")
if play_again == 'yes':
main()
if play_again =='no':
print("Thanks for playing")
break
def tries():
found= False
max_attempts=50
secret_number = random.randint(1, 50)
while tries <= max_attempts and not found:
user_input_text = start_game()
user_guess_count=+1
if user_input_text == secret_number:
print("It took you {} tries.".format(user_guess_count))
found = True
main()
Try this method:
def play_game():
print("Enter the upper limit for the range of numbers: ")
limit = int(input())
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
count = 1 #new line
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
count = count+

On the First guess nothing is being registered even if i get it right

This is the code:
print("Welcome to my guessing game can you get the magic number hint, it's between 1 and 100 ")
import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess = int(input("Enter your guess:"))
guess_limit = 5
guess_counter = 1
out_of_guesses = False
print("You have", str(guess_limit - guess_counter), "tries left")
while not out_of_guesses:
guess = int(input("Enter guess: "))
if guess == Magic_number:
print("Well done you got it!!")
exit(0)
elif guess < Magic_number:
print("That number is too small, try again")
elif guess > Magic_number:
print("That number is too high try again")
guess_counter += 1
print("You have", str(guess_limit - guess_counter), "tries left")
# exit clause
if guess_limit == guess_counter:
out_of_guesses = True
print("Game over, sorry")
And even if I get it correct on the first try it does something like this:
Welcome to my guessing game can you get the magic number
hint,
it's between 1 and 100
47
Enter your guess: 47
You have 4 tries left
Enter guess: 47
Well done you got it!!
As you can see even though i was correct on the first try it wasn't counted. Ps.(That is what shows up at the bottom of my screen where the code is executed.)
You do not check if guess == Magic_number after reading input on line 4.
Like this
import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess = int(input("Enter your guess:"))
if guess == Magic_number:
print ("You won")
exit(0)
You don't need all those variables, check this.
import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess_limit = 5
guess_counter = 0
while True:
guess = int(input("Enter guess: "))
if guess == Magic_number:
print("Well done you got it!!")
exit(0)
elif guess < Magic_number:
print("That number is too small, try again")
elif guess > Magic_number:
print("That number is too high try again")
guess_counter += 1
print(f"You have {guess_limit - guess_counter} tries left")
if guess_counter == guess_limit:
print("Game over, sorry")
exit(0)

How do i creat levels, replay and keep track of wins and losses

import random
print("Welcome to the game, Guess a Number! \n")
print("There will be 3 rounds to the game.")
print("During the first round, you will be asked to choose a number between 0-10.")
print("You will have 3 chances to guess the correct number. If you can't, the game will start over.")
print("Good Luck! \n")
def ReadyToPlay():
NumberGuesses = 0 #sets numerb of guesses
MaxGuesses = 3 #sets maximum times you can guess
number = random.randint(0,10)
print("Hi stranger, I am thinking of a number between 0 and 10.")
while NumberGuesses < MaxGuesses:
guess = int(input("Take a guess: ")) #prompt to take guess
NumberGuesses = NumberGuesses + 1 #keeps number count
if guess < number:
print("Sorry, your guess is to low.")
elif guess > number:
print("Sorry, your guess is to high.")
if guess == number: #stops current loop and continues the rest of my statment
break
if guess == number:
NumberGuesses = str(NumberGuesses)
print('\n')
print("Congrats Stranger! You have guessed the correct number.")
print("Moving on to round two. \n")
NumberGuesses = 0 #sets numerb of guesses
MaxGuesses = 3 #sets maximum times you can guess
number = random.randint(0,50)
print("Now, I am thinking of a number between 0 and 50.")
while NumberGuesses < MaxGuesses:
guess = int(input("Take a guess: ")) #prompt to take guess
NumberGuesses = NumberGuesses + 1 #keeps number count
if guess < number:
print("Sorry, your guess is to low.")
elif guess > number:
print("Sorry, your guess is to high.")
if guess == number:
break
if guess == number:
NumberGuesses = str(NumberGuesses)
print('\n')
print("You're on fire!")
print("Now you have arrived to the last round.")
print("You will have to choose 2 numbers, in order to complete the game. \n")
NumberGuesses = 0 #sets numerb of guesses
MaxGuesses = 6 #sets maximum times you can guess
number = random.randint(0,100)
print("The first number I am thinking of is between 0 and 100")
while NumberGuesses < MaxGuesses:
guess = int(input("Take a guess: "))
NumeberGuesses = NumberGuesses + 1
if guess < number:
print("Sorry, your guess is to low.")
elif guess > number:
print("Sorry, your guess is to high.")
if guess == number:
break
if guess == number:
print('\n')
print("Your guessA is correct.")
print("Now, guess the second number.")
NumberGuesses = 0 #sets numerb of guesses
MaxGuesses = 6 #sets maximum times you can guess
number = random.randint(0,100)
print("The second number I am thinking of is between 0 and 100")
while NumberGuesses < MaxGuesses:
guess = int(input("Take a guess: ")) #prompt to take guess
NumberGuesses = NumberGuesses + 1 #keeps number count
if guess < number:
print("Sorry, your guess is to low.")
elif guess > number:
print("Sorry, your guess is to high.")
if guess == number:
break
if guess == number:
print('\n')
print("Your guessB is also correct.")
print("Congratulations on finishing the game!!!")
if guess != number:
number = str(number)
print("\n")
print("The number I was thinking of was: " + number)
replay = input("Do you want to play again (y/n)?: ")
if replay == "y":
ReadyToPlay()
ReadyToPlay
i need help creating 3 levels, being able to replay the game from each level and keeping track of my wins and losses. i am a beginner so it needs to be very easy to code. So far I have created three parts to the game which all work. But when I need to reply, the game starts from the beginning and not from where u have reached up until
Use a container that will hold the state of the game; update the state during game play. Add a parameter to ReadyToPlay() that is optional. The parameter accepts a container that holds the current game state. If passed when the function is called, use it to start the game from there. Pass the state container for a replay.
You might want to consider having your function return the guess and current state then move the if guess != number: code outside of the function.

Python "Guess The Number" game giving unexpected results

i recently started learning python and my friend from work who is a programmer gave me a simple challenge to write a "guess the number" style game.
So i came up with something as follows:
import random
print("Hello, welcome to GUESS THE NUMBER game")
run = True
def again():
global run
playagain = str(input("Would you like to play again? Type y/n for yes or no: "))
if playagain == "y":
run = True
elif playagain == "n":
run = False
while run:
guess = int(input("Guess the number between 1 and 10: "))
num1 = random.randint(1, 10)
if guess == num1:
print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1))
again()
elif guess > num1:
print("Too high, go lower!")
elif guess < num1:
print("Too small, go higher!")
My problem is that after the user has chosen to play again, the numbers sometimes dont register and go out of whack. For example you input 5 and it says too low, but if you input 6 it says too high! I don't seem to be dealing in float numbers so they should be whole, any ideas where i went wrong?
Thanks in advance and very excited to learn more on the subject
Your problem is that you're regenerating the random number every time.
num1 = random.randint(1, 10)
Instead, maybe put the guess and check logic inside it's own loop.
while True:
guess = int(input("Guess the number between 1 and 10: "))
if guess == num1:
print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1))
break # leave the while True loop
elif guess > num1:
print("Too high, go lower!")
elif guess < num1:
print("Too small, go higher!")
again()
You are calculating the random number on each iteration of the loop. Therefore every time you guess the random number changes.
import random
print("Hello, welcome to GUESS THE NUMBER game")
run = True
def again():
global run
playagain = str(input("Would you like to play again? Type y/n for yes or no: "))
if playagain == "y":
run = True
elif playagain == "n":
run = False
num1 = random.randint(1, 10)
while run:
guess = int(input("Guess the number between 1 and 10: "))
if guess == num1:
print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1))
again()
elif guess > num1:
print("Too high, go lower!")
elif guess < num1:
print("Too small, go higher!")

How can i create a game that alternated between players?

I am looking to make a guess my number game that alternates between the user guessing and the Al but I'm not sure how to do it. I already have a guess my number game code but I don't know what to add to make it change from user to computer.
#Guess my number
import random
print ("Welcome to the guess my number game")
print ("***********************************")
print ("I will choose a random number between 1-100")
print ("and you must guess what it is.")
print ()
number = random.randint(1,100)
guesses = 0
guess = 0
while guess != number:
guess = int(input("Take a guess: "))
guesses=guesses+1
if guess > number:
print("Lower...")
continue
elif guess < number:
print ("Higher...")
else:
print ("Well done you have guessed my number and it took you", guesses,"guesses!")
input ("\n\nPress enter to exit.")
guesses = [[],[]]
for player in itertools.cycle([0,1]):
if player == 0:
guess = int(input("Take a guess: "))
else:
guess = computer_guess()
guesses[player].append(guess)
if guess == number:
break
if guess > number:
print("Lower...")
continue
elif guess < number:
print ("Higher...")
print "Player %d wins"%player
print "It Took %d guesses"%len(guesses[player])
maybe what you are looking for

Categories