FAQ: Learn Python: Loops - Review

This community-built FAQ covers the “Review” exercise from the lesson “Learn Python: Loops”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science
Data Science

FAQs on the exercise Review

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

11 posts were split to a new topic: I’m struggling to understand this exercise?

Apart from others, what I’ve realised so far about loops, is that great attention must be paid when we use “print”. Sometimes it is necessary to “print” inside the loop with indentation, but in other cases this brings trouble and “print” should be written outside loop without indentation.

To be more precise, about the loop with digits:
for item in single_digits:
…print(item)
…squares.append(item**2)
print(squares)
Here, the output seems normal. The first print(inside loop), gives the items from 0 to 9 in a vertical order and then, the second print (outside loop) gives the all squares in a list [0,1,4,9,16,…81]

However, if both “print” are inside loop, the output is complex:
0
[0]
1
[0, 1]
2
[0, 1, 4]
3
[0, 1, 4, 9] and so on…

I suppose this is because of the iterations. It is like every iteration in the loop consists of two “sub-iterations”, one for the print items and one for the print squares. Is it true?
If this is the case, why the result of the second “sub-iteration” is a list including all the squares so far and not the result of the squared item? i.e.

2
4
3
9
4
16…

Hello,guys!Help me with the code,please!Why can`t I use

single_digits=range(10)
for item in single_digits:
  print(item)
  squares=[]
for element in squares:
  squares.append(item**2)
  print(squares)
  cubes=[item**3 for item in single_digits]
  print(cubes)

instead of

single_digits = range(10)
squares = []

for item in single_digits:
  print(item)
  squares.append(item**2)
  
cubes = [item**3 for item in single_digits]
print(cubes)

Hello
when does the while loop stop.
for example this my code to find a factor using a while loop

def factorial(n):
if n == 0 :
return 1
if n < 0 :
ValueError(“Inputs 0 or greater only”)
result = n
while n != 0 :
print(‘{} * {}’.format(result,n-1))
result*= n-1
n-=1
return result

test cases

print(factorial(3) == 6)
print(factorial(0) == 1)
print(factorial(5) == 120)

and this is the result of the code

3 * 2
6 * 1
6 * 0
False
True
5 * 4
20 * 3
60 * 2
120 * 1
120 * 0
False

in my code the condition statement is while n != 0 and when n==0 he still excute the code i dont under stand why ? like (120 * 0) and ( 6 * 0) he excute the code as n == 0 ?

There is the fly in the ointment. The while condition is looking at n but the math is being done on, n - 1.

while n - 1 > 0:

should fix that.

Aside

Even though your situation is quite well controlled (decrement by 1, each iteration) we should avoid using equality in a loop condition. Safer to use inequality so that we don’t accidentally slip below zero (by some freak of nature) and end up with an infinite loop.

1 Like

The output should be sufficient enough to explain the code. In the first example, the number is printed, then the list is appended with its square, then the list is printed. We can see it accumulate as the range is iterated.

Indentation is a fundamental part of Python syntax. It’s role is to set block scope. When the indent is removed from the last line it only prints when the loop is complete.

1 Like

A post was merged into an existing topic: What is a Super User?

In Python Loops: Medical Insurance Project, there are 2 extra tasks to practice more using loops. The first extra task is to “Change the first for loop into a while loop.”

Can anyone give the solution for this? I think I’m still in confusion on converting for loops into while loops.

Thanks a lot!

for loops iterate over a defined sequence, so there is a starting point and an ending point. To convert to a while loop we can establish the starting point and loop until we reach an ending point. But there is more. We can loop infinitely (an indefinite number of iterations) until a breaking condition is met. while has no fixed number of iterations like a for loop.

Please give us an example of your for loop for further examination and discussion.

1 Like

In Python Loops: Medical Insurance Project, there are these lines of code:
actual_insurance_costs = [1100.0, 2200.0, 3300.0, 4400.0, 5500.0, 6600.0, 7700.0]
total_cost = 0

the task is:
Use a for loop to iterate through actual_insurance_costs and add each insurance cost to the variable total_cost.

so i wrote:

for actual in actual_insurance_costs:
  total_cost += actual

the extra task is:
Convert the first for loop in the code to a while loop.

how do you solve the extra task?

Here is an example of a while loop that will do the same as your for-loop:

def solve():    
    # initialize an index counter
    idx = 0
    # initialize a total counter
    tt = 0
    #while index is less than or equal to (length of 'actual_insurance_costs') -1 
    while idx <= len(actual_insurance_costs)-1:
        # increment total by indexed element
        tt += actual_insurance_costs[idx]
        # increment index by 1
        idx += 1
    # return total
    return tt


I hope this helps!

2 Likes

One could do a straight across swap by using an index pointer that increments; or, one could exhaust the list:

temp = actual_insurance_costs[:]
total = 0
while len(temp):
    total += temp.pop()
return total

The original list remains intact.


If temp.pop() looks foreign then revert to the index form until that built-in method comes up (which it does smack dab in the middle of a challenge); or, look it up on docs.python.org.

The method as used above removes the value from the right side of the list and assigns it to the variable. Gradually the list shortens to contain nothing.

2 Likes

I got stuck in the review section and had to go through the chapter to retake notes.
I had to realize there are essentially 4 ways to go about list comprehension, according to the module:

  1. create a list with range()

  2. create a list by new_list = [ for in ]

  3. list comprehension with the conditional before the loop (acting as a filter) Examples of doubling number list
    doubled = [num2 if num<0 else num3 for num in numbers]

4A. list comprehension with the conditional after the loop (acting as a transformation)
for num in numbers
if num<0
only_neg_doubled. append(num2)
4B.
neg_double= [num
2 for num in numbers if num<0]

I posted the module review below and was wondering what’s the discrepancy between the two.

Your code below:

single_digits = range(10)
squares =
cubes=

#Guided
for items in single_digits:
#print(items)
squares.append(items**2)
print(squares)

for items in single_digits:
cubes.append(items**3)
print(cubes)

#Seperation
print(‘\n’)

#Retry
single_digits = range(10)
square = [num2 for num in single_digits]
cube = [num
3 for num in single_digits]
print(square)
print(cube)

I am looking for someone to explain what was wrong with my initial logic on this task.

I inputted

single_digits = range(0, 10)

squares =

for i in single_digits:
print(i)
single_digits.append(i**2)

Opposed to:

for i in single_digits:
print(i)
squares.append(i**2)

What output would my initial code run

Not sure we can append to a range object, but nonetheless, this is a bad idea since it is what we are iterating over (the range). Besides, you have a squares list so why not append the squared values to that?

1 Like

Thanks,

I misunderstood how .append is applied, but it clicked after reading this!

1 Like

Hey there, I have a question about the Carly’s Clippers exercise on step 5.

This was given:

hairstyles = [“bouffant”, “pixie”, “dreadlocks”, “crew”, “bowl”, “bob”, “mohawk”, “flattop”]
prices = [30, 25, 40, 20, 20, 35, 50, 35]
last_week = [2, 3, 5, 8, 4, 4, 6, 2]

I’m trying to subtract 5 from each price in prices using a loop, but I’m confused why the following code is giving me only an output of 30 for new_prices

for price in prices:
new_prices = price - 5
print(new_prices)

The hint says to use this: “new_prices = [price - 5 for price in prices]” but I’m confused why the above code won’t also work.

Thanks in advance

I am pleasantly surprised to get this “right” for the program… but why is it so ugly when printed? How can I clean this up?

‘Clean this up’, how?
The function printed what you specified: single digits between 1-10 (not including 10) then squared each number and cubed each number, appended each to a list, and printed each number 1-9 as well as a list of those squared and cubed values.