【发布时间】:2016-11-26 18:45:43
【问题描述】:
我正在编写一个 Python 脚本,其中用户必须猜测脚本选择的随机数。这是我的代码:
import random
while True:
number = random.randint(1, 3)
print("Can you guess the right number?")
antwoord = input("Enter a number between 1 and 3: ")
if antwoord == number:
print ("Dang, that's the correct number!")
print (" ")
else:
print ("Not the same!")
print ("The correct answer is:")
print (number)
while True:
answer = input('Try again? (y/n): ')
print (" ")
if answer in ('y', 'n'):
break
print("You can only answer with y or n!")
if answer == 'y':
continue
else:
print("Better next time!")
break
它有效......有点......我正在尝试它并遇到了这个: User enters 2, it says it's incorrect, but then displays the same number!
我有一种感觉,每次我调用变量“数字”时,它都会再次更改随机数。如何强制脚本保留开始时选择的随机数,而不是在脚本中不断更改它?
【问题讨论】:
-
为什么不在while外分配随机数?
-
这是 python 2 还是 3?如果是python 3,则需要对输入求值(使用
eval(input()))——"2"与2不一样 -
如果是这种情况@AhsanulHaque,你如何解释它说它是错误的数字,但后来显示相同的数字并说这是要选择的正确数字?
-
输入返回一个字符串,不能等于数字:'2' != 2. 试试 int (input))
-
这是 Python 3 @Lolgast 所以我会试试你的解决方案!