2013-07-01 4 views
8

[OK]をので、私はPythonでグレードのチェックコードを書いていると私のコードは次のとおりです。私は私のpythonを介して実行入力():「NameError:名前が 『N』に定義されていません」

unit3Done = str(input("Have you done your Unit 3 Controlled Assessment? (Type y or n): ")).lower() 
if unit3Done == "y": 
    pass 
elif unit3Done == "n": 
    print "Sorry. You must have done at least one unit to calculate what you need for an A*" 
else: 
    print "Sorry. That's not a valid answer." 

私は"n"を選択し、コンパイラと私は言ってエラーを取得:

"NameError: name 'n' is not defined"

を、私は"y"を選択したとき、私は'y'が問題点と別のNameErrorを得るが、私は何かを行うときに、コードは通常どおりに動作します。

すべてのヘルプは大歓迎です

は、ありがとうございます。

答えて

16

Python 2でraw_inputを使用して文字列を取得すると、inputeval(raw_input)に相当します。

だから、
>>> type(raw_input()) 
23 
<type 'str'> 
>>> type(input()) 
12 
<type 'int'> 

、あなたがinputnのようなものを入力すると、それはあなたがnという名前の変数を探していると考えている:

>>> input() 
n 
Traceback (most recent call last): 
    File "<ipython-input-30-5c7a218085ef>", line 1, in <module> 
    type(input()) 
    File "<string>", line 1, in <module> 
NameError: name 'n' is not defined 

正常に動作しますraw_input

>>> raw_input() 
n 
'n' 

help on raw_input

>>> print raw_input.__doc__ 
raw_input([prompt]) -> string 

Read a string from standard input. The trailing newline is stripped. 
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. 
On Unix, GNU readline is used if enabled. The prompt string, if given, 
is printed without a trailing newline before reading. 

inputのヘルプ:

>>> print input.__doc__ 
input([prompt]) -> value 

Equivalent to eval(raw_input(prompt)). 
1

あなたが代わりにPythonの2. raw_input()input() functionを使用して、やPython 3にそう

input()実行与えられた入力にeval()を、切り替えていますnと入力すると、nという変数を探して、Pythonコードとして解釈されます。 'n'(引用符付き)と入力して回避することはできますが、それはほとんど解決策ではありません。

Python 3では、raw_input()の名前がinput()に変更され、Python 2のバージョンが完全に置き換えられました。あなたの教材(本、コースノートなど)がnが動作することを期待してinput()を使用している場合は、代わりにPython 3を使用する必要があります。

関連する問題