[Tutor] Two subsequent for loops in one function - I got it!

Steven D'Aprano steve at pearwood.info
Sun Nov 24 01:48:19 CET 2013


On Sat, Nov 23, 2013 at 08:57:54PM +0100, Rafael Knuth wrote:

> I have only one question left.
> Here's my original program again:
> 
> for x in range(2, 10):
>     for y in range(2, x):
>         if x % y == 0:
>             print(x, "equals", y, "*", x//y)
>             break
>     else:
>         print(x, "is a prime number")
> 
> So the first output of the outer loop is: 2.
> It's then passed to the inner loop:
> 
>     for y in range(2,x):
>         if x % y == 0:
>     ...
> 
> And I was wondering what is happening inside that loop.

Absolutely nothing! The inner loop doesn't get executed. Python first 
generates the range object range(2, 2) which is empty (it starts at 2 
and stops at 2). Since y iterates over an empty list, the loop 
immediately exits and the body gets executed zero times.


> The output of
> 
>     for y in range (2,2):
> 
> should be ... none - correct?

Not quite "none", more like *nothing*. There's no output at all, because 
the body isn't executed even once.

[...]
> Just want to understand how Python deals with "no values" within a program.

It doesn't. Things always have a value, if they are executed at all. But 
if they don't get executed, then they don't exist at all.


if False:
    # This code never runs!
    print("This will never be printed")
    x = 23

print(x)



At this point (unless x happened to have been defined even earlier in 
the code), trying to print x will cause a NameError -- the name 'x' 
doesn't exist.


-- 
Steven


More information about the Tutor mailing list