Variables in Python
In Python, variables are memory spaces associated with a name, where you can store a value, data, or information.
What are variables? They are a fundamental element of programming. A variable is a memory space where information can be written and/or read.
How to use variables in Python
Each variable is associated with a unique name chosen by the programmer.
Who decides the variable's name?
The developer decides the variable's name. Typically, it is a mnemonic name related to the information it contains.
Example: Using the variable "name" to store my name.
Each variable is assigned a specific piece of data.
In Python, you don't need to declare variables in advance; you can simply initialize them by assigning them a value.
In this aspect, Python is similar to PHP and differs from C language.
Note: Although you don't need to declare variables, you cannot use uninitialized variables. If you do, the interpreter will throw an error during execution.
Assigning a value to a variable
To assign a value to a variable, type the variable name followed by the equal sign (=) and the information you want to assign to it.
name=information
Example
In the following code, I create the variable "name" to store the alphanumeric value "Andrea".
name="Andrea"
This is a practical example of assigning an alphanumeric value.
Thanks to automatic typing, the Python interpreter initializes the variable "name" as an alphanumeric variable.
Note: The information is enclosed in quotes because it is an alphanumeric value.
Next, I create a variable "year" to store the birth year.
year=1968
In this case, quotes are not used because it is a numeric value.
The interpreter initializes the variable "year" as a numeric variable.
How to display a variable
To display the content of a variable, use the print command, placing the variable name in parentheses.
print(variablename)
A practical example
I want to display the value stored in the variable "name" on the screen.
So, I type the following instruction:
print(name)
The Python interpreter executes the print instruction, reads the value contained in the "name" variable, and prints it on the screen.
Andrea
Types of Variables in Python
Python has several types of variables.
- Integer variables
- Float variables (decimal numbers)
- String variables (alphanumeric)
- Boolean variables (true or false)
In addition to these types, there are also high-level data types such as lists, tuples, dictionaries, and sets.
And so on.