In programming languages like C/C++, every time a variable is declared simultaneously a memory would be allocated this would allocation would completely depend on the variable type. Therefore, the programmers must specify the variable type while creating a variable. But luckily in Python, you don’t have to do that. Python doesn’t have a variable type declaration. Like pointers in C, variables in Python don’t store values legitimately; they work with references highlighting objects in memory.
A variable is more likely a *container* to store the values. Now the values to be stored depends on the programmer whether to use integer, float, string or etc.
*A Variable is like a box in the computer’s memory where you can store a single value. — Al Sweigart*
Unlike in other programming languages, in Python, you need not declare any variables or initialize them. Please read this.
The general syntax to create a variable in Python is as shown below:
variable_name = value
The variable_name
in Python can be short as sweet as a, b, x, y, ...
or can be very informative such as age, height, name, student_name, covid, ...
*Although it is recommended keeping a very descriptive variable name to improve the readability.*
All set and done, there are some rules that you need to follow while naming a variable:
A variable name must start with a *letter* or the *underscore character*
A variable name cannot start with a *number*
A variable name can only contain *alpha-numeric characters* and *underscores. For example, anything like this is valid: A-z, 0–9, and _*
Variable names are *case-sensitive* *(height, Height, and HEIGHT* are three different variables names)
Below given is an example to properly initialize a value to a variable:
# This is a valid and good way to assign a value to a variable
# For example you might want to assign values to variables to calculate the area of a circle
pi = 3.142 # I could have also used "math" library (math.pi)
radius = 5 # Interger value for radius
area_of_circle = 0 # Used to store the value of area of circle
area_of_circle = pi * (radius) ** 2 # Area = (PI * R^2)
print("The area of the circle based on the given data is: ", area_of_circle)
The area of the circle based on the given data is: 78.55
I# believe just by seeing a picture or an image, the concepts can be understood more quickly. Below is the pictorial representation of a variable and it being stored in the memory.