我正在写一个简单的基于文本的游戏来增强我对Python的了解。在游戏的一个阶段,用户需要猜测集合[1,5]中的一个数字,才能实现他或她的愿望。他们只有三次尝试。我有两个问题:
1)假设genie_number
被随机选择为3。用户每次猜测后,这个值是否会改变?我不希望程序在每次猜测后随机选择另一个整数。它应该保持不变,这样用户就有3/5的机会猜对它。在
2)我想惩罚用户不猜测整数,我已经在except ValueError
部分中做过。但是如果用户在一行中进行了三次非整数猜测并用尽了所有的尝试,我希望循环重新指向else: dead("The genie turns you into a frog.")
。现在它给我的错误信息如下。我怎么解决这个问题?在
'Before I grant your first wish,' says the genie, 'you must answer this
'I am thinking of a discrete integer contained in the set [1, 5]. You ha
(That isn't much of a riddle, but you'd better do what he says.)
What is your guess? > what
That is not an option. Tries remaining: 2
What is your guess? > what
That is not an option. Tries remaining: 1
What is your guess? > what
That is not an option. Tries remaining: 0
Traceback (most recent call last):
File "ex36.py", line 76, in <module>
start()
File "ex36.py", line 68, in start
lamp()
File "ex36.py", line 48, in lamp
rub()
File "ex36.py", line 38, in rub
wish_1_riddle()
File "ex36.py", line 30, in wish_1_riddle
if guess == genie_number:
UnboundLocalError: local variable 'guess' referenced before assignment
以下是我目前为止的代码:
^{pr2}$
回答您的第一个问题,否。如果您继续调用
randint(1, 5)
,是的,它将更改,但一旦您分配它,该值将固定:如您所见,一旦我们将随机数赋给
x
,x
始终保持不变。但是,如果我们继续调用randint()
,它就会改变。在回答您的第二个问题时,您不应该在
^{pr2}$int(raw_input())
后面的tries
中添加1,如果该值是一个整数,它也将添加1来尝试。相反,请尝试将您的代码合并到如下内容中:你得到了错误,因为你三次都答错了。因此,没有为
guess
赋值。在while
循环之后,您将尝试查看guess
是否是某个东西,但它不是:但是,如果输入正确,
guess
会变成:编辑
与@LosFrijoles关于范围问题的说法相反,错误实际上是由于缺少正确的输入:
如您所见,变量
x
既存在于for
循环中,也存在于常规shell中,因此它不属于范围问题:如您所见,它是一个错误错误。。。:)由于错误,
x
永远不会被赋值,除非我们实际给出一个整数输入,因为代码永远不会到达print x
,因为它因错误而中断:当我们给一个整数输入时,
x
就有效了。在相关问题 更多 >
编程相关推荐