Practice Makes Perfect -- product


Practice Makes Perfect : product

The emulator returns the following error:
Oops, try again. Your function crashed on [1, 2] as input because your function throws a "list index out of range" error.

When I run this on my laptop, it works as expected.

def product(numbers):
    a = numbers[0]
    b = numbers[1]
    c = numbers[2]
    total = a * b * c
    return total     

first_number = int(raw_input('Enter a number:  '))
second_number = int(raw_input('Enter a second number:  '))
third_number = int(raw_input('Enter a third number:  '))
numbers = list()
for x in first_number, second_number, third_number:
print product(numbers)


We'll want our function to take a list of any length. Your method is very fixed and depends upon a 3 member list every time.

Not sure this is valid code unless Python is treating the comma separated list as a tuple.


The specs for the exercise were to multiply a list of three integers. I wrote my code with that in mind. If I take the commas out, the emulator complains about a syntax error in the "for" statement.


My apologies for my first statement. I got the idea for "three" from the example given on the page.


I just tested this and Python does treat it as a tuple.

 > a,b,c = 4,5,6
 > y = 1
 > for x in a,b,c: 
..   y *= x 
 > y
=> 120

At any length, this is not the way to a usable function. Work with lists of any length.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.