0

Take the pseudocode below for example:

Python keeps the previous value for x, so if get_sum() fails, the conditional is still checked using the previous value of x. Is this because python for loop doesn't introduce a new scope and is it ok to simply del the object at the end of each iteration?

for number in number_list:
    try:
        x = get_sum()
    except:
        ....

    if x > 100:
        do something
    
4
  • You can always write: x = None; x = get_sum() and check for None later. Commented Feb 22, 2022 at 17:33
  • " Is this because python for loop doesnt introduce new scope and is it ok to simply del the object at the end of each iteration?" Yes, Python does not have block scope, x is just a global variable here (or if it is in a function, a local variable, but local to the function not to a the block). Note, you don't del objects, you del variables Commented Feb 22, 2022 at 17:41
  • But if you do del x then x > 100 will throw a NameError (or UnboundLocal if you are in a local scope...) Commented Feb 22, 2022 at 17:41
  • 1
    I know it's pseudocode, but this warning is important anyways: Never use a bare except! Except only the errors you expect to happen! Commented Feb 22, 2022 at 17:47

1 Answer 1

2

Every variable in python is created in the scope of their respective functions and classes rather than at different levels of indentation, or in for loops or while loops. There's no block scope in python like there is in java.

If you need x to not retain its old value, you can always set x = None in your except clause and have a conditional catch it later on. If i'm misinterpreting your question please leave a comment

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

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.