import random
guess = '0'
while (guess) != 'exit':
answer = random.randrange(1,100)
answer = str(answer)
guess = input('Enter a number between 1 and 100 or enter exit to exit: ')
if not guess.isdigit():
if guess == "exit":
print('Game closed')
break
else:
print('Your guess was not a digit, try again')
guess = (guess)
if guess == answer:
print('Correct')
elif guess > answer :
print('Too high, try again')
elif guess < answer :
print('Too low, try again')
how would i get this to generate a new random number after you guess the correct answer
The main problem here is that you do actually generate a new number each time, even if the guess was wrong. Instead you should generate the first random number outside of the loop, and only generate a new random number if the guess was correct:
import random
guess = '0'
answer = random.randrange(1, 100)
while (guess) != 'exit':
answer = str(answer)
guess = input('Enter a number between 1 and 100 or enter exit to exit: ')
if not guess.isdigit():
if guess == "exit":
print('Game closed')
break
else:
print('Your guess was not a digit, try again')
guess = (guess)
if guess == answer:
print('Correct')
answer = random.randrange(1, 100) #make new random number if guess is correct
elif guess > answer :
print('Too high, try again')
elif guess < answer :
print('Too low, try again')
I am not sure I understand your comment correctly. You can use random.randint(a,b) to get integer, not decimal number.
( https://docs.python.org/3/library/random.html#random.randint )
import random
guess = '0'
answer = random.randint(1, 100)
while (guess) != 'exit':
answer = str(answer)
guess = input('Enter a number between 1 and 100 or enter exit to exit: ')
if not guess.isdigit():
if guess == "exit":
print('Game closed')
break
else:
print('Your guess was not a digit, try again')
guess = (guess)
if guess == answer:
print('Correct')
answer = random.randint(1, 100) #make new random number if guess is correct
elif guess > answer :
print('Too high, try again')
elif guess < answer :
print('Too low, try again')
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.