learnai2k@gmail.com

Variables

Section 1: What Is a Variable?

A variable is a name that is used to store a value in your program memory.

In simple words, you can think a variable like a box with a label. The box contains the value and its label is name of a variable.



Here, three variables -  x, name, and is_ready -  are created, which contain the values 10, 'Hitesh', and True, respectively.

You don’t need to declare the data type of a variable. You don’t need to declare it in Python.

You can change the value (of a variable) any time as shown below:



Section 2: Creating and Assigning Variables

In Python, you can create a variable using the = sign.



Multiple assignments:

You can assign several variables at once in a single line. This helps to make code short and clean.


 
It means, x, y, and z get values 10,20 and 30 respectively.

In next line, three variables (name, age, and city) get the same value "New Delhi”. This is also known as chained assignment

Augmented assignment:

In this, you update the value of a variable using its own value in a shorter way.

In this type assignment, we use a shortcut operator like +=, -=, *=, or /=.

Example:

•    x += 5 means add 5 to x
•    x -= 2 means subtract 2 from x
•    x *= 3 means multiply x by 3
•    x /= 2 means divide x by 2

Example code:


 
In simple words,
count += 20 means, take the current value of count (10), add 20 to it, and store the new value (30) back into count variable.

Section 3: Variable Naming Rules & Conventions

In Python, when you create a variable then one needs to follow some rules to avoid error at run time.

Rule No 01:

You can not start a variable name with a number as shown below:

Example 01:


 
This is an incorrect one and error is also shown for above declaration.

Example 02:


 
This is correct one.

Rule No 02:

A variable name can only have:

•    Lowercase letters: a–z
•    Uppercase letters: A–Z
•    Digits: 0–9
•    Underscore: _

Example:


 
Rule No 03:

Python treats uppercase and lowercase as different.

Example: Count and count are two different variables in Python language.

Rule No 04:

In Python, there are some reserved words like class, if, for, while, etc.

These reserved words are called keywords and you cannot use them as variable names.

Section 04: Variable Types and Mutability

In Python variables, you can store any type of data like:


 
Mutable vs Immutable

Mutability simply means whether a value can be changed after creation or not.


 
a)    Immutable Example


 
Here, you can see that changing y value does not affect x because numbers are immutable.

b)    Mutable Example



If we print both lists a and b, the result is [10, 20, 30] because lists are mutable.

Both a and b are of list type and share the same memory location, so when one changes, the other also changes.