1

This code will raise NameError: name 'i' is not defined:

for n in range(2, 101):
    for i in range(2, n):
        if n % i == 0:
            break
    if n % i != 0:
        print(n, end=' |')

This code will execute without error:

n = 97
if True:
    for i in range(2, n):
        if n % i == 0:
            break
    if n % i != 0:
        print(n, end=' |')

Could anybody tell why?

2 Answers 2

5

When n is 2, range(2,n) will be an empty list, and so the body of that loop will not execute at all.

Sign up to request clarification or add additional context in comments.

Comments

3

That has nothing to do with scopes, in fact for loops in python do not create their own scopes unless it is in a list comprehension. The reason you are getting an error is i is not getting created in the first code.

for n in range(2,101):
# at first iteration n == 2
    for i in range(2,n):
    # this is equivalent to range(2,2) in first iteration

So, there is nothing to iterate on, hence no value is assigned to i. And when it goes to n % i, it throws NameError.

In the second block:

for i in range(2, n):
# value if i is 2

As i has a value, hence defined, it does not throw NameError.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.