Variables in Python can hold text and numbers. For example:

The variable names are on the left and the values on the right. Once a variable is assigned, it can be used in other places of the program.

Related Course:

In the example above, we have three variables: x, price and word.

Note: Variables may not contain spaces or special characters.

Text in variables

Text variables may be defined in 3 ways:

The type depends on what you prefer. 


Once defined variables can be replaced or modified:

Python supports the operators +, -, / and * as well as brackets.  Variables may be shown on the screen using the print statement.

The first output of the program above is simply the raw value of the variables. If you want to print a more detailed message like “x = 5”, use the line ‘print(“x = ” + str(x))’. This str() function converts the numeric variable to text.

Global variables

What is the difference between global and local variables?

A global variable can be accessed anywhere in code. A local variable can only be used in a specific code block.

Related course:

global variable example

We say the scope is global, it can be used in any function or location throughout the code.
In the example below we define a global variable, y amount lines of code later we can still use that variable.

Note: In Python a global variable is always limited to the module. Thus, there is no global variable as there is in other programming languages. It’s always within a module.

local variables

This is contrary to a local variable, which can only be accessed in the local scope.
In the example below, x is a local variable..

If a variable is declared inside a function or loop, it’s a local variable. Global variables are usually defined at the top of the code.

best practice

Global variables are considered a bad practice because functions can have non-obvious behavior. Usually you want to keep functions small, staying within the size of the screen. If variables are declared everywhere throughout the code, it becomes less obvious to what the function does.