How To Define Variables In Python

Python is a popular, versatile, and easy-to-learn programming language. One of its essential features is the ability to store and manipulate data using variables. In this tutorial, we will learn how to define variables in Python and handle them in your code.

Step 1: Understanding Variables in Python

A variable is a container that holds a value. It can be a number, a text string, a list, or other data type. In Python, variables do not require a specific data type declaration, which is one of the reasons many people find it more user-friendly than other programming languages.

Step 2: Assigning a Value to a Variable

To assign a value to a variable in Python, use the assignment operator (=). The variable name is written on the left side of the assignment operator, while the value to be stored is on the right side.

For example:

In this example, we have created the following variables:

  • age contains the value 25
  • name contains the value 'Alice'
  • colors contains a list of strings ['red', 'blue', 'green']

Step 3: Using Variables in Expressions

You can use variables in expressions, which are combinations of values, variables, and operators. When using an expression in Python, the interpreter evaluates the expression and produces a result.

For example:

In this case, the value of sum_of_x_and_y will be 30.

Step 4: Updating a Variable

You can update the value of a variable by assigning a new value to it. The old value will be overwritten and lost.

For example:

The value of x is now 15.

Step 5: Rules for Naming Variables

Variable names in Python should follow these rules:

  1. It must begin with a letter (a-z, A-Z) or underscore (_).
  2. It can only contain letters, digits (0-9), and underscores.
  3. It cannot be a Python reserved word (such as while, if, or class).

The above examples show valid variable names in Python.

Now let’s put together everything we’ve learned in one simple code block:


The sum of 5 and 10 is 15.

This code demonstrates variable assignment, updating, and using expressions in Python. The code block creates a message and prints it to the console, showing the sum of the numbers 5 and 10.


Defining variables in Python is straightforward and essential for carrying out various operations in your code. Variables allow you to store and manage data more efficiently, and understanding their usage is crucial for mastering Python programming. Make sure to follow the rules when naming variables, and don’t be afraid to practice and experiment with different data types in your code.