Search code examples
pythonlistindexingadditionindices

Python List Iteration/Addition


I think my problem is very simple but I cannot figure it out. I am trying to add the even indices of the list into the variable . The error persists on the last line of the function . I do not understand why you cannot iterate through the list with the for loop to add the indices?

    def main():
        # Get Input Number
        n = int(input("Enter a number:"))

        # Call <oddEvenSame()>
        oddEvenSame(n)   


    def oddEvenSame(n):
        # Split all digits of <n> into their own index within <digits>
        digits = [int(i) for i in str(n)]

        # Add even indices of <digits> into <even>
        even = 0
        for j in range(0, len(digits), 2):
            even += digits[j]

    # Call <main()>
    main()

Solution

  • There are no errors in your code but it does nothing because:

    1. You don't return your result, even, from oddEvenSame function
    2. In your main function you don't use the returned values from oddEvenSame invocation.

    Here are the minor changes you should do:

    def main():
        # Get Input Number
        n = int(input("Enter a number:"))
    
        # Call <oddEvenSame()>
        print(oddEvenSame(n))
    
    
    def oddEvenSame(n):
        # Split all digits of <n> into their own index within <digits>
        digits = [int(i) for i in str(n)]
    
        # Add even indices of <digits> into <even>
        even = 0
        for j in range(0, len(digits), 2):
            even += digits[j]
        return even
    
    main()
    

    As a side note, you may use slicing instead of loop in oddEvenSame func:

    def oddEvenSame(n):
        digits = [int(i) for i in str(n)]
        return sum(digits[::2])