Search code examples
pythonpython-3.xlistuser-inputmap-function

Here's my code. I am trying to get user input of integers, go through a function utilizing map and returning a list of cubed results


I am using Python 3

vals = int(input("Enter comma separated numbers"))

def cube(nums):
    return nums**3

print(list(map(cube,vals)))

I get this error when I input 2,3

#Traceback (most recent call last):
  File "/Users/administrator/Documents/Python/Master Python/Day7a.py", line 15, in <module>
    vals = int(input("Enter comma separated numbers"))
ValueError: invalid literal for int() with base 10: '2,3'

This works when I put the integers myself, though:

vals = [2,3]
def cube(nums):
    return nums**3

alist = (list(map(cube,vals)))

Solution

  • You should convert the input from the user to a sequence of integers (or floats, if so desired) before you can map vals to perform numeric operations:

    vals = map(int, input("Enter comma separated numbers").split(','))