for loop in python
Steven D'Aprano
steve at pearwood.info
Thu Apr 28 05:48:37 EDT 2016
On Thu, 28 Apr 2016 07:34 pm, g.v.aarthi at skct.edu.in wrote:
> start_list = [5, 3, 1, 2, 4]
> square_list = []
Here you set square_list to a list.
> # Your code here!
> for square_list in start_list:
.....^^^^^^^^^^^^^
Here you set square_list to each item of the start_list. So the first time
around the loop, you have:
square_list = 5
The second time:
square_list = 3
The third time:
square_list = 1
and so on. Except that the next line:
> x = pow(start_list, 2)
tries to raise *start_list* to the power of 2:
[5, 3, 1, 2, 4]**2
which will raise an exception:
> TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
So you need to do this:
start_list = [5, 3, 1, 2, 4]
square_list = []
# Your code here!
for ????? in start_list:
Choose a different name! Not one you have already used. Something
like "value" or "x" or "the_number_we_want_to_square".
x = pow(?????, 2)
square_list.append(x)
And you only need to sort the square list once, at the end, *outside* of the
for-loop, not inside it. (No need to indent the sort line.)
--
Steven
More information about the Python-list
mailing list