Home > Net >  How do I get this for loop to print
How do I get this for loop to print

Time:02-14

Would any happen to know why I keep getting the error below in my for loop? Any insight would be greatly appreciated and helpful.

the_count = [1, 2, 3, 4, 5]
for number in the_count:
print(f"This is count {number}")

NameError                                 Traceback (most recent call last)
<ipython-input-3-e3d6b461f13e> in <module>
----> 1 print(f"This is count {number}")

NameError: name 'number' is not defined

CodePudding user response:

Well it should give indentation error but it’s giving name error

the_count = [1, 2, 3, 4, 5]
for number in the_count:
    print(f"This is count {number}")

This is how your code should be.

CodePudding user response:

Are you running this line by line in a terminal or as a .py file? This code works perfectly if you run it as a python file.

the_count = [1, 2, 3, 4, 5]
for number in the_count:
    print(f"This is count {number}")

Which outputs:

This is count 1
This is count 2
This is count 3
This is count 4
This is count 5

You may run into errors with the for loop if you run this code line by line, since the for loop would be executed fully prior to even reading the print statment.

CodePudding user response:

Here are a few ways you can print the loop:

# Option 1
the_count = [1, 2, 3, 4, 5]
for x in the_count:
    print('This is count:'   str(x))

# Option 2
the_count = [1, 2, 3, 4, 5]
for x in the_count:
    print(f"This is count {x}")
  • Related