Variables in Python
Variables are nothing but memory locations to store values. This means that when a variable is created, a space is reserved in the memory. Like C, C++, Java, and other languages, Python doesn’t need an explicit declaration of variables.
Variable declaration looks like this in C:
whereas in Python, declaration happens automatically when you assign a value to a variable.
Declaring a variable involves equal sign ( = ), name, and value of the variable.
In the above example, letter = "Jack"
,
letter
is the name of the variable, that is, the operand to the left of the = sign is the name of the variable.Jack
is the value assigned to the variable, that is, the operand to the right of the = sign is the value assigned to the variable.=
operator is used to assigning the value to the variables.
Similarly number, decimal
are variables. Python also allows multiple assignments. You can assign a single value to multiple variables or multiple values to multiple variables in the same line.
Here a = b = c = 20
denotes that the value 20 is assigned to all three variables a,b and c; a, b, c = 1, 2, "Jack"
simply just means a = 1
, b = 2
and c = "Jack"
.
Python also allows re-declaration of variables, irrespective of value and data type.
Output:
Rules for creating variables in Python:
- A variable name must either start with a letter or an underscore ( _ ).
- A variable name cannot start with a number.
- A variable name can only contain alpha-numeric characters and underscores (A-Z, a-z, 0–9, and _ ) and no other special characters.
- Variable names are case-sensitive (number, Number, and NUMBER are three different variables).
- Reserved words or keywords (eg: print, def, while, etc.) cannot be used to name variables.
If my work has inspired or helped you out, I would love it if you could support me by buying me a coffee or a book.