Language: EN


Variables in Python

Variables are containers that allow us to store and manipulate values in our programs.

This value can be of any data type in Python, such as numbers, strings, lists, dictionaries, among others.

Internally, the name of the variables acts as an “alias” to refer to a section of the computer’s memory, where we are going to store a value.

Variable declaration

In Python, we do not need to explicitly declare the type of a variable before assigning it a value. By assigning a value to a variable, we are creating a reference to that value in memory.

When we assign a value using the = operator, Python will automatically determine the type of the variable. Let’s see some examples:

# Assignment of values to variables
number = 10
name = "John"
list = [1, 2, 3]

# Printing the values of the variables
print("Number:", number)  # Output: Number: 10
print("Name:", name)  # Output: Name: John
print("List:", list)  # Output: List: [1, 2, 3]

In this example, we have created three variables:

  • number which contains the value 10
  • name which contains the string "John"
  • list which contains a list [1, 2, 3].

Python automatically infers the data type based on the value we assign.

Naming rules for variables

When naming variables in Python, there are some rules we must follow:

  • The variable name must start with a letter or an underscore (_).
  • The variable name can contain letters, numbers, and underscores.
  • Python distinguishes between uppercase and lowercase, so name and Name are different variables.
  • Reserved Python words cannot be used as variable names (for example: if, while, for, etc.).