Search code examples
pythonfunctionnumbersperfect-square

Square list of numbers user input Python


i'm trying to write a function where user can input a list of numbers, and then each number gets squared, example [1,2,3] to [1,4,9]. so far my code is this:

def squarenumber():
    num = raw_input('Enter numbers, eg 1,2,3: ').split(',')
    print [int(n) for n in num if n.isdigit()]  ##display user input
    list = []
    for n in num:
        list += int(n)*int(n)
    print list;   

x = squarenumber()

but i get this error saying 'int' object is not iterable. I tried different ways, but still no clue so if anyone can help me i'd be greatly appreciated.


Solution

  • First of all do not use list as a variable, use lst. Also you are incrementing a value not appending to a list in your original code. To create the list, then use lst.append(). You also need to return the list

    def squarenumber():
      num = raw_input('Enter numbers, eg 1,2,3: ').split(',')
      print [int(n) for n in num if n.isdigit()]  ##display user input
      lst = []
      for n in num:
        if n.isdigit():
          nn = int(n)
          lst.append(nn*nn)
      print lst
      return lst  
    
    x = squarenumber()