功能中的用户输入,我可以将其设为“全局”吗?

时间:2016-10-11 04:50:00

标签: function python-3.x user-input

我能说出这个问题的最佳方式= '我可以使用'程序员'定义的函数来获取用户输入,然后在另一个用户定义的函数中使用该输入吗?'

背景资料:

    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

- 我想知道是否有办法创建一个能够获取用户输入的函数,然后在任何其他用户定义的函数中使用该函数中收集的信息。

我想创建一个收集用户输入的函数,而不是使用语句抓取main函数,如果可能的话。这样我就可以使用该函数从用户那里获取一个列表,而不是使用我的全局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()

1 个答案:

答案 0 :(得分: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