Even though it looks pretty simple, its was very confusing for me at the time.

So, lets have a look at the example below:

40% off TNW Conference!

In one code snippet, the global variableXgives anUnboundLocalError.

You’re probably making these Python mistakes — here’s how to avoid them

However, when we have a go at print the variable, it works.

The has to do with scoping.

When you make an assignment to a variable in a scope (e.g.

Article image

This is what happened in the first scenario when we didx += 1.

Or if we are lucky, we get an error and easily notice it.

But let me give you an example of what I mean.

Article image

Even today, I sometimes make this mistake.

In any case, its a bad situation to have.

A classic mistake is the following:

By simply creating a variable namedlistwe broke the access to thelistfunction.

Article image

This article was originally published onLive Code StreambyJuan Cruz Martinez, founder and publisher of Live Code Stream.

Sign up for updates on everything related to programming, AI, and computer science in general.

Also tagged with

Article image

Article image

Article image

Article image

Article image

Article image

Article image

Article image