0% found this document useful (0 votes)
16 views85 pages

Python Variables and Data Types

Uploaded by

Aamna Raza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
16 views85 pages

Python Variables and Data Types

Uploaded by

Aamna Raza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 85

PYTHON VARIABLES AND DATA TYPES

Python Variables
A variable is a named location used to store data in the memory. It is helpful to think of
variables as a container that holds data that can be changed later in the program. For
example,

number = 10

Here, we have created a variable named number. We have assigned the value 10 to the
variable.
You can think of variables as a bag to store books in it and that book can be
replaced at any time.

number = 10
number = 1.1

Initially, the value of number was 10. Later, it was changed to 1.1.
Assigning values to Variables in Python
As you can see from the above example, you can use the assignment operator = to
assign a value to a variable.

Example 1: Declaring and assigning value to a variable


website = "apple.com"
print(website)

Output

apple.com

In the above program, we assigned a value apple.com to the variable website. Then, we
printed out the value assigned to website i.e. apple.com
Note: Python is a type-inferred language, so you don't have to explicitly define the
variable type. It automatically knows that apple.com is a string and declares the
website variable as a string.
Example 2: Changing the value of a variable
website = "apple.com"
print(website)

# assigning a new value to website


website = “ABCD.com"

print(website)

Output

apple.com
ABCD.com
In the above program, we have assigned apple.com to the website variable initially.
Then, the value is changed to ABCD.com.
Example 3: Assigning multiple values to multiple variables
a, b, c = 5, 3.2, "Hello"

print (a)
print (b)
print (c)
If we want to assign the same value to multiple variables at once, we can do this
as:

x = y = z = "same"

print (x)
print (y)
print (z)
The second program assigns the same string to all the three variables x, y and z.
Constants
A constant is a type of variable whose value cannot be changed.
It is helpful to think ofconstants as containers that hold information which cannot be
changed later.
You can think of constants as a bag to store some books which cannot be replaced once
placed inside the bag.
Assigning value to constant in Python
In Python, constants are usually declared and assigned in a module. Here, the module is a new
file containing variables, functions, etc. which is imported to the main file. Inside the module,
constants are written in all capital letters and underscores separating the words.
Example 3: Declaring and assigning value to a constant
Create a constant.py:
PI = 3.14
GRAVITY = 9.8
Create a main.py:
import constant
print(constant.PI)
print(constant.GRAVITY)
Output
3.14
9.8
In the above program, we create a constant.py module file. Then, we assign the constant value
to PI and GRAVITY. After that, we create a main.py file and import the constant module. Finally,
we print the constant value.
Note: In reality, we don't use constants in Python. Naming them in all capital letters
is a convention to separate them from variables, however, it does not actually
prevent reassignment.
Rules and Naming Convention for Variables and constants
• Constant and variable names should have a combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9) or an underscore (_). For example:
snake_case
MACRO_CASE
camelCase
CapWords
• Create a name that makes sense. For example, vowel makes more sense than v.
• If you want to create a variable name having two words, use underscore to separate them.
For example:
my_name
current_salary
• Use capital letters possible to declare a constant. For example:
PI
G
MASS
SPEED_OF_LIGHT
TEMP
• Never use special symbols like !, @, #, $, %, etc.
• Don't start a variable name with a digit.
Scope of Variable
Scope of a variable in python is not different than other programming languages. Here also
variable follows same rule i.e., if a variable is defined inside a function, then its scope is inside
the function only and variables which are declared outside of any function block globally do
possess a global scope.

Example 1 : Global Scope


value1 = 20 #Globally Declared
def ChangeValue():
print(value1) #Will use Global Value
ChangeValue() #Calling a function
print(value1) #Printing its value again
Output:
In above program we declared a variable globally and then we wrote a function inside that
we printed the value of variable. After the function we again printed the value of variable.
The variable was declared globally so we can use it inside function.
Example 2 : Local Scope

value1 = 20 #Globally Declared


def ChangeValue():
value1 = 30 # Local scope declaration
print(value1) #Will use localScope

ChangeValue() #Calling a function


print(value1) #Printing its value again
Output:

In above program we declared variable with same name inside a function. If you remember
how we manipulated the value of variable but here it didn’t work because Python
considered it as declaration inside function scope i.e., local scope.
Data Types in Python

Data type classifies the variable. It tells what kind of values are acceptable
for a particular variable , what mathematical, relational or logical operations
we can perform without any errors.
Python provides some basic data types as well some advance and very useful
data types. Everything in Python is an object, variables are instance whereas
data types are classes.
Data Types
Number
Number can be an Integer, Float and Complex in Python. They are defined as int, float
and complex class in Python.

type() :This function can be used to know which class a variable or a value belongs.

isinstance() :This function checks if an object belongs to a particular class.


Example

b=5
print(b, "is of type", type(b))

b = 22.05
print(b, "is of type", type(b))

b = 1+2j
print(b, "is complex number?", isinstance(1+2j,complex))

Output
(5, 'is of type', <type 'int'>)
(22.05, 'is of type', <type 'float'>)
((1+2j), 'is complex number?', True)
Integers in Python are same as any other programming language. The only limitation is
the memory available. Floating numbers are accurate upto 15 decimal places. Decimal
numbers are separated by decimal points. 2 is an integer and 2.3 is float. Complex
numbers are written as (x + 2j) where one is real and another one is imaginary part. Here
‘x’ is real part and ‘2j’ is our imaginary part.

Example
>>> integer = 123456787465454813165
>>> integer
123456787465454813165
>>> b = 0.1215487465415486
>>> b
0.1215487465415486
>>> c = 1 + 2j
>>> c
(1+2j)
Booleans
The boolean data type is either True or False.
In Python, boolean variables are defined by the True and False keywords.

>>> a = True
>>> type(a)
<class 'bool'>

>>> b = False
>>> type(b)
<class 'bool'>

The output <class 'bool'> indicates the variable is a boolean data type.
Note the keywords True and False must have an Upper Case first letter. Using a lowercase
true returns an error.
List
List is a data type in Python which you can relate to arrays in some other programming
languages. But arrays are homogeneous means same type of variable can be stored
whereas in Python list, you can store any type of item in it. Declaring a Python list is very
straight forward, you just need to write all values comma separated inside square
brackets.
Example 1
Suppose you want to store heights of a group then you can store them in list as below :

#Storing heights of persons in Height


Height = [1.73 , 1.68, 1.76 ]
List items can be accessed by indices which starts from zero 0 for the first element and
then continues incrementally.

Example 2
We will access our height list created earlier

print(Height[0])

#you want to store height and name both then


Height = [“rahul”, 1.75, “person”, 1.63, “person2”, 1.96]
Nested List
You can even store list inside a list i.e. nested list.

Example 3: suppose we store heights of person as an individual sublist in list.

Person_heights = [[“person1”, 1.75] , [“person2”, 1.68]]


Lists are mutable as we seen they can be accessed by index and we can also manipulate
them by assignment operator.

Example 4
Values = [ 1, 2, 3, 4,5, 6]
Values[0] = 9
print(Values)
Output

[9, 2, 3, 4, 5, 6]
We can use slicing operator [ ] to get a subset list or a particular item. Slicing a very
useful feature in Python

The : symbol is used for more than one purpose in Python.


As slice operator with sequence −
The : operator slices a part from a sequence object such as list, tuple or string. It
takes two arguments. First is the index of start of slice and second is index of end
of slice. Both operands are optional. If first operand is omitted, it is 0 by default. If
second is omitted, it is set to end of sequence.
Example :
b= [5,10,15,20,25]
#printing upto 3 indices
print(b[:3])
#reversing a list with use of slicing
print(b[::-1])
#printing from indices 1 to 3
print(b[1:3])
Output
[5, 10, 15]
[25, 20, 15, 10, 5]
[10, 15]
Tuples
Tuples are ordered sequence. Tuples are written as comma-separated elements within
parentheses. Tuples once created can’t be modified that makes them faster as
compared to list.

Example:
#Here we are declaring a tuple named score:
Score = (20,30,55,68,12,32)

#All the different types in Python - String, Integer, Float can all be contained in tuple.
Tuple1 = (‘person’, 20, 12.5)
Each element of tuple can be accessed via index same as lists.

Index Value
0 person
1 20
2 12.5
Accessing Tuples

# accessing 0 index
print(Tuple1[0])

Output
person

We accessed same element first with zero index .


Mutable List vs Immutable Tuples
List has mutable nature i.e., list can be changed or modified after its creation
according to needs whereas tuple has immutable nature i.e., tuple can’t be
changed or modified after its creation.
Example 2.1: Modify an item List vs. Tuple
list_num = [1,2,3,4]
tup_num = (1,2,3,4)
list_num[2] = 5
print(list_num)
tup_num[2] = 5
Output:
[1,2,5,4]
Traceback (most recent call last):
File "python", line 6, in <module>
TypeError: 'tuple' object does not support item assignment
Strings
Python string is a sequence of Unicode characters. Strings are represented as characters
between single quote or double quote. Multiline strings are denoted by triple quotes ‘’’,
or “””

Declaring a String
str_var = ‘STRING’
str2 = “i am string”

Note: Python does not have a character data type, a single character is simply a string
with a length of 1.
Strings also support the slicing operator after all its sequence of characters.

Example

R = "Hello World"
print("R[4] =", R[4]);
print("R[1:3]=",R[1:3])
Output
('R[4] =', 'o')
('R[1:3]=', 'el')
String Operators
String operators represent the different types of operations that can be employed on the
string type of variables in the program. Python allows several string operators that can be
applied on the python string are as below:
• Assignment operator: “=”
• Concatenate operator: “+”
• String repetition operator: “*”
• String slicing operator: “[]”
• String comparison operator: “==” & “!=”
• Membership operator: “in” & “not in”
• Escape sequence operator: “\”
• String formatting operator: “%” & “{}”
Example #1 – Assignment Operator “=”
Python string can be assigned to any variable with an assignment operator “= “. Python
string can be defined with either single quotes [‘ ’], double quotes[“ ”] or triple quotes [‘’’
‘’’]. var_name = “string” assigns “string” to variable var_name.

Code:

string1 = "hello"
string2 = 'hello'
string3 = '''hello'''
Output:
print(string1)
print(string2)
print(string3)
Example #2 – Concatenate Operator “+”
Two strings can be concatenated or join using “+” operator in python as
explained in below example code:

Code:
string1 = "hello"
string2 = "world "
string_combined = string1+string2
print(string_combined)

Output:

hello world
Example #3 – String Repetition Operator “*”
The same string can be repeated in python by n times using string*n as explained in the
below example.

Code:

string1 = "helloworld "


print(string1*2)
print(string1*3)
print(string1*4)
print(string1*5)

Output:
Example #4 – String slicing operator “[]”
Characters from a specific index of the string can be accessed with the string[index] operator.
The index is interpreted as a positive index starting from 0 from the left side and negative
index starting from -1 from the right side.
•string[a]: Returns a character from a positive index a of the string from the left
side as displayed in the index graph above.
•string[-a]: Returns a character from a negative index a of the string from the right
side as displayed in the index graph above.
•string[a:b]: Returns characters from positive index a to positive index b of the as
displayed in index graph above.
•string[a:-b]: Returns characters from positive index a to the negative index b of the
string as displayed in the index graph above.
•string[a:]: Returns characters from positive index a to the end of the string.
•string[:b] Returns characters from the start of the string to the positive index b.
•string[-a:]: Returns characters from negative index a to the end of the string.
•string[:-b]: Returns characters from the start of the string to the negative index b.
•string[::-1]: Returns a string with reverse order.
Code:
Output:

string1 = "helloworld"
print(string1[1])
print(string1[-3])
print(string1[1:5])
print(string1[1:-3])
print(string1[2:])
print(string1[:5])
print(string1[:-2])
print(string1[-2:])
print(string1[::-1])
Example #5 – String Comparison Operator “==” & “!=”
String comparison operator in python is used to compare two strings.
•“==” operator returns Boolean True if two strings are the same and return
Boolean False if two strings are not the same.

•“!=” operator returns Boolean True if two strings are not the same and return
Boolean False if two strings are the same.
These operators are mainly used along with if condition to compare two strings
where the decision is to be taken based on string comparison.
Code:

string1 = "hello"
string2 = "hello, world"
string3 = "hello, world"
string4 = "world"
print(string1==string4)
print(string2==string3)
print(string1!=string4)
print(string2!=string3)

Output:
Example #6 – Membership Operator “in” & “not in”
Membership operator is used to searching whether the specific character is
part/member of a given input python string
•“a” in string: Returns boolean True if “a” is in the string and returns False if
“a” is not in the string.

•“a” not in string: Returns boolean True if “a” is not in the string and returns
False if “a” is in the string.
A membership operator is also useful to find whether specific substring is part
of a given string.
Code:

string1 = "helloworld"
print("w" in string1)
print("W" in string1)
print("t" in string1)
print("t" not in string1)
print("hello" in string1)
print("Hello" in string1)
print("hello" not in string1)

Output:
Example #7 – Escape Sequence Operator “\”
To insert a non-allowed character in the given input string, an escape character is used. An
escape character is “\” or “backslash” operator followed by a non-allowed character. An
example of a non-allowed character in python string is inserting double quotes in the string
surrounded by double-quotes.

1. Example of non-allowed double quotes in python string:

Code:

string = "Hello world I am from "India""


print(string)

Output:
2. Example of non-allowed double quotes with escape sequence
operator:

Code:

string = "Hello world I am from \"India\""


print(string)

Output:
Example #8 – String Formatting Operator “%”
String formatting operator is used to format a string as per requirement. Toinsert
another type of variable along with string, the “%” operator is used along with
python string. “%” is prefixed to another character which indicates the typeof the
value which we want to insert along with python string. Please refer below table
for some of the commonly used different string formatting specifiers:
Code:

name = "india"
age = 19
marks = 20.56
string1 = 'Hey %s' % (name)
print(string1)
string2 = 'my age is %d' % (age)
print(string2)
string3= 'Hey %s, my age is %d' % (name, age)
print(string3)
string3= 'Hey %s, my subject mark is %f' % (name, marks)
print(string3)

Output:
Set
Sets are type of collections like list and tuples which means you can input
different Python types. Sets are unordered whereas list and tuples are ordered
collections. Sets don’t have any record for the element position they only
contain unique elements.
• A set is a collection which is both unordered and unindexed and
unchangeable.
• Unordered means that the items in a set do not have a defined order.
• Set items can appear in a different order every time you use them, and
cannot be referred to by index or key.
• Sets are unordered, so you cannot be sure in which order the items will
appear.
Creating a set
You can create a set with curly braces and in between the elements you want to put.

Example
Set1 = { 1, 2, 1, 3, 4, 5 }
print(Set1)
You can see that we have kept a duplicate element inside set while declaring but when
the actual set is created this element will be removed and you will get only unique
elements.

Output
set([1, 2, 3, 4, 5])
# Different types of sets in Python
# set of integers
my_set = {1, 2, 3}
print(my_set)

# set of mixed datatypes


my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)

Output

{1, 2, 3}
{1.0, (1, 2, 3), 'Hello'}
# set cannot have duplicates
# Output: {1, 2, 3, 4}
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)

# we can make set from a list


# Output: {1, 2, 3}
my_set = set([1, 2, 3, 2]) Output
print(my_set)
{1, 2, 3, 4}
# set cannot have mutable items {1, 2, 3}
# here [3, 4] is a mutable list Traceback (most recent call last):
# this will cause an error. File "<string>", line 15, in <module>
my_set = {1, 2, [3, 4]}
my_set = {1, 2, [3, 4]} TypeError: unhashable type: 'list'
Empty curly braces {} will make an empty dictionary in Python. To make a set without
any elements, we use the set() function without any argument.

# Distinguish set and dictionary while creating empty set

# initialize a with {}
a = {}

# check data type of a


print(type(a))

# initialize a with set() Output


a = set()
# check data type of a <class 'dict'>
print(type(a)) <class 'set'>
Modifying a set in Python
Sets are mutable. However, since they are unordered, indexing has no meaning.

We cannot access or change an element of a set using indexing or slicing. Set data type
does not support it.

We can add a single element using the add() method, and multiple elements using the
update() method. The update() method can take tuples, lists, strings or other sets as its
argument. In all cases, duplicates are avoided.
# initialize my_set
my_set = {1, 3}
print(my_set)
# my_set[0]
# if you uncomment the above line
# you will get an error
# TypeError: 'set' object does not support indexing
# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set) Output

# add multiple elements {1, 3}


# Output: {1, 2, 3, 4} {1, 2, 3}
my_set.update([2, 3, 4]) {1, 2, 3, 4}
print(my_set)
Removing elements from a set

A particular item can be removed from a set using the methods discard() and remove().

The only difference between the two is that the discard() function leaves a set unchanged if
the element is not present in the set. On the other hand, the remove() function will raise an
error in such a condition (if element is not present in the set).

The following example will illustrate this.


# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4) Output
print(my_set)
# remove an element {1, 3, 4, 5, 6}
# Output: {1, 3, 5} {1, 3, 5, 6}
my_set.remove(6) {1, 3, 5}
print(my_set) {1, 3, 5}
# discard an element Traceback (most recent call last):
# not present in my_set File "<string>", line 28, in <module>
# Output: {1, 3, 5} KeyError: 2
my_set.discard(2)
print(my_set)
Similarly, we can remove and return an item using the pop() method.

Since set is an unordered data type, there is no way of determining which item will be
popped. It is completely arbitrary.

We can also remove all the items from a set using the clear() method.
# initialize my_set
# Output: set of unique elements
my_set = set("HelloWorld")
print(my_set)
# pop an element
# Output: random element
print(my_set.pop())
# pop another element
my_set.pop() Output
print(my_set)
# clear my_set {'H', 'l', 'r', 'W', 'o', 'd', 'e'}
# Output: set() H
my_set.clear() {'r', 'W', 'o', 'd', 'e'}
print(my_set) set()

print(my_set)
Python Set Operations
Sets can be used to carry out mathematical set operations like union, intersection,
difference and symmetric difference. We can do this with operators or methods.

Let us consider the following two sets for the following operations.

>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
Set Union
Union of A and B is a set of all elements from both sets.

Union is performed using | operator. Same can be accomplished using the union()
method.
# Set union method
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)
Output
{1, 2, 3, 4, 5, 6, 7, 8}
# use union function
>>> A.union(B)
{1, 2, 3, 4, 5, 6, 7, 8}

# use union function on B


>>> B.union(A)
{1, 2, 3, 4, 5, 6, 7, 8}
Set Intersection

Intersection of A and B is a set of elements that are common in both the sets.
Intersection is performed using & operator. Same can be accomplished using the
intersection() method.

# Intersection of sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use & operator


# Output: {4, 5}
print(A & B)
Output
{4, 5}
# use intersection function on A
>>> A.intersection(B)
{4, 5}

# use intersection function on B


>>> B.intersection(A)
{4, 5}
Set Difference
Difference of the set B from set A(A - B) is a set of elements that are only in A but not in
B. Similarly, B - A is a set of elements in B but not in A.
Difference is performed using - operator. Same can be accomplished using the
difference() method.

# Difference of two sets


# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use - operator on A
# Output: {1, 2, 3}
print(A - B)
Output
{1, 2, 3}
# use difference function on A
>>> A.difference(B)
{1, 2, 3}

# use - operator on B
>>> B - A
{8, 6, 7}

# use difference function on B


>>> B.difference(A)
{8, 6, 7}
Set Symmetric Difference
Symmetric Difference of A and B is a set of elements in A and B but not in both (excluding
the intersection).
Symmetric difference is performed using ^ operator. Same can be accomplished using the
method symmetric_difference().
# Symmetric difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)
Output
{1, 2, 3, 6, 7, 8}
# use symmetric_difference function on A
>>> A.symmetric_difference(B)
{1, 2, 3, 6, 7, 8}

# use symmetric_difference function on B


>>> B.symmetric_difference(A)
{1, 2, 3, 6, 7, 8}
Dictionary
Dictionary is also an unordered collection in Python which has keys and values.
Dictionaries are very good at data retrieval you just need to know the key. To create
dictionary, we use curly brackets. The keys are the first element in and dictionary they
are unique and immutable. Each key and value pairs are separated by colon on the
left side is the key and right side is the value.

#Empty Dictionary declaration


>>> dict1 = {}
>>> dict2 = {"k":"value","two":2}
>>> type(dict2)
<class 'dict'>
Accessing elements of Dictionary

While indexing is used with other data types to access values, a dictionary uses keys.
Keys can be used either inside square brackets [] or with the get() method.

If we use the square brackets [], KeyError is raised in case a key is not found in the
dictionary. On the other hand, the get() method returns None if the key is not found.
# get vs [] for retrieving elements
my_dict = {'name': 'Jack', 'age': 26}

# Output: Jack
print(my_dict['name'])
Output
# Output: 26
Jack
print(my_dict.get('age'))
26
# Trying to access keys which doesn't exist throws errorNone
# Output None Traceback (most recent call last):
print(my_dict.get('address')) File "<string>", line 15, in
<module>
print(my_dict['address'])
# KeyError
print(my_dict['address']) KeyError: 'address'
Changing and Adding Dictionary elements
Dictionaries are mutable. We can add new items or change the value of existing items
using an assignment operator.

If the key is already present, then the existing value gets updated. In case the key is not
present, a new (key: value) pair is added to the dictionary.
# Changing and adding Dictionary Elements
my_dict = {'name': 'Jack', 'age': 26}

# update value
my_dict['age'] = 27

#Output: {'age': 27, 'name': 'Jack'}


print(my_dict) Output

# add item {'name': 'Jack', 'age': 27}


my_dict['address'] = 'Downtown' {'name': 'Jack', 'age': 27,
'address': 'Downtown'}
# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
print(my_dict)
Removing elements from Dictionary
We can remove a particular item in a dictionary by using the pop() method. This
method removes an item with the provided key and returns the value.

The popitem() method can be used to remove and return an arbitrary (key, value) item
pair from the dictionary. All the items can be removed at once, using the clear() method.

We can also use the del keyword to remove individual items or the entire dictionary
itself.
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# remove a particular item, returns its value # Output: 16
print(squares.pop(4))
# Output: {1: 1, 2: 4, 3: 9, 5: 25}
print(squares)
# remove an arbitrary item, return (key,value) # Output: (5, 25)
print(squares.popitem()) Output
# Output: {1: 1, 2: 4, 3: 9} 16
print(squares) {1: 1, 2: 4, 3: 9, 5: 25}
# remove all items (5, 25)
squares.clear() {1: 1, 2: 4, 3: 9}
# Output: {} {}
print(squares) Traceback (most recent call last):
# delete the dictionary itself File "<string>", line 30, in <module>
del squares print(squares)
# Throws Error NameError: name 'squares' is not defined
print(squares)
Manipulate or add elements in dictionary
my_info = {'name':'Rahul', 'age': 25}

# update value
my_info['age'] = 26

#Output: {'age': 26, 'name': 'Rahul'}


print(my_info)

# add item
my_info['address'] = 'India'

# Output: {'address': 'India', 'age': 26, 'name': 'Rahul'}


print(my_info)
Python Type Conversion

Type conversion is the process of converting data types from one type to another.
For example, an integer value is converted into a float, or a string is converted into a
number.
Type conversion can occur in one of the two types –
•Implicit Conversion
•Explicit Conversion
1. Implicit Conversion in Python

In implicit conversion, the Python automatically converts the value from one type to
another.

For example: when we add an integer and a float value, the resultant will be in float value.

In these types of situations, Python always converts the smaller data types into larger data
types so that data is not lost.
X = 12
Y = 20.50
Z=X+Y
print(Z)
type(X)
type(Y)
type(Z)

Output:

32.5
<class ‘int’>
<class ‘float’>
<class ‘float’>
However, when we add a string and an integer together, Python is not able to
use implicit conversion and it will give us a TypeError.
We can achieve this task by explicitly converting the data type.

2. Explicit Conversion in Python


In explicit conversion, users convert the data type of an object to
the required data type.

To perform the explicit conversion, we have some predefined functions


like int(), float(), str(), hex(), oct(), etc.
Type casting or data type conversion
We can convert different data types into some other by using different type conversion
functions like - int(), str(), float() , set() etc.

> > > float("5.2")


5.2
> > > float(5.2)
5.2
Note :When converting string to float it must be a compatible float value. Conversion
from Float to Int will truncate the value after decimal

>>> int(10.23)
10
>>> int(-11.96)
-11
Summary
Python has flexible and powerful data structures with in-built functions for all basic
manipulation

Accessing, retrieving and doing any computation is so easy with Python.

Python Collections (Arrays)


• There are four collection data types in the Python programming language:
• Lists - for ordered sequence of objects
• Tuple - can be considered as immutable list
• Set - unique list
• Dictionary / dict - pair of key and values
THANK YOU

You might also like