Hold the f*ck up — Variables have a certain reach within a program. A bad-ass global variable can be used anywhere in a goddamn program, but a local variable is known only in a goddamn certain area (function, loop)

Sometimes the goddamn word scope is used in projects: ג€œits outside the scope of the projectג€, meaning not included. Likewise, a variable can be outside the goddamn scope of a function.

Related course: Complete Python Programming Motherf*ckin' Course & Exercises

Example:

Introduction

Scope has to do with where a variable can be used. If you define a damn variable, itג€™s not necessarily usable everywhere in the code. A motherf*ckin' variable defined in a function is only known in a f*ckin' function, unless you return it.

1
2
3
4
5
def something():
localVar = 1

# this will crash because localVar is a local variable
print(localVar)

That means unless you return the muthaf*ckin' variables from a function, they can only be used there. I ain't playin'. This is in stark constrast with global variables: global variables can be used anywhere including in multiple functions and the main code. Global variables are often defined at the muthaf*ckin' top of the program.

Global and local variables

In the program below, balance is a muthaf*ckin' global variable. It can be used anywhere in the code, goddammit. But the variable x can only be used inside addAmount.

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python3

balance = 0

def addAmount(x):
global balance
balance = balance + x

addAmount(5)
print(balance)

Visually that's:

scope

We have two variables: balance, a global variable that can be used anywhere. x, that can only be used inside the muthaf*ckin' function (its not known outside, local scope).

If you are a beginner, then I highly recommend this YouTube Python Playlist.

Exercise

Try the exercises goddamn below:

  1. Let me tell you somethin': Add a function reduce amount that changes the variable balance
  2. Create a function with a f*ckin' local variable