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')
在猜到正确的答案之后,我将如何生成一个新的随机数
答案 0 :(得分:1)
这里的主要问题是,即使猜测错误,您每次都会实际生成一个新数字。相反,您应该在循环外生成第一个随机数,并且只有在猜测正确时才生成新的随机数:
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')
答案 1 :(得分:1)
我不确定我是否理解你的评论。您可以使用random.randint(a,b)来获取整数,而不是十进制数。
(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')