2017-06-09 8 views
0

私は引数を持つ関数を使用するためのpythonの引数に学ぶ道を上げていない以下の通りである:私は、このような場合、関数内でNameErrorを上げ、それが必要必要があることを期待してい関数の引数:NameError

def res(arg1, arg2): 
    try: 
     print(a+b) # it prints result.. shouldn't code be break here? 
     return a + b # this also returns a result. 
    except NameError: 
     return "failed." 
a = 2 
b = 3 
print(res(a, b)) 

ブロック以外で処理することができますが、何らかのエラーが発生するのではなく、arg1+arg2a +bの両方で動作しますか?これを理解して克服するためには、どんな種類の助けも必要です。

+6

'A'と 'B'は、あなたのモジュール内のグローバルであり、すべてのグローバルは、あなたの機能を利用できます。 –

+0

これは、解釈される言語は、関数定義の前に定義されたグローバル変数であってはなりませんか? – Gahan

+4

いいえ、関数を呼び出す前にグローバルを定義する必要があります。この記事は役に立ちましたか:SOベテランのNed Batchelderによって書かれた[Pythonの名前と値についての事実と神話](http://nedbatchelder.com/text/names.html) –

答えて

0

あなたは例外を発生する場合、これを試してみてください:

def res(arg1, arg2): 
    try: 
     print(a+b) # tries to find variable a and b in global scope if it found it will use it's value 
     return a + b 
    except NameError: 
     return "failed." 

def function2(): 
    a = 2 # this is within scope of function2() so it is not accessible by res() 
    b = 3 
    print(res(a, b)) 


function2() # on calling this you will get NameError from res because a and b are not in global scope