Skip to content

Variable

Variable:
It is a memory location referring with an identifier that is used to store some type of data.

How to create variable?
In python, we can create a variable directly with the help of assignment statement. you can also use assignment statement to change the existing value of a variable too.

Difference between python and other languages in variable creation:

In C/C++/Java we have to write declaration statement to create variable, then use assignment statement to store value.

Example: (C/C++/java)
int x; //declaration statement
x=12; //assignment statement

🐍
filename.py
#Example
x=12  #creation with Assignment

if the above statement is found first time in the code, python will create a new variable and store value into it. If it is already created before, the same statement will change its value.

🐍
filename.py
#Example:
x=12 #creates new variable and stores value
print(x)
x=24 #changes existing value of variable
print(x)

What is assignment statement?
The statement that contains assignment operator is called as ‘Assignment Statement’

The equal to (=) symbol is called as Assignment Operator in python.

 

4 valid syntax or general format of assignment statement:
var=val
var=var
var=expr
var=func()

🐍
filename.py
#Example:
num=10

How to display the value of a variable?
print() function can be used to print the value of a variable too.

🐍
filename.py
#example
num=10
print(num)
print(num+5)
print("Num value is:",num)
print(num,"x","5=",num*5)
🐍
filename.py
#Example Program showing all syntaxes of assignment statement
a=10 #var=val
b=a  #var=var
c=a+b  #var=expr
d=input()  #var=fun()
print("a=",a)
print("b=",b)
print("c=",c)
print("d=",d)

Multiple value assignment:
a list of variables can be created with single assignment statement in python.

🐍
filename.py
#Example:
a,b,c=1,2,3
a=b=c=2

But assigning single value into multiple variables is not direct method

🐍
filename.py
#Example:
a,b,c=2  #gives error

Initialisation Vs Assignment
A variable can be assigned with different values during program execution. First value assignment is called as ‘initialization’.

🐍
filename.py
#Example:
a=12  #variable creation and initialisation
print(a)
a=24 #Assignment
print(b) #Assignment
a=36
print(c) #Assignment

Practice Questions:
1. Write python code to create a variable with identifier ‘num’, initialize it with value 25 and display its value

2. write python code to store your name into a variable and display welcome message like “Hi YourName, Welcome”

3. Write python code to create two variables ‘first’ and ‘second’, initialise them with desired values. Add the values in the variables and store into new variable ‘res’. Display the result.

4. Write python code to create two variables ‘length’ and ‘width’. Calculate area of rectangle and print result.