Reputation: 4101
I have a list of numbers:
nums = [12, 10, 32, 3, 66, 17, 42, 99, 20]
My first task was to print each number on a new line, like this:
12
10
32
3
66
17
42
99
20
I was able to do this by creating a for loop that printed the integers in the list:
nums = [12, 10, 32, 3, 66, 17, 42, 99, 20]
for i in nums:
print(i)
Now I need to write another for loop that prints each number and its square on a new line, like this:
The square of 12 is 144
The square of 10 is 100
The square of 32 is 1024
The square of 3 is 9
The square of 66 is 4356
The square of 17 is 289
The square of 42 is 1764
The square of 99 is 9801
The square of 20 is 40
So far I have actually been able to print the squared values, but can't get them on separate lines by themselves. I also need to rid of the brackets around the values.
My attempt:
nums = [12, 10, 32, 3, 66, 17, 42, 99, 20]
for i in nums:
print(i)
squared = [ ]
for i in nums:
squared.append(i * i)
print("The square of", i, "is", squared)
Resulted in:
12
10
32
3
66
17
42
99
20
The square of 12 is [144]
The square of 10 is [144, 100]
The square of 32 is [144, 100, 1024]
The square of 3 is [144, 100, 1024, 9]
The square of 66 is [144, 100, 1024, 9, 4356]
The square of 17 is [144, 100, 1024, 9, 4356, 289]
The square of 42 is [144, 100, 1024, 9, 4356, 289, 1764]
The square of 99 is [144, 100, 1024, 9, 4356, 289, 1764, 9801]
The square of 20 is [144, 100, 1024, 9, 4356, 289, 1764, 9801, 400]
I need to get rid of the brackets and need to only include one squared value per line (that corresponds with the integer to the left). How should I do this?
Upvotes: 1
Views: 24757
Reputation: 21
nums = (12, 10, 32, 3, 66, 17, 42, 99, 20)
for i in nums:
print(i)
for i in nums:
print("the square of",i,"is", i**2)
Upvotes: 2
Reputation: 16865
I'm not sure if you actually want to track the squares or if that was just part of your effort to get them printed.
Assuming you did want to track the squares, a minor change would be:
nums = [12, 10, 32, 3, 66, 17, 42, 99, 20]
for i in nums:
print(i)
squared = [ ]
for i in nums:
sqr = i * i
squared.append(sqr)
print("The square of {} is {}".format(i, sqr))
This allows you to have the current square ready to work with without having to reference it from the array.
If you really did mean to reference the squared value from the array, you'd use a negative index to fetch from the end of the array:
nums = [12, 10, 32, 3, 66, 17, 42, 99, 20]
for i in nums:
print(i)
squared = [ ]
for i in nums:
squared.append(i*i)
print("The square of {} is {}".format(i, squared[-1]))
Upvotes: 2
Reputation: 1
nums = [12, 10, 32, 3, 66, 17, 42, 99, 20]
for i in nums:
print(i**2)
Upvotes: 0