0

I'm having some trouble working with this code:

def sumList(nums):
    sum = 0
    for num in nums:
        sum = sum + num
    return sum
print(sumList([5, 2, 4, 7])

    def numDict():
    num = dict()
    num = 5
    num = 2
    num = 4
    num = 7

print(sumList([5, 2, 4, 7]))

def main():
    nums = sumList()
    print(num[5])
    print(num[2])
    print(num[4])
    print(num[7])

main()

What I'm trying to do is test the sumList several times with the main function. Above, the numbers add together to produce 18. I want to incorporate the main function. How can I do this?

Taylor
  • 9
  • 1

2 Answers2

0

Ok so I'm not 100% sure on what you're saying but if you're just saying like how do I test sumList with the main function then you can do something like the following:

testCases = [([1,2,3],6) , ([1,1,1],3), ([10,10,12], 32)]
def main():
    for testCase, answer in testCases:
        if sumList(testCase) != answer:
            print("False")
    print("Everything checks out")

# then to actually call your main function like something similar to cpp
if __name__ == '__main__':
    main()

That convention the if __name__ == '__main__': is commonly how you can access your main call in python.

If you're curious about the point of the main function, there's a really good Stack link here. Stack to the rescue once again. Use it heavily!

Community
  • 1
  • 1
jlarks32
  • 931
  • 8
  • 20
0

How about something like this?

def sumList(nums):
    sum = 0
    for num in nums:
        sum = sum + num
    return sum

def main():
    print("Test One:")
    print(sumList([5,2,4,7]))
    print("Test Two:")
    print(sumList([1,2,3,4]))
    print("Test Three:")
    print(sumList([0.5, 0.5, 0.5, 0.5]))

This should produce output like this

Test One:
18
Test Two:
10
Test Three:
2.0
rileymcdowell
  • 590
  • 1
  • 4
  • 15