How to use variables in Python ?

2 min

First of all, in Python and a lot of other programming languages variables are a way to store temporary values that will be used within the execution of our program.

Second, in Python unlike a lot of other languages you don't need to specify the type of variable when creating a variable.

Third, a variable can change its type along the way. It is not recommend but Python can handle it.

Here are all the possible variables that you can use in Python:

  1. Numbers (integer, float, complex)
  2. Strings (single quote, multiple quote, multi-line)
  3. Booleans
  4. Data Structures (Lists, Dictionaries, Tuples, Sets, ...)
  5. Files

Our focus in  this article are about 1,2 and 3.

Assign a value to a variable

When you first declare the variable and assign a value to it, the variable is created.

Here are some examples :

age = 27 # An integer
gpa = 5.7 # A float
name = "Brice" # A double quote string
has_siblings = True # A boolean
quote = """ # Multi line string
The world as we have created it is a process of our thinking. 
It cannot be changed without changing our thinking.

Albert Einstein
Examples of variables creation

Edit the value of a variable

When a variable already have a value like above, it is totally possible to reassign a new value to it.

age = 28 # Assigning a new value to an integer
gpa = 5.5 # Assigning a new value to an float
name = "James" # A double quote string
Value reassignment works the same for all variables

Show the value of a variable

There is in Python a general method to show the value of a variable within a console.

The print() method.

Here is an example that prints the variable age with a value of 28

age = 28

This will show the value 28 in the console

F-string printing

You will need to print multiple variable along with text.

Here is the best method to do that has been introduced in Python 3.6

age = 28
name = "Brice"

print(f"My age is {age}")
print(f"{name} age is {age}")
Show the value of multiple variable along with text.

Delete the variable

You might need once or twice to delete the value of a variable for various reasons.

Using the del attribute before a variable you delete it.

This frees up memory space

Here is how you do it :

age = 28
del age
How to delete a variable in Python

Here you are ! You now know how to use a variable in Python !