Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"NameError: name 'number' is not defined" – working with lists

I made a code with the for-loop in Python, and I cannot get it right.
So, Python receives two lists from me. One is named colors and contains the seven colors of the rainbow, while the other one is named crayons_count and contains seven numbers that would represent how many crayons you have from each color.

The problem is, I worked in the code with 2 for-loops. And in the second one, I get a NameError. I have been researching this problem for days.

So, this is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
crayons_count = [10, 5, 7, 8, 9, 2, 3]

for index, color in enumerate(colors):
    print(index, color)

for (color) in colors and (number) in crayons_count:
    print (color, number)

And I was expecting to get something like this:

0 red
1 orange
2 yellow
3 green
4 blue
5 indigo
6 violet
red 10
orange 5
yellow 7
green 8
blue 9
indigo 2
violet 3

For now, I have the results of the first loop but get this error from the second loop:

This is an image with the error

>Solution :

The issue with your code is that you are trying to iterate over two lists at once using a single for-loop. This is not possible in Python.

Instead, you can use the zip() function to iterate over two lists simultaneously. The zip() function takes two or more sequences as input and returns an iterator that aggregates elements from each of the sequences.

colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
crayons_count = [10, 5, 7, 8, 9, 2, 3]

for index, color in enumerate(colors):
    print(index, color)

for color, number in zip(colors, crayons_count):
    print(color, number)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading