Reusing Temporary Variables

Python: Loops | Codecademy

In this exercise we’re introduced to for loops and temporary variables. As far as I can understand it doesn’t matter what we use for the temporary variable, but it’s good practice to make it make sense.

Does this mean we can reuse the same temporary variable for different things in a piece of code? Can we use the name of a defined variable (although this may cause confusion to the reader)? Could this cause bugs or other issues? It appears to work fine in the example below but that’s a super simple piece of code.

board_games = ["Settlers of Catan", "Carcassone", "Power Grid", "Agricola", "Scrabble"] sport_games = ["football", "hockey", "baseball", "cricket"] for game in board_games: print(game) for game in sport_games: print(game)

The basic syntax in Python for loops is:

for var in iterable:
    do something here

The loop variable, or, “var” takes on the value of the next item every time it loops through the iterable.
The iterable can be any type of object—string, list, tuple, dictionary, a file, set, etc.

Yes, but that doesn’t answer the question.

Would using the same temporary variable multiple times cause issues?
For example, if var = n in every loop.
for n in iterable:

Would using a pre-defined variable in a loop cause issues?
For example, if var = iterable
for iterable in iterable:

Well, did you try it out multiple times? And what happened?

names = ["Jerry", "Elaine", "George", "Kramer"]
games = ["baseball", "soccer", "hockey", "football"]
boroughs = ["Manhattan", "Brooklyn", "Bronx", "Queens"]

for x in names:
    print(x)

for x in games:
    print(x)

for x in borough:
    print(x)

Jerry
Elaine
George
Kramer
baseball
soccer
hockey
football
Manhattan
Brooklyn
Bronx
Queens

the loop variable is directly related, or bound to the iterable in the (each specific) for loop.

animals = ['cat', 'dog', 'koala', 'panda']

for puma in animals:
    print(puma)  

cat
dog
koala
panda

iterable = ["house", "apartment", "tree", "sky"]

for iterable in iterable:
    print(iterable)

house
apartment
tree
sky

You can call the loop var whatever you want. The for statement iterates over the sequence in the order that they are in the sequence.

See:
https://docs.python.org/3/tutorial/controlflow.html#for-statements

And:
https://docs.python.org/3/reference/compound_stmts.html#for

Further, Assignment Statements:
https://docs.python.org/3/reference/simple_stmts.html#assignment

1 Like