I made five chances for the guesser to guess the random number. Every time 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 the first wrong guess will say you get 4 chances left, then another wrong, three chances left, and so on. How can I do that? Or, how to add a loop on the x.
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) '.')
CodePudding user response:
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