为什么我的代码没有显示输出?

时间:2018-10-05 04:54:59

标签: python python-3.x

我编写了一个读取整数的程序,直到用户输入0为止,该程序将存储整数,然后返回整数之和。但是它没有显示输出,出了什么问题?

def readList():
    n=int(input())
    while n!=0:
        n=int(input())
        return n

def calSum(n):
    n=myList


myList = readList()
sum = calSum(myList)
print(sum)

2 个答案:

答案 0 :(得分:0)

这应该是您要寻找的

readList函数会附加到列表中,然后返回该列表,并像以前一样只返回第一个数字。

calcSum函数使用Python内置的sum函数来计算列表中所有整数的总和。

def readList():
    myList = []
    n=int(input())
    while n!=0:
        n=int(input())
        myList.append(n)
    return myList

def calSum(n):
    return sum(n)

myList = readList()
sum = calSum(myList)
print(sum)

答案 1 :(得分:0)

calSum正在将myList分配给n,但是它位于calSum之内,并且此def之外的任何内容都无法读取它,因为它是局部变量。

与readList中的n有关。它是本地的。因此readList中的“ n”和calSum中的“ n”在这些函数之外不存在,无法在其他任何地方使用。

您能够使用readList中的“ n”,只是因为您使用了return,该返回值将此值返回到程序的其余部分。而且,您必须以calSum的方式进行制作,才能使其正常工作。

Google在python中提供了全局变量和局部变量,以获取有关主题的更多信息:)

def readList():
    n=int(input("Input from readList"))
    while n!=0:
        n=int(input("Looped input from readList"))
        return n

def calSum(n):
    n=myList
    return n #Added return as student suggested 

myList = readList()
sum = calSum(myList)
print(sum)