Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

User integer guessing game: How do I add another check to if loop

new to Python and Stack. As the title says I’m coding a guess number game. The instructions are as follows:

Write a program that prompts the user for an integer that the player (maybe the user, maybe someone else) will try to guess. If the player’s guess is higher than the target integer, the program should display too high. If the user’s guess is lower than the target integer, the program should display too low. The program should use a loop that repeats until the user correctly guesses the integer. Then the program should print how many guesses it took.

When you run your program it should match the following format:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Enter the integer for the player to guess.
-12
Enter your guess.
100
Too high - try again:
50
Too high - try again:
-2000
Too low - try again:
-12
You guessed it in 4 tries.

If the user guesses the integer in 1 try, then your program should print "You guessed it in 1 try."

My code:

print('Enter the integer for the  player to guess.')
secret_int = int(input())

guess_taken = int(0)

print('Enter your guess.')

while guess_taken < secret_int:
    guess = int(input())

    guess_taken = guess_taken + 1

    if guess < secret_int:
        print('Too low - try again:')

    if guess > secret_int:
        print('Too high - try again:')

    if guess == secret_int:
        print('You guesses it in', guess_taken, 'tries.')
        break

My code works fine but I can’t seem to figure out how to add this provision "If the user guesses the integer in 1 try, then your program should print "You guessed it in 1 try." I’ve tried everything I can think of and nothings works, all out of ideas. Thank you and sorry for any formatting errors!

>Solution :

Just change your final print line to this:

print('You guesses it in', guess_taken, ('tries.' if guess_taken > 1 else "try."))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading