FAQ: Learn Python: Loops - Using Range in Loops

This was the code I typed
promise = “I will finish the python loops module!”
for n in range(5):
print(promise)
I know the output would be that promise*5
But I don’t know how to explain the funtion of n in line 2. I would like to know what is the meaning of n in this code.
please forgive me if I say something worng. I am new in coding.
Thanks for help in advance

It’s the name you’re using to assign values from your iterable (range(5)) here. On each iteration the next value of that iterable is taken and assigned to n and then the suite of code which makes up the body of the loop is run, in this case the print statement.

So it’s part of the syntax of for loops in Python but you’re not actually using the value. You could change your print function, or add a new one which outputs n so you can see how it changes on each new iteration if you like.

2 Likes

Is there a way of tracking loop iterations involving a list or a collection? like the way it is done in this lesson: For loops using range() function. Link :point_down:
https://www.codecademy.com/courses/learn-python-3/lessons/learn-python-loops/exercises/range
For example, in the exercise below;

sport_games = ["football", "hockey", "baseball", "cricket"]
for sport in sport_games:
  print(sport)

How would I track the loop?

1 Like

It may not have come up, nor may it ever, but Python has a list method that can enumerate a list, giving them physical indices.

>>> sport_games = ["football", "hockey", "baseball", "cricket"]
>>> for i, x in enumerate(sport_games):
    print (f" Index: {i}\n Sport: {x}")

    
 Index: 0
 Sport: football
 Index: 1
 Sport: hockey
 Index: 2
 Sport: baseball
 Index: 3
 Sport: cricket
>>> 

The method returns an iterator which will come up in the course, eventually. This type of object is consumed when used. You’ll learn more about that concept.

2 Likes

ok I get it, thank you so much. I will try it

1 Like

Hi guys, please can someone explain like I’m 5 what the str() function does in a loop? (see below)

for temp in range(6):
print("Loop is on iteration number " + str(temp + 1))

Why can’t it just be print("Loop is on iteration number " + (temp + 1)

Many thanks :slight_smile:

str is a Python data type used to represent text (anything in quotes). It is a class with a str() constructor.

In other words, anything we give to the constructor will be returned as a string object.

 str(3.14)    =>    '3.14'

Numbers cannot be concatenated to a string so in order to print them together we need to cast the number to a str.

2 Likes

That makes sense, thank you!

1 Like

is it because you are using an already created variable as your temporary variable that the for loop needs to temporarily operate in your code? (trying to convey how I visualize it. id imagine its basically looking at itself and not looking for the previous variable. is this why it needs to be a temp var?

When we assign an iteration variable in a for loop, it takes its assignments from the iterable (the range, in this case), each in turn and in sequence. If that chosen variable happens to exist already, it gets immediately overwritten.

For this reason, it is always wise to invent a new, yet unused outside of any loops, variable so as to avoid accidentally destroying the existing variable and its value.

The variable we choose to use within a loop can be reused in other loops without upsetting any apple carts.

One convention when iterating a range or list is to use the letter i as our iteration variable.

for i in range(10):
    print (i, end=', ')
for i in range(10, 20):
    print (i, end=', ')

Given that the two loops are independent of each other (one follows the other in execution order) reusing the variable i has no effect. All we need remember is to never use the variable name in our main program.

thank you for validating that!

1 Like

okay, I just got to this part of the lessons myself and was incredibly confused, then I found this forum and read through it and now it makes sense.

What the lesson SHOULD say, FOR loops that use the “range()” function, the temp value cannot match the str name convention otherwise it tries to read the temp loop name.

promise = "I will not cheat"

for promises in range(5):
  print(promise)

I will not cheat
I will not cheat
I will not cheat
I will not cheat
I will not cheat

The temp part is not very clear for me. Suddenly this phrase appears " Something to note is we are not using temp anywhere inside of the loop body." Then comes the explanation but I didn’t get what is necessary for. Thanks.

@luisardi I think it’s saying that if here, we are learning about For loops using range function for the main purpose of simplying repeating a task N number of times. The range function is used because it provides an easily generated iterable that satifies the N requirement and the “list” itself takes very little memory and can be dumped after used. In those cases, the temporary variable we create does not matter and doesn’t have to appear inside the loop. If it mattered (ie. the iterable item that we do each loop in is needed) we can always call the temp variable within the loop, as demonstrated in the example after.

Hopefully this helps!

1 Like

Why is it that for this exercise, I can literally put anything (except the word “promise”) after “for” loop to print the promise variable five times? If that’s the case, what does that “anything” do here in this loop? (a placeholder?)

promise = “I will finish the python loops module!”

for anything in range(5):
print(promise)

Just that, as it has no other purpose; its value is never accessed. For loops like this (counting loops) it is very common to see,

n = 42  #  or any integer
for _ in range(n):
    # repeated action

The underscore tells a reader to not look for any interaction involving the iteration variable.

3 Likes

Now I know that not every single variable has to do something in a program, though it does seem a bit counterintuitive to a beginner!

1 Like

It looks like it doesn’t matter what kind of range you put into range()

promise = “I will finish the python loops module!”
numbers = range(2)
for numbers in range(500):
print(promise)

This will still print it 500 times, even though we set numbers = range(2)

1 Like

To preserve code formatting in forum posts, see: [How to] Format code in posts

Try adding in a few print statements:

promise = "I will finish the python loops module!"

numbers = range(2)
print(numbers)

for numbers in range(5):
    print(promise)
    
print(numbers)

Output:

range(0, 2)
“I will finish the python loops module!”
“I will finish the python loops module!”
“I will finish the python loops module!”
“I will finish the python loops module!”
“I will finish the python loops module!”
4

You assigned range(2) to the numbers variable initially. Then immediately in the next statement, you have used numbers as the loop variable in a for loop. So the original value assigned to the variable gets overwritten as soon as the loop executes. After you exit the loop, numbers holds the last value that was assigned to it (In my snippet, the last value is 4. In your snippet, the last value assigned to numbers will be 499).

1 Like

Why does the below print the message vertically,

promise = “I will finish the python loops module!”
: for prom in promise:
print(prom)

and (below) prints it horizontally but multiple times?

promise = “I will finish the python loops module!”

for prom in promise:
print(“I will finish the python loops module!”)