Home Python Course Menu Book

Python Function Scope

 

The variable you set up can't be seen from everywhere in your Python code. If they could be seen from anywhere in your code they would have what's called global scope. But variables you set up inside of functions can only be seen inside of that function. This is called local scope. Try this as an example.

In your function from the previous section, as soon as your type any of the variables set up there, such as add_ten, you'll see a popup box appear. The name of your variable will be on the list:

IntelliSense list in PyCharm

Now try the same just after the code outside of the function, just below the print line "The addition total was". You'll see the popup again:

Example of local scope in Python

But notice that add_ten is not on the list. That's because the add_ten variable can't be seen outside of the addition function. It is local to that function.

You can set up a new variable that has the same name as one inside a function, but that can lead to difficulties and bugs that are hard to track down.

Later in the course, you'll learn more about global variables. For now, let's move on. We'll take a look at programming loops in Python.