Home > OS >  Guess the Number Program Exits in 2nd Inputs
Guess the Number Program Exits in 2nd Inputs

Time:04-08

really a beginner here. I was following "Automate the Boring Stuff with Python" book and the author makes you write a short "guess the number" program. The book gives a solution but I wanted to pursue my own one. I do not know why this program exits on 2nd input. Can you tell me whats wrong with it, I was not able to figure it out even though its a pretty basic code.

import random

secretNumber = random.randint(1,20)
print("I got a number in my mind from 1 to 20")
guess = int(input("Take a guess."))
numberOfTries = 0

if guess < secretNumber:
    print("Your guess is lower than my number")
    numberOfTries = numberOfTries   1
    int(input("Take a guess."))

elif guess > secretNumber:
    print("Your guess is higher than my number")
    numberOfTries =  1
    guess = int(input("Take a guess."))

if guess == secretNumber:
    print("You guessed right!")
    print("You found my number in"   str(numberOfTries))

CodePudding user response:

It is because you need to put the guessing part in a loop. So far you only have a single instance of checking your guessed value against the correct value. Thus:

secretNumber = random.randint(1,20)
guess = int(input("Take a guess."))

while guess != secretNumber:
    # logic from above
    #    .  .  .  . 
    guess = int(input("Take a guess."))

CodePudding user response:

Here's the code properly formatted:

import random

secretNumber = random.randint(1,20)
print("I got a number in my mind from 1 to 20")
guess = -1
numberOfTries = 0
while guess != secretNumber:
    # inserted space after input
    guess = int(input("Take a guess: "))
    if guess < secretNumber:
        print("Your guess is lower than my number")
        # changed to  =
        numberOfTries  = 1
        # removed input()

    elif guess > secretNumber:
        print("Your guess is higher than my number")
        # changed the =  to  =
        numberOfTries  = 1

    if guess == secretNumber:
        print(f"You guessed right!\nYou found my number in {numberOfTries} tries!")

I suggest not copy-pasting but reading the comments and understanding the changes.

Furthermore, here is a bit more advanced code (just the while loop part):

while guess != secretNumber:
    guess = int(input("Take a guess: "))
    if guess != secretNumber:
        if guess > secretNumber:
            higher_lower = "higher"
        else:
            higher_lower = "lower"
        numberOfTries  = 1
        print(f"Your guess is {higher_lower} than my number")

Good luck with python!

  • Related