Skip to main content
Taught by Tech Leads

Master pipelines, cloud & AI to become an operational Data Engineer.

DataScientist.fr
Image de Understanding Variables - Practical Tutorial in Python
Python

Understanding Variables - Practical Tutorial in Python

Photo de Romain DE LA SOUCHÈRE

Tech Lead, CTO AXI Technologies

Published on 8 janvier 2025 · 10 min of reading

Introduction to variables in Python

Variables are one of the fundamental concepts in programming, and Python is no exception. Understanding how to declare, use, and manage variables is essential for writing efficient and readable code. In this section, we will cover the basics of variables in Python to provide you with the knowledge necessary to start using them in your own programs.

What is a variable?

A variable is a container that allows you to store data. In Python, you can store different types of data in variables, such as numbers, strings, lists, and more. One of the interesting features of Python is its dynamic typing, which means you do not need to explicitly declare the data type of a variable.

Why use variables?

Variables are crucial because they allow you to reuse values without constantly recreating them. They also make the code more readable and easier to maintain. For example:
python
In this example, the value 10 is stored in the variable number, which can then be used multiple times in the program.
With this introduction, we will explore in more detail the declaration and initialization of variables.

Declaring and initializing variables

In Python, declaring and initializing variables are simple and straightforward processes. You do not need to use specific keywords to declare a variable, nor do you need to specify its data type at the time of declaration.

Declaring variables

To declare a variable, simply choose an appropriate variable name and assign it a value. For example:
python

Initializing variables

Initializing a variable means assigning it an initial value. You can initialize a variable using the = operator. Here are some examples:
python

Reassigning variables

In Python, you can reassign a new value to a variable at any time. This means that the data type of the variable can change dynamically:
python
This flexibility allows for simpler code and makes Python programs very versatile. In the next section, we will explore the data types available in Python and how dynamic typing works.

Data types and dynamic typing

Python is known for its dynamic typing and its wide variety of built-in data types. This allows developers to easily manipulate different types of data without worrying about explicitly declaring their types.

Common data types

Here are some common data types in Python:
  • Integers (int): Represent integer numbers. Examples: 0, -5, 42.
  • Floats (float): Represent floating-point numbers. Examples: 3.14, -2.5.
  • Strings (str): Represent sequences of characters. Examples: "Hello", 'Python'.
  • Lists (list): Represent ordered collections of values. Examples: [1, 2, 3], ["a", "b", "c"].
  • Dictionaries (dict): Represent collections of key-value pairs. Examples: "name": "Alice", "age": 25.

Dynamic typing

Dynamic typing means that the data type of a variable is determined at runtime and can change at any time. For example:
python
This feature provides great flexibility but also requires good management to avoid unexpected type errors. In the following sections, we will discuss the scope and lifetime of variables, as well as best practices for naming variables.

Scope and lifetime of variables

The scope and lifetime of variables are important concepts to understand for writing effective and error-free Python code.

Scope of variables

The scope of a variable refers to the region of the program where it is accessible. In Python, there are mainly two types of scope:
  • Local scope: Variables defined inside a function are local to that function and are not accessible outside of it.
  • Global scope: Variables defined outside of any functions are global and can be accessed from anywhere in the program.
Example:
python

Lifetime of variables

The lifetime of a variable is the time during which it exists in memory. Global variables exist until the end of the program, while local variables exist only during the execution of their function.
python
Understanding the scope and lifetime of variables is crucial for avoiding errors and ensuring clean and functional code. In the next section, we will explore best practices for naming variables.

Best practices for naming variables

Choosing variable names is crucial for code readability and maintainability. Clear and meaningful variable names help make it easier to understand what the code does, both for you and for other developers.

Use descriptive names

Avoid using overly short or non-descriptive variable names such as x, y, or z. Prefer names that clearly indicate the intention of the variable:
python

Follow naming conventions

In Python, the PEP 8 convention recommends using snake_case for naming variables. This means using lowercase letters and underscores to separate words:
python

Avoid reserved words

Python has reserved keywords that cannot be used as variable names. For example, class, def, and return are reserved words. Using these words as variable names will lead to errors:
python
python

Be consistent

Consistency in variable naming throughout the code is essential. For example, if you start using snake_case, continue to use it throughout your code.
Adopting these best practices for naming your variables will help make your code more readable and easier to maintain. In the next section, we will discuss common errors related to variables and how to avoid them.

Common errors and how to avoid them

Even experienced developers can make common mistakes when manipulating variables in Python. Here are some of the most frequent errors and tips on how to avoid them.

Using uninitialized variables

Always ensure to initialize your variables before using them. Accessing an uninitialized variable will result in an error.
python

Variable name conflicts

Avoid using the same name for local and global variables to prevent conflicts and unexpected behaviors.
python

Forgetting variable scope

Be aware of the scope of variables to avoid errors where a local variable is used instead of a global variable.
python

Poor management of data types

Python's dynamic typing can lead to errors if you are not careful with the data types of variables.
python
By following these tips, you can avoid these common errors and write more robust and reliable Python code. In the next section, we will examine practical examples and case studies to illustrate these concepts.

Practical examples and case studies

To illustrate the concepts discussed, let's look at some practical examples and case studies that show how to effectively manipulate variables in Python.

Inventory management example

Suppose you are managing a product inventory in a store. You can use variables to store information about products and their quantities:
python

Calculating average grades

Imagine you want to calculate the average grades of students:
python

Case study: User management

Consider a simple script for managing users in an application:
python
These examples demonstrate how to use variables to solve practical problems. By applying the concepts and best practices discussed, you will be able to write efficient and readable Python code.

Want to go further?

This topic is part of our Become a Data Analyst course. Browse the full programme, or get it by email.

Share with

Photo de Romain DE LA SOUCHÈRE

Romain DE LA SOUCHÈRE

Tech Lead, CTO AXI Technologies

Expert Data Engineering et Cloud, Romain affiche plus de 11 ans d'expérience, dont plusieurs années comme Lead Developer sur des solutions Smart Building haute performance. Il y a conçu et mis en production des moteurs de traitement capables d'absorber des centaines de milliers de données de capteurs par minute, ainsi que des bases clusterisées gérant plus de 10 millions de données dynamiques. Certifié Microsoft Azure DevOps Engineer Expert, il maîtrise aussi bien le développement back-end (Python, C#) que le DevOps (Docker, Kubernetes, Terraform) et les agents LLM. Formateur en Python, cloud, DevOps et IA générative appliquée, il forme avec une obsession : Amener chaque apprenant à concevoir et déployer des architectures réellement scalables en production.

» Learn More

Associated trainings

All our trainings
Image de la formation Become a Data Analyst
Become a Data Analyst
6 months
Intermediate
Guarantee

Associated articles

See all our articles
Image de l'article Lists - Practical Tutorial in Python

janvier 8, 2025

Lists - Practical Tutorial in Python

Reading time: 10 min

Image de l'article Python Dictionaries Guide - Interactive Tutorial

janvier 8, 2025

Python Dictionaries Guide - Interactive Tutorial

Reading time: 10 min

Image de l'article File Handling in Python - Complete Tutorial

janvier 8, 2025

File Handling in Python - Complete Tutorial

Reading time: 10 min