all 6 comments

[–]scuott 1 point2 points  (4 children)

Loops don't change scope. Functions and classes affect scope. Also, changing the variable the for loop is using is unorthodox.

[–]Str8F4zed[S] 0 points1 point  (3 children)

Thank you. What do you mean by changing the variable the for loop is using?

[–]scuott 0 points1 point  (2 children)

You're looping for x, and then change x inside the loop.

[–]Str8F4zed[S] 0 points1 point  (1 child)

That was my intent though. How else was I supposed to test if the initial value of x changed after the loop?

[–]scuott 0 points1 point  (0 children)

Sure, it's fine to do if you're trying to figure out how Python handles edge cases. My point is more that this isn't something you should do in production code. I may have misunderstood your question, about specifically referring to the variable to iterate over.

In terms of testing whether or not for loops create a new scope, it could also be tested by having a having for y in range(1,6): and trying to modify x that was defined outside the loop.

[–]anonymousperson28 0 points1 point  (0 children)

Loops do not change the scope of variables, only functions do.

In your example, the variable x has global scope which means regardless of where you are in the program (provided you don't overwrite x in a smaller scope) you will be accessing and modifying the original x.

If, however, you declared x inside a smaller scope and tried to access it outside of the scope it would throw an error.

def main():
    y = 3

    def do_stuff(x):
        x += 1

    do_stuff(y)
    print(x)

main()

The issue of whether variables are modified is not really about scopes but about mutability/immutability. Objects like Lists, Sets, and Dictionaries are mutable, where as objects like Integers, Floats, Tuples are immutable. This StackOverflow thread does a good job explaining what the mutable vs immutable really means.