Question: Looking for a way to explain something in Python to my students. If we start with number\_list = range(100), we can use a for loop such as...

```
for n in number_list: (do something)  

```

If we have the same set up, but try to use a while loop, n comes back as undefined. How do I explain that?

```
while n in number_list < 20: (do something)  --> n is undefined

```

I guess it is more curious why it's OK in the for loop. I have been harping on them to initialize variables before using them, so why does n work just fine in the for loop?

Answer: 
Your current `while` loop is mostly gibberish. There's no `in` clause in a `while` statement (unless you're using the `in` operator to check if a value is a member of a container). Unlike a for loop, a `while` doesn't assign any value to a name on each iteration, it just checks the truth value of the expression you give it. That expression needs to be valid *before* the loop runs!

You can write a `while` loop that is almost equivalent to your `for` loop:

```
number_list = range(100)

iterator = iter(number_list)
try:
    while True:
        n = next(iterator)

        # do stuff here with n (body of the loop)

except StopIteration:
    pass

```

(The only way this is different from the for loop is that it creates the name `iterator` in the current namespace, while a `for` loop stores its iterator internally, without it being accessible to Python code.)

Unfortunately, that loop is unlikely to be easier for your students to understand, since exceptions are probably more complicated than looping.

If you only need to be able to iterate over a sequence (such as a `list` or a `range`), you can make a simpler `while` loop that uses an index to get each value from the sequence, rather than using the iterator protocol:

```
number_list = range(100)

i = 0
while i < len(number_list):
    n = number_list[i]

    # do stuff with n here

```
```
for n in number_list: (do something)  

```

Pick one element from the number\_list(in Pur case its a range) then save that value in a variable called 'n' , the value of the 'n' will change every time you run the for loop. the loop will exit when it encounters a 'StopIteration'. The variable 'n' will get created automatically with a value we fetch from the number\_list

> 
> `while n in number_list < 20:`
> 
> 
> 

Here you checking a variable's value present inside the list number\_list. But it is not defined. while only runs when it get True value from the condition