You are on page 1of 77

UNIT II –DATA TYPES IN PYTHON

2.1 DATATYPES IN PYTHON:

The data stored in memory can be of many types. For example, a person's age is stored
as a numeric value and his or her address is stored as alphanumeric characters. Python has
various standard data types that are used to define the operations possible on them and the
storage method for each of them.

Every value in Python has a datatype. Since everything is an object in Python


programming, data types are actually classes and variables are instance (object) of these classes.
Python provides various standard data types that define the storage method on each of them. The
data types defined in Python are given below.

1. Numbers

2. Sequence Type

3. Dictionary

4. Boolean

5. Set
2.1.1 Numbers:

Number stores numeric values. The integer, float, and complex values belong to a Python
Numbers data-type. Python provides the type() function to know the data-type of the variable.
Similarly, the isinstance() function is used to check an object belongs to a particular class.

Python creates Number objects when a number is assigned to a variable.

For example;
Output:

Python supports three types of numeric data.

1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has
no restriction on the length of an integer. Its value belongs to int

2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.

3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote
the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.

2.1.2Sequence Type:

String:
The string can be defined as the sequence of characters represented in the quotation marks. In
Python, we can use single, double, or triple quotes to define a string.

String handling in Python is a straightforward task since Python provides built-in functions and
operators to perform operations in the string.

 In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".

 The operator * is known as a repetition operator as the operation "Python" *2 returns


'Python Python'.

The following example illustrates the string in Python.

Output:

Example of string handling:


Output:

List:

Python Lists are similar to arrays in C. However, the list can contain data of different types. The
items stored in the list are separated with a comma (,) and enclosed within square brackets [].

We can use slice [:] operators to access the data of the list. The concatenation operator (+) and
repetition operator (*) works with the list in the same way as they were working with the strings.

Consider the following example.


Output:

Tuple:

A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The items of the tuple are separated with a comma (,) and enclosed
in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.

Let's see a simple example of the tuple.

Output:
Dictionary:

Dictionary is an unordered set of a key-value pair of items. It is like an associative array


or a hash table where each key stores a specific value. Key can hold any primitive data type,
whereas value is an arbitrary Python object.

The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.

Consider the following example.


Output:

it

Boolean:

Boolean type provides two built-in values, True and False. These values are used to determine
the given statement true or false. It denotes by the class bool. True can be represented by any
non-zero value or 'T' whereas false can be represented by the 0 or 'F'.

Consider the following example.

Output:

it

Set:

Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after
creation), and has unique elements. In set, the order of the elements is undefined; it may return
the changed sequence of the element. The set is created by using a built-in function set(), or a
sequence of elements is passed in the curly braces and separated by the comma. It can contain
various types of values.

Consider the following example.

Output:

2.2 MUTABLE vs IMMUTABLE OBJECTS IN PYTHON:

Python is an object-oriented programming language i.e., everything in Python is an


object. Every variable in Python holds an instance of an object. Objects are abstraction for data,
and Python has an amazing variety of data structures that you can use to represent data, or
combine them to create own custom data.
There are two types of objects in Python i.e. Mutable and Immutable objects.A first
fundamental distinction that Python makes on data is about whether or not the value of an object
changes. If the value can change, the object is called mutable, while if the value cannot change,
the object is called immutable.

Whenever an object is instantiated, it is assigned a unique object id. The type of the
object is defined at the runtime and it can’t be changed afterwards. However, it’s state can be
changed if it is a mutable object.
To summarize the difference, mutable objects can change their state or contents and
immutable objects can’t change their state or content.

 Immutable Objects: These are of in-built types like int, float, bool, string, unicode, tuple.
In simple words, an immutable object can’t be changed after it is created.
 Mutable Objects : These are of type list, dict, set . Custom classes are generally mutable.
Mutable and immutable objects are handled differently in python. Immutable objects are
quicker to access and are expensive to change because it involves the creation of a copy.
Whereas mutable objects are easy to change. Use of mutable objects is recommended when
there is a need to change the size or content of the object

It is important to understand that every object in Python has an ID (identity), and type and
a value. Once created, the ID of an object never changes. It is a unique identifier for it, and it is
used behind the scenes by Python to retrieve the object when we want to use it.

The type also never changes. The type tells what operations are supported by the object and
the possible values that can be assigned to it.

The value can either change or not. If it can, the object is said to be mutable, while when it
cannot, the object is said to be immutable.

2.2.1Mutable Data Types:


Mutable sequences can be changed after creation. Some of Python’s mutable data types
are: lists, byte arrays, sets, and dictionaries.

Lists: lists are mutable.

Here is an example of list:

Output is:

Byte Arrays:

Byte arrays represent the mutable version of bytes objects. They expose most of the
usual methods of mutable sequences as well as most of the methods of the bytes type. Items
are integers in the range [0, 256).
Sets

Python provides two set types, set and frozenset. They are unordered collections of immutable
objects.

2.2.2 Immutable Data Types:


Immutable data types differ from their mutable counterparts in that they cannot be
changed after creation. Some immutable types include numeric data
types, strings, bytes, frozen sets, and tuples.

Numeric Data Types:


You have already seen that integers are immutable; similarly, Python’s other built-in numeric data
types such as booleans, floats, complex numbers, fractions, and decimals are also immutable!

Strings and Bytes:


Textual data in Python is handled with str objects, more commonly known as strings. They are
immutable sequences of Unicode code points. Unicode code points can represent a character.
When it comes to storing textual data though, or sending it on the network, you may want to
encode it, using an appropriate encoding for the medium you’re using. The result of an encoding
produces a byte’s object, whose syntax and behavior is similar to that of strings.
Both strings and bytes are immutable.

Frozen Sets:

As discussed in the previous section, frozensets are similar to sets. However, frozenset objects are
quite limited in respect of their mutable counterpart since they cannot be changed. Nevertheless,
they still prove very effective for membership test, union, intersection, and difference operations,
and for performance reasons.

Tuples:

The last immutable sequence type we’re going to see is the tuple. A tuple is a sequence of
arbitrary Python objects. In a tuple, items are separated by commas. These, too, are immutable, as
shown in the following example:
2.3 FUNDAMENTAL DATA TYPES:

Data type is a collection of data or items. The basic fundamental data types are numeric data
type which consists of the following:
 INT
 FLOAT
 COMPLEX
 BOOLEAN
 STRING.

2.3.1 INT data type:

These represent numbers in the range -2147483648 through 2147483647. (The range
may be larger on machines with a larger natural word size, but not smaller.) When the result of
an operation would fall outside this range, the result is normally returned as a long integer (in
some cases, the exception OverflowError is raised instead). For the purpose of shift and mask
operations, integers are assumed to have a binary, 2’s complement notation using 32 or more
bits, and hiding no bits from the user (i.e., all 4294967296 different bit patterns correspond to
different values).

Plain integers (also just called integers) are implemented using long in C, which gives
them at least 32 bits of precision (sys.maxint is always set to the maximum plain integer value
for the current platform; the minimum value is -sys.maxint - 1). Long integers have unlimited
precision.

Numbers are created by numeric literals or as the result of built-in functions and
operators. Unadorned integer literals (including binary, hex, and octal numbers) yield plain
integers unless the value they denote is too large to be represented as a plain integer, in which
case they yield a long integer. Integer literals with an ‘L’ or ‘l’ suffix yield long integers (‘L’ is
preferred because 1l looks too much like eleven!).

2.3.2 FLOAT data type:

These represent machine-level double precision floating point numbers. You are at the
mercy of the underlying machine architecture (and C or Java implementation) for the accepted
range and handling of overflow. Python does not support single-precision floating point
numbers; the savings in processor and memory usage that are usually the reason for using these
is dwarfed by the overhead of using objects in Python, so there is no reason to complicate the
language with two kinds of floating point numbers.
Floating point numbers are usually implemented using double in C; information about the
precision and internal representation of floating point numbers for the machine on which your
program is running is available in sys.float_info.

2.3.3 COMPLEX datatype:


Complex numbers are an extension of the familiar real number system in which all
numbers are expressed as a sum of a real part and an imaginary part. Imaginary numbers are real
multiples of the imaginary unit (the square root of -1), often written i in mathematics or j in
engineering. Python has built-in support for complex numbers, which are written with this latter
notation; the imaginary part is written with a j suffix, e.g., 3+1j. To get access to complex
equivalents of the math module, use cmath. Use of complex numbers is a fairly advanced
mathematical feature. If you’re not aware of a need for them, it’s almost certain you can safely
ignore them.
Complex numbers are stored as a pair of machine-level double precision floating point numbers.

2.3.4 BOOLEAN datatypes:


These represent the truth values False and True. The two objects representing the
values False and True are the only Boolean objects. The Boolean type is a subtype of plain
integers, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts,
the exception being that when converted to a string, the strings “False” or “True” are returned,
respectively.

2.3.5 STRING datatype:


The items of a string are characters. There is no separate character type; a character is
represented by a string of one item. Characters represent (at least) 8-bit bytes. The built-in
functions chr() and ord() convert between characters and nonnegative integers representing
the byte values. Bytes with the values 0-127 usually represent the corresponding ASCII values,
but the interpretation of values is up to the program. The string data type is also used to
represent arrays of bytes, e.g., to hold data read from a file.

2.4 NUMBER DATATYPES:


Binary, Octal and Hexadecimal numbers

In Python we can print decimal equivalent of binary, octal and hexadecimal numbers using the
following built-in functions.

 bin() : used to return the binary representation of a specified integer.

Eg: x =  10  
y =  bin(x)  

print (y)

 hex():   used to generate hex value of an integer argument.

Eg: result = hex(1)  

result2 = hex(342)  

print(result)  

print(result2)

 oct() :is used to get an octal value of an integer number. 

Eg: val = oct(10) 

print("Octal value of 10:",val)

2.5 INBULT FUNCTIONS IN PYTHON:

The Python built-in functions are defined as the functions whose functionality is pre-
defined in Python. The python interpreter has several functions that are always present for use.
These functions are known as Built-in Functions. There are several built-in functions in Python
which are listed below:

S.NO FUNCTION & ITS EXAMPLE


DESCRIPTION
1. abs() : used to return the
1. integer = -20  
absolute value of 2.
a print('Absolute value of -40 is:', abs(integer))  
number. 3.   
OUTPUT: Absolute value of -20 is: 20
2. all() : accepts an iterable
1. k = [0, False]  
object (such as list,
2. print(all(k))  
dictionary, etc.)
OUTPUT: False
3. bin() : used to return the
1. x =  10  
binary representation of 2.
a y =  bin(x)  
specified integer. 3. print (y)  
4.
OUTPUT: 0b1010

4.  bool(): converts a value
1. test1 = [0]  
to boolean(True or False)
2. print(test1,'is',bool(test1))  
using the standard truth
testing procedure. OUTPUT: [0] is True

5. bytes() : used for


1. string = "Hello World."  
returning a bytes object.  2. array = bytes(string, 'utf-8')  
3. print(array) 

OUTPUT: b ' Hello World.'

6. callable() : is something
1. x = 8  
that can be called. This
2. print(callable(x))  
built-in function checks
and returns true if the OUTPUT: False
object passed appears to
be callable, otherwise
false.
7.  compile() : takes source
1. code_str = 'x=5\ny=10\nprint("sum =",x+y)'  
code as input and returns
2. code = compile(code_str, 'sum.py', 'exec')  
a code object which can
3. print(type(code))  
later be executed by
4. exec(code)  
exec() function. 5. exec(x)  
OUTPUT: <class 'code'>
sum = 15

8.  exec() : used for the


dynamic execution 1. x = 8  
of
Python program 2. exec('print(x==8)')  
which
3. exec('print(x+4)')  
can either be a string or
object code and it accepts
large blocks code, OUTPUT: True
of
unlike the eval() function 12
which only accepts a
single expression.
9. sum() : used to get the
1. s = sum([1, 2, 4], 10)  
sum of numbers of an
2. print(s)  
iterable, i.e., list.
OUTPUT: 17

10. any() function returns true1. l = [0, False, 5]  


if any item in an iterable is2. print(any(l))  
true. Otherwise, it returns
False. OUTPUT: True

11. ascii() : returns a string 1. otherText = 'Pythön is interesting'  


containing a printable 2. print(ascii(otherText
representation of an
object and escapes the OUTPUT: 'Pyth\xf6n is interesting'
non-ASCII characters in
the string using \x, \u or \
U escapes
12. bytearray(): returns 1.
a string = "Python is a programming language."  
bytearray object and can
2.   
convert objects into
3. # string with encoding 'utf-8'  
bytearray objects, or
4. arr = bytearray(string, 'utf-8')  
create an empty bytearray
5. print(arr)  
object of the specified OUTPUT: bytearray(b'Python is a programming
size. language.')

13. eval() :parses the


1. x = 8  
expression passed to 2.
it print(eval('x + 1'))  
and runs python
expression(code) within OUTPUT: 9
the program.
14.  float() :returns a floating- print(float(8.19))  
point number from a
number or string. OUTPUT: 8.19

15. format() :returns a print(format(12, "b"))  


formatted representation
of the given value. OUTPUT: 1100
16.  frozenset():returns an
1. letters = ('m', 'r', 'o', 't', 's')  
immutable frozenset
2. fSet = frozenset(letters)  
object initialized with
3. print('Frozen set is:', fSet)  
elements from the given
4. print('Empty frozen set is:', frozenset())  
iterable. OUTPUT: Frozen set is: frozenset({'o', 'm', 's', 'r', 't'})
Empty frozen set is: frozenset()
17. getattr() :returns the
1. class Details:  
value of a named attribute
2.     age = 22  
of an object. If it is not
3.     name = "Phill"  
found, it returns the
4. details = Details()  
default value. 5. print('The age is:', getattr(details, "age"))  
6. print('The age is:', details.age)  
OUTPUT: The age is: 22
The age is: 22
18. globals() :returns the
1. age = 22  
dictionary of the current
2. globals()['age'] = 22  
global symbol table. 3. print('The age is:', age) 
OUTPUT: The age is: 22
19. iter() : used to return an
1. list = [1,2,3,4,5]  
iterator object. It creates
2. listIter = iter(list)  
an object which can be
3. # prints '1'  
iterated one element at 4.
a print(next(listIter))
time. OUTPUT: 1
20. len() :used to return the
1. strA = 'Python'  
length (the number of
2. print(len(strA))  
items) of an object. OUTPUT: 6
21.  list(): creates a list in
1. String = 'abcde'       
python. 2. print(list(String)) 
OUTPUT: ['a', 'b', 'c', 'd', 'e']

22. locals() :updates and


1. def localsPresent():  
returns the dictionary of
2.     present = True  
the current local symbol
3.     return locals()  
table. 4.   print('localsPresent:', localsPresent()) 
OUTPUT: localsPresent: {'present': True}

23. map() : used to return 1.


a numbers = (1, 2, 3, 4)  
list of results after
2. result = map(calculateAddition, numbers)  
applying a given function
3. print(result)
to each item of an OUTPUT: {8, 2, 4, 6}
iterable(list, tuple etc.).
24. memoryview() :returns 1.
a randomByteArray = bytearray('ABC', 'utf-8')  
memoryview object of the
2.   
given argument. 3. mv = memoryview(randomByteArray)  
4.   
5. # access the memory view's zeroth index  
6. print(mv[0])  
OUTPUT: 65

25. object() : returns an


1. python = object()  
empty object. It is a base
2.   
for all the classes and
3. print(type(python))  
holds the built-in
4. print(dir(python)) 
properties and methods OUTPUT: <class 'object'>
which are default for all ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__',
the classes. '__format__', '__ge__',
'__getattribute__', '__gt__', '__hash__', '__init__',
'__le__', '__lt__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__',
'__str__', '__subclasshook__']

26. open() :opens the file and


1. f = open("python.txt")  
returns a corresponding
2. # specifying full path  
file object. 3. f = open("C:/Python33/README.txt")  
OUTPUT: Since the mode is omitted, the file is opened
in 'r' mode; opens for reading.

27.  chr() :used to get a string result = chr(102) # It returns string representation of a c


representing a character har
which points to a Unicode print(result)  
code integer. For example, print("is it string type:", type(result) is str)  
chr(97) returns the string  OUTPUT: ValueError: chr() arg not in range(0x110000)
'a'. 
28.  complex() :used to a = complex(1) # Passing single parameter  
convert numbers or string b = complex(1,2) # Passing both parameters
print(a)  
into a complex number
print(b)
OUTPUT: (1.5+0j)
(1.5+2.2j)

29. delattr() : used to delete an class Student:  


attribute from a class.   id = 101  
name = "Pranshu"  
def getinfo(self):  
 print(self.id, self.name)
1. s = Student()  
2. s.getinfo()  
3. delattr(Student,'course') 
4. s.getinfo() 

OUTPUT: 101 Pranshu


AttributeError: course

30. dir() : returns the list of names


1. att = dir()  
in the current local scope. 2. print(att)  
OUTPUT: ['__annotations__', '__builtins__', '__cached__',
'__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__']

31. divmod() : used to get


1. result = divmod(10,2)  
remainder and quotient of two
2. print(result)
numbers.  OUTPUT: (5, 0)

32. enumerate() function returns


1. result = enumerate([1,2,3])  
an enumerated object 2. print(result)  
3. print(list(result))  
OUTPUT: <enumerate object at 0x7ff641093d80>
[(0, 1), (1, 2), (2, 3)]

33. dict() :is a constructor which


1. result = dict() 
creates a dictionary. 2. result2 = dict(a=1,b=2)  
3. print(result)  
4. print(result2)  
OUTPUT: {}
{'a': 1, 'b': 2}

34. filter() :used to get filtered


1. def filterdata(x):  
elements.  2.     if x>5:  
3.         return x  
4. result = filter(filterdata,(1,2,6))  
5. print(list(result))  
OUTPUT: [6]

35.  hash() :used to get the hash


1. result = hash(21) 
value of an object 2. result2 = hash(22.2) 
3. print(result)  
4. print(result2)  
OUTPUT: 21
461168601842737174
36. help() :used to get help related
1. info = help()
to the object passed during the
2. print(info)  
call OUTPUT: Welcome to Python 3.5's help utility!

37. min() :used to get the smallest small = min(2225,325,2025) 


element from the collection. print(small)
OUTPUT: 325

38. Set(): is a built-in class, and this result = set() # empty set  


function is a constructor of this result2 = set('12')  
class.  print(result)  
print(result2)
OUTPUT: set()
{'1', '2'}

39. hex(): used to generate hex result = hex(1)  


value of an integer argument result2 = hex(342)  
1. print(result)  
2. print(result2)
OUTPUT: 0x1
0x156

40. id(): function returns the val2 = id(1200) 


identity of an object val3 = id([25,336,95,236,92,3225]) 
print(val2)  
print(val3)
OUTPUT: 139963805666864
139963781994504

41. setattr() : is used to set a value student = Student(102,"Sohan")  


to the object's attribute print(student.id)  
print(student.name)  
setattr(student, 'email','sohan@abc.com')
print(student.email)  
OUTPUT: 102
Sohan
sohan@abc.com

42. slice() : used to get a slice of


1. result = slice(5) 
elements from the collection of
2. result2 = slice(0,5,3)
elements.  3. print(result)  
4. print(result2)  
OUTPUT: slice(None, 5, None)
slice(0, 5, 3)

43. sorted() :is used to sort str = "mrecw"


elements. sorted1 = sorted(str) 
print(sorted1) 

OUTPUT: [‘c’,’e’,’m’,’r’,’w’]
44.  next() :is used to fetch next number = iter([256, 32, 82])
item from the collection. item = next(number)
print(item)
1. item = next(number)  
2. print(item)
OUTPUT: 256
32

45. input() :is used to get an input val = input("Enter a value: ")  


from the user. print("You entered:",val)  
OUTPUT: Enter a value: 45
You entered: 45

46.  int() :is used to get an integer


1. val = int(10) 
value 2. val2 = int(10.52) 
3. val3 = int('10')
4. print("integer values :",val, val2, val3)  
OUTPUT: integer values: 10 10 10
47.  isinstance() :is used to check student = Student(1010,"John")  
whether the given object is an lst = [12,34,5,6,767] 
instance of that class. print(isinstance(student, Student)) 
print(isinstance(lst, Student)) 
OUTPUT: True
False

48. oct() :is used to get an octal val = oct(10) 


value of an integer number.  print("Octal value of 10:",val)
OUTPUT: Octal value of 10: 0o12

49. ord() function returns an print(ord('8'))  


integer representing Unicode print(ord('R')) 
code point for the given
Unicode character. OUTPUT: 56
82

50. pow() : is used to compute the


1. print(pow(4, 2))  
power of a number. It returns2.
x print(pow(-4, 2)) 
to the power of y. If the third print(pow(4, -2))  
argument(z) is given, it returns OUTPUT: 16
x to the power of y modulus z, 16
i.e. (x, y) % z. 0.0625

51. print() : prints the given object


1. print("Python is programming language.")  
to the screen or other standard
2.  x = 7  
output devices. 3. print("x =", x)  
4. y = x  
5. print('x =', x, '= y')  
OUTPUT: Python is programming language.
x=7
x=7=y

52. range() :returns an immutable print(list(range(0)))  


sequence of numbers starting print(list(range(4))) 
from 0 by default, increments print(list(range(1,7 )))  
by 1 (by default) and ends at a OUTPUT: []
specified number. [0, 1, 2, 3]
[1, 2, 3, 4, 5, 6]

53. reversed() :returns the reversed String = 'Java'  


iterator of the given sequence. print(list(reversed(String)))  
Tuple = ('J', 'a', 'v', 'a')  
print(list(reversed(Tuple)))  
OUTPUT: ['a', 'v', 'a', 'J']
['a', 'v', 'a', 'J']

54. round() :rounds off the digits of print(round(10)) 


a number and returns the print(round(10.8)) 
floating point number. print(round(6.6)) 

OUTPUT: 10
11
7

55. issubclass() :returns true if class Rectangle:  


object argument(first def __init__(rectangleType):  
 print('Rectangle is a ', rectangleType)  
argument) is a subclass of
class Square(Rectangle):  
second class(second  def __init__(self):  
argument).  Rectangle.__init__('square')  
print(issubclass(Square, Rectangle))  
print(issubclass(Square, list))  
print(issubclass(Square, (list, Rectangle)))  
print(issubclass(Rectangle, (list, Rectangle)))  

OUTPUT: True
False
True
True

56. str(): converts a specified str('4') 


value into a string. OUTPUT: '4'

57. tuple() :is used to create a tuple


1. t2 = tuple([1, 6, 9])  
object. 2. print('t2=', t2)  
OUTPUT: t2= (1, 6, 9)

58. type() :returns the type of the


1. List = [4, 5]  
specified object if a single
2. print(type(List))  
argument is passed to the
3.   
type() built in function. If three
4. Dict = {4: 'four', 5: 'five'}  
arguments are passed, then 5.
it print(type(Dict))  
returns a new type object. 6.   
7. class Python:  
8.     a = 0  
9.   
10. InstanceOfPython = Python()  
11. print(type(InstanceOfPython))
OUTPUT:<class 'list'>
<class 'dict'>
<class '__main__.Python'>

59. vars() : returns the __dict__


1. class Python:  
attribute of the given object. 2.   def __init__(self, x = 7, y = 9):  
3.     self.x = x  
4.     self.y = y  
5.     
6. InstanceOfPython = Python()  
7. print(vars(InstanceOfPython))  

OUTPUT: {'y': 9, 'x': 7}


60. zip() :returns a zip object, which numList = [4,5, 6]  
maps a similar index of multiple strList = ['four', 'five', 'six']  
containers. result = zip()  
resultList = list(result)  
print(resultList)  
result = zip(numList, strList)    
resultSet = set(result)  
print(resultSet) 
OUTPUT: []
{(5, 'five'), (4, 'four'), (6, 'six')}
8.

2.6 DATATYPE CONVERSIONS:

Sometimes, you may need to perform conversions between the built-in types. To convert
between types, you simply use the type name as a function.

There are several built-in functions to perform conversion from one data type to another. These
functions return a new object representing the converted value.

Sr.No. Function & Description

1 int(x [,base])

Converts x to an integer. base specifies the base if x is a string.

2 long(x [,base] )

Converts x to a long integer. base specifies the base if x is a string.

3 float(x)
Converts x to a floating-point number.

4 complex(real [,imag])

Creates a complex number.

5 str(x)

Converts object x to a string representation.

6 repr(x)

Converts object x to an expression string.

7 eval(str)

Evaluates a string and returns an object.

8 tuple(s)

Converts s to a tuple.

9 list(s)

Converts s to a list.

10 set(s)

Converts s to a set.

11 dict(d)

Creates a dictionary. d must be a sequence of (key,value) tuples.


12 frozenset(s)

Converts s to a frozen set.

13 chr(x)

Converts an integer to a character.

14 unichr(x)

Converts an integer to a Unicode character.

15 ord(x)

Converts a single character to its integer value.

16 hex(x)

Converts an integer to a hexadecimal string.

17 oct(x)

Converts an integer to an octal string.

2.7PRIORITIES OF DATATYPES IN PYTHON:


2.8PYTHON OPERATORS:

The operator can be defined as a symbol which is responsible for a particular operation
between two operands. Operators are the pillars of a program on which the logic is built in a
specific programming language. Python provides a variety of operators, which are described as
follows.

 Arithmetic operators
 Assignment Operators

 Logical Operators

 Bitwise Operators

 Membership Operators

 Identity Operators

2.8.1 Arithmetic Operators:

Arithmetic operators are used to perform arithmetic operations between two operands. It includes
+ (addition), - (subtraction), *(multiplication), /(divide), %(reminder), //(floor division), and
exponent (**) operators.

Consider the following table for a detailed explanation of arithmetic operators.


2.8.2 Comparison operators:

Comparison operators are used to comparing the value of the two operands and
returns Boolean true or false accordingly. The comparison operators are described in the
following table.

2.8.3 Assignment Operators:

The assignment operators are used to assign the value of the right expression to the left operand.
The assignment operators are described in the following table.
2.8.4 Bitwise Operators:

The bitwise operators perform bit by bit operation on the values of the two operands. Consider
the following example.

For example,
2.8.5 Logical Operators:

The logical operators are used primarily in the expression evaluation to make a decision. Python
supports the following logical operators.

2.8.6 Membership Operators:

Python membership operators are used to check the membership of value inside a Python data
structure. If the value is present in the data structure, then the resulting value is true otherwise it
returns false.
2.8.7 Identity Operators:

The identity operators are used to decide whether an element certain class or type

2.9 Slicing and Indexing:


What is Python Slice?

On our way up the learning curve for Python, we only need to deal with Python
iterables not so huge. But when building an application with it, not always do we need to
retrieve the entire iterable. In such cases, slicing is useful as it lets us choose what to see and
focus on. This aids readability and implements abstraction.

about Copy in Python

To slice a iterable, we use the slicing operator, that is [ ]. To separate the start, stop, and step
values, we use the colon ( : ).
Say you want to declare a list with the values 1,2,3,4,5, and only want to see values 2,3, and 4.
You can slice the list for that.

1. >>> list=[1,2,3,4,5]

2. >>> list[1:4]

[2, 3, 4]

3. The Python Slice() Function

slice() is a constructor that creates a Python Slice object to represent the set of indices that
range(start, stop, step) specifies. With this, we can slice a sequence like a string, a tuple, a list, a
range object, or a bytes object. These are all objects that support sequence protocols and
implement __getitem__() and __len__().
The slice() function returns a Python Slice Object.

different Python Functions

a. The Syntax of Python Slice

Let’s talk about the syntax of Slicing in Python first:

1. slice(stop)

1. slice(start, stop, step)

What are these parameters? Let’s see:

 start- Where to begin slicing (Optional)

 stop- Where to stop slicing+1

 step- How much to increment between each index (Optional)


You’ll see that we have two syntaxes. When we provide only one parameter value, it takes it to
be the stop value. This means to start and step are set to None.

b. Python Slice Example

Let’s take a simple example of Python Slicing.

1. >>>slice(3)

slice(None, 3, None)

We can index this as:

1. >>> l=[1,2,3,4,5]

2. >>> l[slice(3)]

[1, 2, 3]
Note that it displays values at the indices 0, 1, and 2. It stops at index 3.

4. Python String Slice

We can slice a string in Python using the Python slice() method.

2.9.1 Forward Direction Slicing with +ve Step

We can also specify the interval. Slicing a string may give us a substring when the step size is 1.
You must learn about Python String

1. >>> s='helloworld'

2. >>> s[slice(1,6,2)]

‘elw’

 With positive indices-

Like in the previous example, we use positive indices here.


1. >>> s='helloworld'

2. >>> s[slice(1,6)]

‘ellow’

2.9.2 Backward Direction Slicing with -ve Step:

 With negative indices-

But like we’ve seen with lists earlier, we can pass negative indices too. These are what it
traverses from the right.
To read the same value right to left, we do:

1. >>> s='helloworld'

2. >>> s[slice(-5,-10,-1)]

‘wolle’
Here’s how we traverse right to left:

Python String Slice

We index everything from letters to digits and from spaces to characters.

5. Python Slicing Tuples

Now let’s take a look at performing Python Slicing on tuples. Check the following code:

 Positive Indices-
1. >>> t=(1,2,3,4,5)

2. >>> t[slice(2,4)]

(3, 4)

 Negative Indices-

Let’s traverse right to left.

1. >>> t[slice(-1,-5,-2)]

(5, 3)

6. Indexing to Create Python Slice

We have often sliced lists using [ : ]. Let’s try that one more time.

Remember the previous Python Slicing example? Now take a look at this-

1. >>> t[-1:-5:-2]

(5, 3)
So we concur that slicing is a way to choose indices for elements to show. What slice() really
does is give us indices for those. We can use the slice() function as a subscript.

When indexing, what happens when we do not pass one or more of the values?

1. >>> t[:3]#From 0 to 2

(1, 2, 3)

1. >>> t[3:]#From 3 to end

(4, 5)

1. >>> t[:]#From beginning to end

(1, 2, 3, 4, 5)
a. Extended Python Slices with a step value

1. >>> t[::-1]#Reverse

(5, 4, 3, 2, 1)

1. >>> t[::-2]#Reverse with step=2

(5, 3, 1)

1. >>> t[:5:2]#Upto index 5, with step=2

(1, 3, 5)

1. >>> t[:5:-1]#Index 5 to end (already ahead of that), right to left; results in empty tuple

()

know about Methods in Python

1. >>> t

(1, 2, 3, 4, 5)

1. >>> t[len(t)::-3]#End to front, step=3 right to left

(5, 2)

b. Resizing Lists in Python Slices

1. >>> l=[1,2,3,4,5]

2. >>> l[1:4]

[2, 3, 4]

1. >>> l[1:4]=[2,3,3.5,4]

2. >>> l

[1, 2, 3, 3.5, 4, 5]
The length of the slice on the right should be equal to that on the left.
c. Deleting Python Slices

We can also use the del keyword to delete a slice.

1. >>> del l[::4]

2. >>> l

[2, 3, 3.5, 5]

2.10 Decision Making Statements:

Decision making is the most important aspect of almost all the programming languages. As the
name implies, decision making allows us to run a particular block of code for a particular
decision. Here, the decisions are made on the validity of the particular conditions. Condition
checking is the backbone of decision making.

In python, decision making is performed by the following statements.

Indentation in Python

For the ease of programming and to achieve simplicity, python doesn't allow the use of
parentheses for the block level code. In Python, indentation is used to declare a block. If two
statements are at the same indentation level, then they are the part of the same block.

Generally, four spaces are given to indent the statements which are a typical amount of
indentation in python.
Indentation is the most used part of the python language since it declares the block of code. All
the statements of one block are intended at the same level indentation. We will see how the
actual indentation takes place in decision making and other stuff in python.

2.10.1 The if statement

The if statement is used to test a particular condition and if the condition is true, it executes a
block of code known as if-block. The condition of if statement can be any valid logical
expression which can be either evaluated to true or false.

The syntax of the if-statement is given below.

1. if expression:  

2.     statement  

Example 1
1. num = int(input("enter the number?"))  

2. if num%2 == 0:  

3.     print("Number is even")  

Output:

enter the number?10

Number is even

Example 2 : Program to print the largest of the three numbers.

1. a = int(input("Enter a? "));  

2. b = int(input("Enter b? "));  

3. c = int(input("Enter c? "));  

4. if a>b and a>c:  

5.     print("a is largest");  

6. if b>a and b>c:  

7.     print("b is largest");  

8. if c>a and c>b:  

9.     print("c is largest");  

Output:

Enter a? 100

Enter b? 120

Enter c? 130

c is largest

2.10.2 The if-else statement


The if-else statement provides an else block combined with the if statement which is executed
in the false case of the condition.

If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.

The syntax of the if-else statement is given below.

1. if condition:  

2.     #block of statements   

3. else:   

4.     #another block of statements (else-block)   

Example 1 : Program to check whether a person is eligible to vote or not.

1. age = int (input("Enter your age? "))  

2. if age>=18:  

3.     print("You are eligible to vote !!");  
4. else:  

5.     print("Sorry! you have to wait !!");  

Output:

Enter your age? 90

You are eligible to vote !!

Example 2: Program to check whether a number is even or not.

1. num = int(input("enter the number?"))  

2. if num%2 == 0:  

3.     print("Number is even...")  

4. else:  

5.     print("Number is odd...")  

Output:

enter the number?10

Number is even

2.10.3 The elif statement

The elif statement enables us to check multiple conditions and execute the specific block of
statements depending upon the true condition among them. We can have any number of elif
statements in our program depending upon our need. However, using elif is optional.

The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement.

The syntax of the elif statement is given below.

1. if expression 1:   
2.     # block of statements   

3.   

4. elif expression 2:   

5.     # block of statements   

6.   

7. elif expression 3:   

8.     # block of statements   

9.   

10. else:   

11.     # block of statements  
Example 1
1. number = int(input("Enter the number?"))  

2. if number==10:  

3.     print("number is equals to 10")  

4. elif number==50:  

5.     print("number is equal to 50");  

6. elif number==100:  

7.     print("number is equal to 100");  

8. else:  
9.     print("number is not equal to 10, 50 or 100");  

Output:

Enter the number?15

number is not equal to 10, 50 or 100

Example 2

1. marks = int(input("Enter the marks? "))  

2. f marks > 85 and marks <= 100:  

3.    print("Congrats ! you scored grade A ...")  

4. lif marks > 60 and marks <= 85:  

5.    print("You scored grade B + ...")  

6. lif marks > 40 and marks <= 60:  

7.    print("You scored grade B ...")  

8. lif (marks > 30 and marks <= 40):  

9.    print("You scored grade C ...")  

10. lse:  

11.    print("Sorry you are fail ?")  

2.11 Looping Statements

The flow of the programs written in any programming language is sequential by default.
Sometimes we may need to alter the flow of the program. The execution of a specific code may
need to be repeated several numbers of times.

For this purpose, The programming languages provide various types of loops which are capable
of repeating some specific code several numbers of times. Consider the following diagram to
understand the working of a loop statement.
2.11.1 Why we use loops in python?

The looping simplifies the complex problems into the easy ones. It enables us to alter the flow
of the program so that instead of writing the same code again and again, we can repeat the
same code for a finite number of times. For example, if we need to print the first 10 natural
numbers then, instead of using the print statement 10 times, we can print inside a loop which
runs up to 10 iterations.

2.11.2 Advantages of loops

There are the following advantages of loops in Python.

1. It provides code re-usability.


2. Using loops, we do not need to write the same code again and again.
3. Using loops, we can traverse over the elements of data structures (array or linked lists).

There are the following loop statements in Python.


2.12 Python for loop

The for loop in Python is used to iterate the statements or a part of the program several times.
It is frequently used to traverse the data structures like list, tuple, or dictionary.

The syntax of for loop in python is given below.

1. for iterating_var in sequence:    

2.     statement(s)    

The for loop flowchart


For loop Using Sequence

Example-1: Iterating string using for loop

1. str = "Python"  

2. for i in str:  

3.     print(i)  

Output:

n
Example- 2: Program to print the table of the given number .

1. list = [1,2,3,4,5,6,7,8,9,10]  

2. n = 5  

3. for i in list:  

4.     c = n*i  

5.     print(c)  

Output:

10

15

20

25

30

35

40

45

50s

Example-4: Program to print the sum of the given list.

1. list = [10,30,23,43,65,12]  

2. sum = 0  

3. for i in list:  

4.     sum = sum+i  

5. print("The sum is:",sum)  

Output:
The sum is: 183

For loop Using range() function

The range() function

The range() function is used to generate the sequence of the numbers. If we pass the range(10),
it will generate the numbers from 0 to 9. The syntax of the range() function is given below.

Syntax:

1. range(start,stop,step size)  

o The start represents the beginning of the iteration.


o The stop represents that the loop will iterate till stop-1. The range(1,5) will generate
numbers 1 to 4 iterations. It is optional.
o The step size is used to skip the specific numbers from the iteration. It is optional to use.
By default, the step size is 1. It is optional.

Consider the following examples:

Example-1: Program to print numbers in sequence.

1. for i in range(10):  

2.     print(i,end = ' ')  

Output:

0123456789

Example - 2: Program to print table of given number.

1. n = int(input("Enter the number "))  

2. for i in range(1,11):  

3.     c = n*i  

4.     print(n,"*",i,"=",c)  

Output:
Enter the number 10

10 * 1 = 10

10 * 2 = 20

10 * 3 = 30

10 * 4 = 40

10 * 5 = 50

10 * 6 = 60

10 * 7 = 70

10 * 8 = 80

10 * 9 = 90

10 * 10 = 100

Example-3: Program to print even number using step size in range().

1. n = int(input("Enter the number "))  

2. for i in range(2,n,2):  

3.     print(i)  

Output:

Enter the number 20

10

12

14
16

18

We can also use the range() function with sequence of numbers. The len() function is combined


with range() function which iterate through a sequence using indexing. Consider the following
example.

1. list = ['Peter','Joseph','Ricky','Devansh']  

2. for i in range(len(list)):  

3.     print("Hello",list[i])  

Output:

Hello Peter

Hello Joseph

Hello Ricky

Hello Devansh

2.12.1 Nested for loop in python

Python allows us to nest any number of for loops inside a for loop. The inner loop is executed n
number of times for every iteration of the outer loop. The syntax is given below.

Syntax

1. for iterating_var1 in sequence:  #outer loop  

2.     for iterating_var2 in sequence:  #inner loop  

3.         #block of statements     

4. #Other statements    

Example- 1: Nested for loop

1. # User input for number of rows  

2. rows = int(input("Enter the rows:"))  
3. # Outer loop will print number of rows  

4. for i in range(0,rows+1):  

5. # Inner loop will print number of Astrisk  

6.     for j in range(i):  

7.         print("*",end = '')  

8.     print()  

Output:

Enter the rows:5

**

***

****

*****

Example-2: Program to number pyramid.

1. rows = int(input("Enter the rows"))  

2. for i in range(0,rows+1):  

3.     for j in range(i):  

4.         print(i,end = '')  

5.     print()  

Output:

22

333

4444
55555

2.12.2 Using else statement with for loop

Unlike other languages like C, C++, or Java, Python allows us to use the else statement with the
for loop which can be executed only when all the iterations are exhausted. Here, we must
notice that if the loop contains any of the break statement then the else statement will not be
executed.

Example 1

1. for i in range(0,5):    

2.     print(i)    

3. else:  

4.     print("for loop completely exhausted, since there is no break.")  

Output:

for loop completely exhausted, since there is no break.

The for loop completely exhausted, since there is no break.

Example 2

1. for i in range(0,5):    

2.     print(i)    

3.     break;    

4. else:print("for loop is exhausted");    
5. print("The loop is broken due to break statement...came out of the loop")    

In the above example, the loop is broken due to the break statement; therefore, the else
statement will not be executed. The statement present immediate next to else block will be
executed.

Output:

2.13 Python While loop

The Python while loop allows a part of the code to be executed until the given condition returns
false. It is also known as a pre-tested loop.

It can be viewed as a repeating if statement. When we don't know the number of iterations
then the while loop is most effective to use.

The syntax is given below

1. while expression:    

2.     statements    

Here, the statements can be a single statement or a group of statements. The expression
should be any valid Python expression resulting in true or false. The true is any non-zero value
and false is 0.

While loop Flowchart


Example-1: Program to print 1 to 10 using while loop

1. i=1  

2. #The while loop will iterate until condition becomes false.  

3. While(i<=10):    

4.     print(i)   

5.     i=i+1   

Output:

7
8

10

Example -2: Program to print table of given numbers.

1. i=1    

2. number=0    

3. b=9    

4. number = int(input("Enter the number:"))    

5. while i<=10:    

6.     print("%d X %d = %d \n"%(number,i,number*i))    

7.     i = i+1    

Output:

Enter the number:10

10 X 1 = 10

10 X 2 = 20

10 X 3 = 30

10 X 4 = 40

10 X 5 = 50

10 X 6 = 60
10 X 7 = 70

10 X 8 = 80

10 X 9 = 90

10 X 10 = 100

2.13.1 Infinite while loop

If the condition is given in the while loop never becomes false, then the while loop will never
terminate, and it turns into the infinite while loop.

Any non-zero value in the while loop indicates an always-true condition, whereas zero indicates


the always-false condition. This type of approach is useful if we want our program to run
continuously in the loop without any disturbance.

Example 1

1. while (1):    

2.     print("Hi! we are inside the infinite while loop")  

Output:

Hi! we are inside the infinite while loop

Hi! we are inside the infinite while loop

Example 2

1. var = 1    

2. while(var != 2):    

3.     i = int(input("Enter the number:"))    
4.     print("Entered value is %d"%(i))    

Output:

Enter the number:10

Entered value is 10

Enter the number:10

Entered value is 10

Enter the number:10

Entered value is 10

Infinite time

2.13.2 Using else with while loop

Python allows us to use the else statement with the while loop also. The else block is executed
when the condition given in the while statement becomes false. Like for loop, if the while loop
is broken using break statement, then the else block will not be executed, and the statement
present after else block will be executed. The else statement is optional to use with the while
loop. Consider the following example.

Example 1

1. i=1   

2. while(i<=5):    

3.     print(i)    

4.     i=i+1    

5. else:  

6.     print("The while loop exhausted")    

Example 2

1. i=1    
2. while(i<=5):    

3.     print(i)    

4.     i=i+1    

5.     if(i==3):    

6.         break   

7. else:  

8.     print("The while loop exhausted")  

Output:

In the above code, when the break statement encountered, then while loop stopped its
execution and skipped the else statement.

Example-3 Program to print Fibonacci numbers to given limit

1. terms = int(input("Enter the terms "))  

2. # first two intial terms  

3. a = 0  

4. b = 1  

5. count = 0  

6.   

7. # check if the number of terms is Zero or negative  

8. if (terms <= 0):  

9.    print("Please enter a valid integer")  

10. elif (terms == 1):  

11.    print("Fibonacci sequence upto",limit,":")  
12.    print(a)  

13. else:  

14.    print("Fibonacci sequence:")  

15.    while (count < terms) :  

16.        print(a, end = ' ')  

17.        c = a + b  

18.        # updateing values  

19.        a = b  

20.        b = c  

21.      

22.     count += 1  

Output:

Enter the terms 10

Fibonacci sequence:

0 1 1 2 3 5 8 13 21 34

2.14 Conditional Statements

2.14.1 Python break statement

The break is a keyword in python which is used to bring the program control out of the loop.
The break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the
inner loop first and then proceeds to outer loops. In other words, we can say that break is used
to abort the current execution of the program and the control goes to the next line after the
loop.

The break is commonly used in the cases where we need to break the loop for a given
condition.
The syntax of the break is given below.

1. #loop statements  

2. break;   

Example 1

1. list =[1,2,3,4]  

2. count = 1;  

3. for i in list:  

4.     if i == 4:  

5.         print("item matched")  

6.         count = count + 1;  

7.         break  

8. print("found at",count,"location");  

Output:

item matched

found at 2 location

Example 2

1. str = "python"  

2. for i in str:  

3.     if i == 'o':  

4.         break  

5.     print(i);  

Output:
p

Example 3: break statement with while loop

1. i = 0;  

2. while 1:  

3.     print(i," ",end=""),  

4.     i=i+1;  

5.     if i == 10:  

6.         break;  

7. print("came out of while loop");  

Output:

0 1 2 3 4 5 6 7 8 9 came out of while loop

Example 3

1. n=2  

2. while 1:  

3.     i=1;  

4.     while i<=10:  

5.         print("%d X %d = %d\n"%(n,i,n*i));  

6.         i = i+1;  

7.     choice = int(input("Do you want to continue printing the table, press 0 for no?"))  

8.     if choice == 0:  
9.         break;      

10.     n=n+1  

Output:

2X1=2

2X2=4

2X3=6

2X4=8

2 X 5 = 10

2 X 6 = 12

2 X 7 = 14

2 X 8 = 16

2 X 9 = 18

2 X 10 = 20

Do you want to continue printing the table, press 0 for no?1


3X1=3

3X2=6

3X3=9

3 X 4 = 12

3 X 5 = 15

3 X 6 = 18

3 X 7 = 21

3 X 8 = 24

3 X 9 = 27

3 X 10 = 30

Do you want to continue printing the table, press 0 for no?0


2.14.2 Python continue Statement

The continue statement in Python is used to bring the program control to the beginning of the
loop. The continue statement skips the remaining lines of code inside the loop and start with
the next iteration. It is mainly used for a particular condition inside the loop so that we can skip
some specific code for a particular condition.The continue statement in Python is used to bring
the program control to the beginning of the loop. The continue statement skips the remaining
lines of code inside the loop and start with the next iteration. It is mainly used for a particular
condition inside the loop so that we can skip some specific code for a particular condition.

Syntax

1. #loop statements    

2. continue  

3. #the code to be skipped     

Flow Diagram
Consider the following examples.

Example 1

1. i = 0                     

2. while(i < 10):                

3.    i = i+1  

4.    if(i == 5):  

5.       continue  

6.    print(i)  

Output:

10

Observe the output of above code, the value 5 is skipped because we have provided the if
condition using with continue statement in while loop. When it matched with the given
condition then control transferred to the beginning of the while loop and it skipped the value 5
from the code.

Let's have a look at another example:

Example 2
1. str = "JavaTpoint"  

2. for i in str:  

3.     if(i == 'T'):  

4.         continue  

5.     print(i)  

Output:

2.14.3 Pass Statement

The pass statement is a null operation since nothing happens when it is executed. It is used in
the cases where a statement is syntactically needed but we don't want to use any executable
statement at its place.

For example, it can be used while overriding a parent class method in the subclass but don't
want to give its specific implementation in the subclass.

Pass is also used where the code will be written somewhere but not yet written in the program
file. Consider the following example.
Example

1. list = [1,2,3,4,5]    

2. flag = 0    

3. for i in list:    

4.     print("Current element:",i,end=" ");    

5.     if i==3:    

6.         pass    

7.         print("\nWe are inside pass block\n");    

8.         flag = 1    

9.     if flag==1:    

10.         print("\nCame out of pass\n");    

11.         flag=0   

Output:

Current element: 1 Current element: 2 Current element: 3

We are inside pass block

Came out of pass

Current element: 4 Current element: 5

Python Pass

In Python, the pass keyword is used to execute nothing; it means, when we don't want to
execute code, the pass can be used to execute empty. It is the same as the name refers to. It
just makes the control to pass by without executing any code. If we want to bypass any code
pass statement can be used.
It is beneficial when a statement is required syntactically, but we want we don't want to
execute or execute it later. The difference between the comments and pass is that, comments
are entirely ignored by the Python interpreter, where the pass statement is not ignored.

Suppose we have a loop, and we do not want to execute right this moment, but we will execute
in the future. Here we can use the pass.

Consider the following example.

Example - Pass statement

1. # pass is just a placeholder for  

2. # we will adde functionality later.  

3. values = {'P', 'y', 't', 'h','o','n'}  

4. for val in values:  

5.     pass  

Example - 2:

1. for i in [1,2,3,4,5]:   

2.     if(i==4):  

3.         pass  

4.         print("This is pass block",i)  

5.     print(i)  

Output:

1. 1  

2. 2  

3. 3  

4. This is pass block 4  
5. 4  

6. 5  

We can create empty class or function using the pass statement.

1. # Empty Function  

2. def function_name(args):  

3.     pass  

4. #Empty Class  

5. class Python:  

6.     pass  

You might also like