Python Variables

Python Variables

A beginner's guide to 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 explicit declaration of variables.

Variables declaration looks like this in C:

char letter = "Python";
int number = 2;
float decimal = 1.50;

whereas in Python, declaration happens automatically when you assign a value to a variable.

letter = "Jack"         #string
number = 2              #integer
decimal = 1.50          #float

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 assign 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.

a = b = c = 20     
a, b, c = 1, 2, "Jack"

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.

#variable declare
number = 10
# display variable
print("Before: ", number)
# re-declare the variable
number = "Hey Python"
print("After:", number)

Output:

Before: 10
After: Hey Python

Rules for creating variables in Python:

  1. A variable name must either start with a letter or an underscore ( _ ).
  2. A variable name cannot start with a number.
  3. A variable name can only contain alpha-numeric characters and underscores (A-Z, a-z, 0-9, and _ ) and no other special characters.
  4. Variable names are case-sensitive (number, Number and NUMBER are three different variables).
  5. Reserved words or keywords (eg: print, def, while etc.) cannot be used to name variables.

That’s all folks. I would really appreciate it if you’ve made it till the end. If you enjoyed this, I’d love it if you could hit the clap button 👏. You can also find me on LinkedIn and Twitter .