13/15 and 14/15 Tried using a Raw Input instead of a prepared list


Here is the code I used for

def product(x):
_total = 1
__for i in range(len(x)):
___total = total * x[i]
__return total

number_list = [1, 2, 3, 1, 10 ]
print product(number_list)

choose = str(raw_input("What are your numbers: "))

print product(choose)

How do i code it so that it would not include spaces and commas? I tried writing that if i was equal to a space or a comma, it would return 1 but error keeps on popping out.

Note there was no problem with the first print because it works. its the 2nd one that i have a bit of problem.

thank you guys!



you can try this for the user input . I had to cook up an implementation for the product function but you can use what you implemented

#for python 3.x
#from functools import *
def product(nums):  
    return  0 if not nums else reduce(lambda x,y:x*y, nums)

exit = False
user_list = []
print("Enter your numbers(one at a time)")
print("Hit 'x' to terminate")
while not exit:
    # for python3.x use input(">>")
    user_input = raw_input(">")
    if(user_input == 'x'):
        exit = True
    user_list.append(int(user_input)) if user_input.isdigit() else ""
print product(user_list)

Sample runs


You can also use regular expressions to define the input pattern like below

import re
#for python 3.x
#from functools import *
def product(nums):  
    return reduce(lambda x,y:x*y, nums)

#this is the regular expression that will define the user input
# if the pattern is not matched the program will keep prompting for 
#the right input
pattern = re.compile(r'^(\d+(\s+\d+)*)*$')

print("Enter your numbers separated by whitespaces only")
print("e.g. 1 2 3 4 5 6 7")

#for python3.x use input(">") instead of raw_input(">")
user_list = raw_input(">")

#as long as user's input does not match the right format
# keep prompting
while(not re.match(pattern, user_list.strip())):
    #for python3.x use input() instead of raw_input()
    user_list = raw_input("Enter your numbers separated by whitespaces only\n>")

# print the product of the user's input
print (None if not user_list else product(map(lambda x: int(x),user_list.split())))

sample run