Variables in Python

Introduction

Having the concept of variables while learning a programming language is very important. Here we will cover the concept of variables in python.

Variables are used to store different types of values. The good thing is in python, you don't have to specify the type of a variable when declaring. This is the biggest advantage of python. Regardless of the data type you store, the variable will automatically be of that type.

Types of data type in python

These are familiar data types in python - string, int, float, list, tuple, dict, bool, etc. String, bool, int, and float are common data types that you can find in other programming languages too but in python, you will find two special data types - sequence type (list, tuple, set), and mapping data type (Python dictionary or dict).

Find the type of a variable

You can find out the type of a variable by using the type() method. See the example below.


# String Variable
name = "It's me Rakshit"
# Integer variable
age = 5
print(type(name))
print(type(age))

Output

<class 'str'>
<class 'int'>

Assign a Single Value to Multiple Variables

Here, it's normal to assign a single value to multiple variables in a single line.


# Assign a single value to multiple variables
a=b=c=5
print("Sum = ", a+b+c)

Output

Sum =  15

Typecast a variable

You can specify the type of a variable when declaring it.


v1 = int(8)
v2 = str(8)
v3 = float(8)

print(v1)
print(type(v2))
print(v3)

Output

8
<class 'str'>
8.0

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post