import random
x=random.randint(1,9)
print(x)
guess=2
print('You have {} chance to guess the number'.format(guess+1))
y=int(input('Your guess: '))
while x!=y:
print('Guess left: {}'.format(guess))
y=int(input('Your guess: '))
guess-=1
if guess==0:
print('Try again. The number was {}'.format(x))
break
print('Well done')
Hello, when I make x is not equal to y deliberately 3 times or make x is not equal to y deliberately 2 times and make x is equal to y thirdly, I get 'Try again..' and 'Well done' messages at the same time. How can I fix it? Please do not use while true or special functions, thanks.
I think I understand what your problem was. All you need to do is put the print('Well Done!') into an if statement or use an else.
import random
x = random.randint(1, 9)
print(x)
guess = 2
print('You have {} chance to guess the number'.format(guess + 1))
y = int(input('Your guess: '))
while x != y:
print('Guess left: {}'.format(guess))
y = int(input('Your guess: '))
guess -= 1
if guess == 0:
print('Try again. The number was {}'.format(x))
break
if x==y:
print('Well done')
Try:
import random
x=random.randint(1,9)
print(x)
guess=3
print(f'You have {guess} chance to guess the number')
flag = 1
while (guess and flag):
y=int(input('Your guess: '))
guess-=1
print(f'Guess left: {guess}')
if guess==0 and (x!=y):
print(f'Try again. The number was {x}')
if (x==y):
print('Well done')
flag = 0
6
You have 3 chance to guess the number
Your guess: 1
Guess left: 2
Your guess: 2
Guess left: 1
Your guess: 3
Guess left: 0
Try again. The number was 6
6
You have 3 chance to guess the number
Your guess: 6
Guess left: 2
Well done
3
You have 3 chance to guess the number
Your guess: 1
Guess left: 2
Your guess: 2
Guess left: 1
Your guess: 3
Guess left: 0
Well done
Edit :
import random
x=random.randint(1,9)
print(x)
guess=2
print('You have {} chance to guess the number'.format(guess+1))
y=int(input('Your guess: '))
while x!=y:
print('Guess left: {}'.format(guess))
y=int(input('Your guess: '))
guess-=1
if guess==0 and (x!=y): # <--here
print('Try again. The number was {}'.format(x))
break
if (x==y): # <-- here
print('Well done')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.