i can't get this code to work and have tried a lot of things

Viewed 25

this is the python code i am working on 2 hours of sleep please help me get this to work the question for the code was to write a program to multiply all the elements of the list at even indexes.

def EvenProduct(arr, n):
    even = 1
    for i in range (0,n):
        if (i % 2 == 0):
            even *= arr[i]
    print("Even Index Product : " , even)

# Driver Code

arr = int(input("Enter the size of the list "))
print("\n")
num_list = list(int(num) for num in input("Enter the list items separated by space ").strip().split())[:arr]

print("User list: ", num_list)
n = len(arr)

EvenProduct(arr, n)

and i got this error

Traceback (most recent call last):
  File "<string>", line 26, in <module>
TypeError: object of type 'int' has no len()
2 Answers

One issue is that you read in arr via:

arr = int(input("Enter the size of the list "))

But then you attempt, later, to call len() on arr:

n = len(arr)

So, since arr is already an int, it has no length. It is a single item.

I think you meant to use num_list and not arr. If that's the case, then the last two lines of your program should be:

n = len(num_list)
EvenProduct(num_list, n)

Especially since, in num_list, you are referring to arr[i] which is invalid if arr is an int. I think you were assuming that arr was num_list, or maybe at some point you changed the name.

You meant to write n = len(num_list).

The value arr is an integer so, as the error indicates, it has no length.

There's no need to pass the length into the function, you can calculate it inside with len(arr).

You can use the enumerate global function to get both index and value simultaneously.

#!/usr/bin/env python

def evens_product(l):
    product = 1
    for i,v in enumerate(l):
        if i % 2 == 0:
            product *= v
    return product

result = evens_product([1,2,3,4,5,6])
print(result) # 15
Related