Reputation: 2183
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.
Upvotes: 0
Views: 6819
Reputation: 4425
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()
Upvotes: 1
Reputation: 1953
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()
Upvotes: 0
Reputation: 377
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()
Upvotes: 0
Reputation: 22465
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]
Upvotes: 0
Reputation: 32207
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]
Upvotes: 0