Question

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.

Was it helpful?

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()

OTHER TIPS

With lists, you should use append() instead of +=. Here is the corrected code:

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:
        lst.append(int(n)*int(n))
    print lst

x = squarenumber()

[Running the code]
Enter numbers, eg 1,2,3:  1,2,3
[1, 2, 3]
[1, 4, 9]
def squarenumber(inp):
    result = [i**2 for i in inp]
    return result

>>>inp = [1,2,3,4,5]
>>>squarenumber(inp)
[1, 4, 9, 16, 25]

You can get the desired output using list comprehension instead another loop to append the square of a number to list. Dont use list as a variable name

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

x = squarenumber()

Since you're using the list comprehension to print the input, I thought you might like a solution that uses another one:

def squarenumber():
    num = raw_input('Enter numbers, e.g., 1,2,3: ').split(',')
    print [int(n) for n in num if n.isdigit()]
    print [int(n)**2 for n in num if n.isdigit()]

x = squarenumber()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top