Python - Variables

2 minute read

In Python, a variable is a named reference to a value that can be changed. Variables are used to store data in a program, such as numbers, strings, lists, and more. In this tutorial, we will cover the basics of variables in Python.

Variable Naming Rules

Before we dive into the examples, let’s first discuss the rules for naming variables in Python:

  1. Variable names must start with a letter or an underscore.
  2. Variable names can only contain letters, numbers, and underscores.
  3. Variable names are case-sensitive, so my_variable and My_Variable are two different variables.

It is also important to choose descriptive and meaningful names for your variables to make your code easier to understand and maintain.

Assigning Values to Variables

In Python, you can assign values to variables using the assignment operator (=). For example:

my_variable = 42
my_string = "Hello, World!"
my_list = [1, 2, 3]

In this example, we have assigned the integer '42' to the variable 'my_variable', the string "Hello, World!" to the variable 'my_string', and the list '[1, 2, 3]' to the variable 'my_list'.

Accessing Variable Values

Once you have assigned a value to a variable, you can access the value by simply referencing the variable. For example:

print(my_variable)
print(my_string)
print(my_list)

This will output:

42
Hello, World!
[1, 2, 3]

Changing Variable Values

In Python, you can change the value of a variable by assigning a new value to it. For example:

my_variable = 42
print(my_variable)  # Output: 42

my_variable = 100
print(my_variable)  # Output: 100

In this example, we have assigned the integer '42' to the variable 'my_variable', printed its value, assigned the integer '100' to the same variable, and printed its new value.

Multiple Assignments

In Python, you can assign multiple variables at the same time. For example:

x, y, z = 1, 2, 3
print(x, y, z)  # Output: 1 2 3

In this example, we have assigned the values '1', '2', and '3' to the variables 'x', 'y', and 'z', respectively.

Conclusion

In conclusion, variables are an essential part of any programming language, and Python is no exception. By following the naming rules and using descriptive names, you can make your code more readable and easier to maintain. By assigning and changing values to variables, you can store and manipulate data in your programs. Finally, by using multiple assignments, you can assign multiple variables at the same time, which can make your code more concise and readable.

Updated: