2016-10-11 4 views
0

私はこの質問をフレーズできる最善の方法= 'プログラマ定義の関数を使用してユーザー入力を取得し、その入力を別のユーザー定義関数内で使用できますか?'関数内のユーザー入力は、「グローバル」にすることはできますか?

背景情報:

1. Python 3.x please 
    2. I understand function statements are usually local, not global, but I am unsure if that is 100% the case 
    3. I usually grab user input during the main function, and then call a function to act on that input, so even though it is 'local' the called function is using that data 

- 私は、他の内、その関数内で収集した情報をユーザの入力をつかむし、次に使用することができます関数を作成する方法があるかどうかを知りたいですユーザー定義関数。

可能であれば、ステートメントを使用してメイン関数を取得するのではなく、ユーザー入力を収集する関数を作成したいと考えています。だから私は、代わりにここでL

の私のグローバルステートメントを使用しての機能を使用して、ユーザからのリストを、つかむことができるような方法は、私の現在の例である:

#Creating global list to be called on by the functions 
L = [1,2,3,4,5,6,7,8,9] #total is 45 


# Sum a list using 'For Loop' 
def sumF(n): 
    total = 0 
    for i in L: 
     total += i 
    return total 

# Sum a list using 'While Loop' 
def sumW(x): 
    count = 0 
    total = 0 
    while count < len(L): 
     total += L[count] 
     count += 1 
    return total 

# Sum a list using Recursion 
def sumR(g,h): 
    if h == 0: 
     return 0 
    else: 
     return g[h-1] + sumR(g,h-1) 

def combine(a,b): 
    L3 = [] 
    a = a.split() 
    b = b.split() 
    # Currently only works when lists have same length? 
    for i in range(len(a)): 
     L3.append(a[i]) 
     L3.append(b[i]) 
    print('The combination of the lists = %s' %L3) 


#main funtion to call all the other functions 
def main(): 
    print('The number %d was calculated using the for-loop function.' %(sumF(L))) 
    print('The number %d was calculated using the while-loop function.' %(sumW(L))) 
    print('The number %d was calculated using a recursive function.' %(sumR(L,len(L)))) 
    user = input('Enter a list of elements, with each being seperated by one space: ') 
    user2 = input('Enter a second list of elements, with each being seperated by one space: ') 
    combine(user,user2) 

#selection control statement to initiate the main function before all others 
main() 
+0

としてそれを参照してください。リストを読んでいるのであれば、オブジェクトを 'my_input_list = []'として宣言してください。読込み関数の中で、グローバルに宣言されたオブジェクトに値を割り当てることができます。または、あなたの関数は、user1とuser2に割り当てたinput()と同じように、呼び出し元に値を返すことができます。 –

+0

'sumF(n)'の定義で 'n'は使用されていますか? –

+0

@AnmolSinghJaggiああ、私の間違い。ループをn回繰り返す必要があります。これはまだLになりますが、いいキャッチです。 – beJeb

答えて

0

機能

内の変数 globalを宣言します
>>> def func(max_input): 
     global list1 
     list1=[] 
     for i in range(max_input): 
      list1.append(input('enter item and press enter')) 
     return list1  #Optional 

出力

>>> 
>>> func(5) 
enter list item and enter1 
enter list item and enter2 
enter list item and enter3 
enter list item and enter4 
enter list item and enter5 

>>> list1 
['1', '2', '3', '4', '5'] 
>>> 
あなたが別の関数内で関数から変数を参照のうえする場合は

その後、こんにちは、あなたが入力を読み取るためにグローバルオブジェクトを設定することができ nonlocal

>>>def func2(): 
     var1=[] #local to func2 
     def func3(): 
      nonlocal var1 #refers to var1 in func2 function 
関連する問題