In this tutorial, We will learn about Python variables and constants.
In Python, a variable is a name that refers to a value. Variables are used to store data in memory and can be used later in the program. To create a variable in Python, we use the assignment operator (=).
Creating a Variable
To create a variable in Python, we simply assign a value to a variable name.
For example, to create a variable called “age” and assign it the value 25, we can write:
age = 25
Using Variables
Once a variable is created, we can use it in our program by referring to its name. For example, we can use the print() function to print the value of a variable to the screen:
age = 25
print(age)
The output of the above code will be:
25
Data Types
Python is a dynamically-typed language. It means we do not need to specify the data type of a variable while creating it. Python automatically assigns a data type to the variable based on the value that is assigned to it.
For example, if we assign a string value to a variable, Python will assign the string data type to the variable. Similarly, if we assign an integer value to a variable, Python will assign the integer data type to the variable.
Changing the Value of a Variable
We can also change the value of a variable later in the program by assigning a new value to it.
For example:
age = 25 print(age) age = 30 print(age)
The output of the above code will be:
25
30
Naming Conventions
In Python, there are some naming rules and conventions that we should follow while naming a variable. A variable name can contain letters, numbers, and underscores. It cannot start with a number.
Variable names are case-sensitive. It means that “age” and “Age” are two different variable names. We should also choose meaningful variable names that describe the purpose of the variable.
Constants
A constant is a value that does not change during the execution of the program. In Python, we can create a constant by using all capital letters for the variable name. For example:
PI = 3.14159
In the above code, “PI” is a constant that holds the value of pi. We can also use constants in place of hard-coded values in our program to make the program more readable and maintainable.