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()
としてそれを参照してください。リストを読んでいるのであれば、オブジェクトを 'my_input_list = []'として宣言してください。読込み関数の中で、グローバルに宣言されたオブジェクトに値を割り当てることができます。または、あなたの関数は、user1とuser2に割り当てたinput()と同じように、呼び出し元に値を返すことができます。 –
'sumF(n)'の定義で 'n'は使用されていますか? –
@AnmolSinghJaggiああ、私の間違い。ループをn回繰り返す必要があります。これはまだLになりますが、いいキャッチです。 – beJeb