Hi ALL,
I am completely new to python and when i was playing with a while loop in the Python SHELL the code works but when I then put it into a file and saved and then tried to run it I got the error "NameError: name 'b' is not defined".
I have looked on this site but I cannot find a simple answer my code is as follows:-

while b <= 10:
    print (b)
b += 1

If I declare b as zero at the top of the program above the while command the program runs but into an infinate loop WHY? I expected the loop to jump back to the while command line not to include the original declaration.
Thanks for you help.
PS
I am using version 3.3 if this makes any difference. Thanks again.

# you have to give b an initial value
# so you can increment by 1 in the loop
b = 0

while b <= 10:
    print (b)
    b += 1

The simple answer for why b is not defined in this loop:

while b <= 10:
    print (b)
b += 1

is that b is not, in fact, defined, at least not when you are trying to compare it to 10. Thus, you do indeed want to initialize it to zero before the beginning of the loop.

But wait, you say, why then is it causing an infinite loop, when you clearly have an increment in the loop? Well, the answer there is, you don't have an increment in the loop; you have an increment after the loop, where it does you no good at all. This is simply a matter of incorrect indentation, and easily is solved thusly:

b = 0
while b <= 10:
    print (b)
    b += 1

To finish up, let me answer a question which you haven't asked: why doesn't the while: loop's conditional value default to zero, when the equivalent for: loop's is:

for b in range(0, 11):
    print (b)

The answer is that the value of this b is getting set by the range() generator on the first pass of the loop, and is reset on each subsequent pass.

commented: Nicely done +4

If I declare b as zero at the top of the program above the while command the program runs but into an infinate loop WHY?

Indentation matters in Python. As you wrote it, line 3 (b += 1) is not part of the loop. Indent this line to match the print statement and it should work as you expect.

Also, instead of a while loop, consider using a for loop here.

Thanks All of you it was indeed bad indentation on my part I must remember indentation is important. Thanks all again for the fast replies

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.