WHAT IS THE VARIABLE IN PYTHON

Variable in Python

Python variables are the reserved memory locations used to store values with in a Python Program.

A variable in Python is created the moment you first assign a value to it.

Variables in Python do not need to be declared with any particular type, and can even change type after they have been set.

If you want to specify the data type of a variable in Python, this can be done with casting.

Execute the following code in python,

x=1 # x is of type Int
y=2.5 # y is of type float
z=True # z is of type boolean
print(x,”,”,y,”,”,z) # print 1 , 2.5 , True
x=’MrBeans’ # x is now of type Str
print(x) # print MrBeans
x=str(5) # This is known as casting, x will be of type str
y=int(5) # y will be of type int
z=float(5) # z will be of type float
print(x,”,”,y,”,”,z) # print 5 , 5 , 5.0
print(type(x),type(y)) # print type of variable, output:
x,y,z=1,2.5,True # Assign values to multiple variables
print(x,”,”,y,”,”,z) # print: 1 , 2.5 , True
w=[x,y,z] # Collection values is called tuple
print(w) # output: [1, 2.5, True]
x,y,z=w # extracting the values into variables is called unpacking
print(x,”,”,y,”,”,z) # output: 1 , 2.5 , True
x=y=z=5 # Assign one value to multiple variables, output: 5 , 5 , 5
print(x,”,”,y,”,”,z) # output: 5 , 5 , 5

OUTPUT of the above code-

1 , 2.5 , True

MrBeans

5 , 5 , 5.0

<class ‘str’> <class ‘int’>

1 , 2.5 , True

[1, 2.5, True]

1 , 2.5 , True

5 , 5 , 5

Global variables are explained in next post.


Leave a Reply

Your email address will not be published. Required fields are marked *