0

Python の知識を深めるために、単純なテキストベースのゲームを書いています。ゲームの 1 つの段階で、ユーザーは自分の願いを叶えるためにセット [1, 5] の数字を推測する必要があります。試行回数は 3 回のみです。2 つの質問があります。

1) がランダムに選択されて 3 であると仮定しgenie_numberます。この値は、ユーザーが推測するたびに変化しますか? プログラムが各推測の後に別の整数をランダムに選択することは望ましくありません。ユーザーが正しく推測できる確率が 3/5 になるように、同じままにしておく必要があります。

2) 整数だけを推測しないことでユーザーにペナルティを課したいのですが、except ValueErrorセクションの下でそれを行いました。しかし、ユーザーが 3 回連続して非整数の推測を行い、すべての試行を使い果たした場合は、ループを にリダイレクトする必要があります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

これまでの私のコードは次のとおりです。

def wish_1_riddle():
    print "\n'Before I grant your first wish,' says the genie, 'you must answer this riddle!'"
    print "'I am thinking of a discrete integer contained in the set [1, 5]. You have three tries.'"
    print "(That isn't much of a riddle, but you'd better do what he says.)"

    genie_number = randint(1, 5)
    tries = 0
    tries_remaining = 3

    while tries < 3:
        try:
            guess = int(raw_input("What is your guess? > "))
            tries += 1
            tries_remaining -= 1

            if guess == genie_number:
                print "Correct!"
                wish_1_grant()
            else:
                print "Incorrect! Tries remaining: %d" % tries_remaining
                continue
        except ValueError:
            tries += 1
            tries_remaining -= 1
            print "That is not an option. The genie penalizes you a try. Be careful!"
            print "Tries remaining: %d" % tries_remaining

    if guess == genie_number:
        wish_1_grant()
    else:
        dead("The genie turns you into a frog.")
4

1 に答える 1

1

最初の質問に答えます。いいえ。を呼び出し続けるとrandint(1, 5)、はい、変更されますが、一度割り当てると、値は固定されます。

>>> import random
>>> x = random.randint(1, 10)
>>> x
8
>>> x
8
>>> x
8
>>> random.randint(1, 10)
4
>>> random.randint(1, 10)
8
>>> random.randint(1, 10)
10

ご覧のとおり、乱数を に割り当てるとx、 はx常に同じままです。ただし、 を呼び出し続けると、randint()変化します。

2 番目の質問に答えると、triesの直後に1 を追加しないでくださいint(raw_input())。値が整数の場合は、試行にも 1 が追加されます。代わりに、コードを以下のようなものに組み込んでみてください。

>>> tries = 0
>>> while tries < 3:
...     try:
...             x = raw_input('Hello: ')
...             x = int(x)
...     except ValueError:
...             tries+=1
... 
Hello: hello
Hello: 1
Hello: 4
Hello: bye
Hello: cool
>>> 

3 回すべて間違って回答したため、エラーが発生しています。したがって、 には何も割り当てられませんguesswhileループの後、guess何かであるかどうかを確認しようとします。

>>> tries = 0
>>> while tries < 3:
...     try:
...             guess = int(raw_input('Enter input: '))
...             print guess
...     except ValueError:
...             tries+=1
... 
Enter input: hello
Enter input: bye
Enter input: good morning
>>> guess
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'guess' is not defined

ただし、正しい入力をすると、次のようにguessなります。

>>> tries = 0
>>> while tries < 3:
...     try:
...             guess = int(raw_input('Enter input: '))
...             print guess
...     except ValueError:
...             tries+=1
... 
Enter input: 4
4
Enter input: hello
Enter input: 9
9
Enter input: bye
Enter input: 6
6
Enter input: greetings
>>> guess
6
>>> 

編集

スコープに問題があるという@LosFrijolesとは対照的に、エラーは実際には正しい入力の欠如によるものでした:

>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> for k in range(1):
...     x = 1
...     print x
... 
1
>>> x
1
>>> 

ご覧のとおり、変数はループと通常のシェルのx両方に存在するため、スコープの問題ではありません。for

>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> for k in range(1, 3):
...     try:
...             x = int(raw_input('Hello: '))
...             print x 
...     except ValueError:
...             pass
... 
Hello: hello
Hello: bye
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> 

ご覧のとおり、これエラー エラーです... :) エラーのxため、コードが に到達しないため、実際に整数を入力しない限り、 が割り当てられることはありませんprint x

>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> for k in range(1, 3):
...     try:
...             x = int(raw_input('Hello: '))
...             print x
...     except ValueError:
...             pass
... 
Hello: hello
Hello: 8
8
>>> x
8
>>> 

整数を入力すると有効xになります。

于 2014-04-26T04:49:34.033 に答える