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

Countdown the chances in loop for guessing game

i made 5 chances for the guesser to guess the random number. Everytime the guesser did wrong, i want to print

"Nice try, guess again (try bigger), you get {x} chance left."

the x is a countdown, so first wrong guess, will say, you get 4 chances left,
then another wrong got 3 chances left and so on. how to do that? how to add loop on the x.

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

so this is my unsuccessful code:

import random

secret_num = random.randint(1,20)


print('Guess the number from 1-20 (you get 5 chances)')
for guess_chance in range (1,6):
    guess = int(input("Input guess number: "))

    if guess < secret_num:
        x = 5
        x -= 1
        print(f'Nice try, guess again (try bigger), you get {x} chance left.')
    elif guess > secret_num:
        x = 5
        x -= 1
        print(f'Nice try, guess again (try smaller), you get {x} chance left.')

    else:
        break

if guess == secret_num:
    print('Congratz, you guess correctly in' + str(guess_chance) + 'times.')
else:
    print('Nope, the correct number is ' + str(secret_num) + '.')

>Solution :

You need to do x = 5 before for guess_chance in range...) and remove it from inside the loop.

print('Guess the number from 1-20 (you get 5 chances)')

x = 5

for guess_chance in range(1, 6):
    guess = int(input("Input guess number: "))

    if guess < secret_num:
        x -= 1
        print(f'Nice try, guess again (try bigger), you get {x} chance left.')

    elif guess > secret_num:
        x -= 1
        print(f'Nice try, guess again (try smaller), you get {x} chance left.')

    else:
        break

Otherwise, each guess you are resetting it to 5 tries and then subtracting one… which presumably always shows 4 tries…

There are many other ways to solve this… I just picked the one that changed your code the least

and when combined with your range this is a bit redundant

x = 6 - guess_chance would work

as would just iterating the range in reverse

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