Sie sind auf Seite 1von 52

PYTHON

ACKNOWLEDGMENT
Industrial Training ​is an important aspect of engineering. Through these Industrial Training,
the student learns to conduct himself herself in the environment of the industry. This is also
helpful in acquiring the required technical knowledge. I have gone through Industrial
Training in ​PYTHON​. I really feel the deepest gratitude towards my guide, ​SUNIT JAISWAL of
LTBP Training ​Institute and ​Buddha Institute of Technology for providing Lab for Training.
Sunit Sir immense love has been of great value to me. Without his unrivaled guidance,
constant encouragement, painstaking efforts, keen observance, benevolent attention the
present dissertation work would have remained futile. He really has the ability to make as
laid back person the foremost one.

I would like to express my gratitude towards my parents and member of Buddha Institute of
technology for their kind cooperation and encouragement which helps me in completion of
this Industrial Training

I am also thankful to ​Mr. Sandeep Singh,​ ​Seminar Co-ordinator.

Finally, we should not miss the opportunity to record our gratitude to the numerous
teachers for their very useful suggestions and guidance without which this project should
not have come into being.

Last but not the least, we bow down to the ALMIGHTY GOD, without whos​e blessing this work
won't be a reality

AKASH CHAUDHARY
ECE 4​th​ year

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​1


PYTHON
TABLE OF CONTENT

CHAPTER 1 4

INTRODUCTION 4
1.1 PYTHON 2 4
1.2. PYTHON 3 4
1.3. Language Feature 5
1.4. Python vs JAVA 6
1.5. Similarity with Java 6
1.6. Current Applications of Python 6
1.7. Statement, Indentation and Comment in Python 6
1.7.1. Statements 6
1.7.2. Indentation 7
1.7.3. Comments 7
1.8. Python Language advantages and applications 8
1.8.1. Advantages : 8
1.8.2. Applications : 8
1.8.3. Organizations using Python : 9
CHAPTER 2 10

DATA STRUCTURES 10
2.1. String 10
2.2. Python List 11
2.3. Python Tuples 14
2.4. Python Sets 17
2.4.1. Frozen sets 22
2.5. Python Dictionary 24
CHAPTER 3 28

CONTROL FLOW STATEMENT 28


3.1. Loops in python 28
3.1.1. While Loop:- 28
3.1.2. For in Loop: 28
3.2. Looping Techniques in Python 29
3.2.1. Using enumerate(): 29
3.2.2. Using zip() 30
3.2.3. Using items(): 30
3.2.4. Using sorted() 30
3.2.5. Using reversed() 31

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​2


PYTHON

CHAPTER 4 32

FUNCTIONS 32
4.1. Pass by Reference or pass by value 32
4.2. Default arguments 32
4.3. Keyword arguments 33
4.4. Variable-length arguments 33
4.5. Class Method 33
4.6. Static Method 34
4.7.7. Class method vs Static Method 34

CHAPTER 5 36

OBJECT ORIENTED PROGRAMMING 36


5.1. Classes 36
5.2. Methods 37
5.3. Inheritance 37
5.4. Iterators 39
5.5. Generators 39
5.6. The self 40
5.7. The __init__ method 41
5.8. Class and Instance Variables (Or attributes) 41
5.9. Data hiding 42
5.10. Printing Objects 43
5.11. Inheritance 44
5.12. Polymorphism in Python 49
5.13. Polymorphism with Inheritance: 50

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​3


PYTHON
CHAPTER 1
INTRODUCTION
Python is a widely-used general-purpose, high-level programming language. It was initially
designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It
was mainly developed for emphasis on code readability, and its syntax allows programmers
to express concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more
efficiently.
There are two major Python versions-
Python 2
Python 3

1.1 PYTHON 2
Python 2.0, released in October 2000, introduced list comprehensions, a feature borrowed
from the functional programming languages SETL and Haskell. Python's syntax for this
construct is very similar to Haskell's, apart from Haskell's preference for punctuation
characters and Python's preference for alphabetic keywords. Python 2.0 also introduced a
garbage collection system capable of collecting reference cycles

1.2. PYTHON 3
Python 3.0 was released on December 3, 2008. It was designed to rectify fundamental
design flaws in the language—the changes required could not be implemented while
retaining full backward compatibility with the 2.x series, which necessitated a new major
version number. The guiding principle of Python 3 was: "reduce feature duplication by
removing old ways of doing things".
.
Nonetheless, Python 3.0 remained a multi-paradigm language. Coders could still follow
object-oriented, structured, and functional programming paradigms, among others, but
within such broad choices, the details were intended to be more obvious in Python 3.0 than
they were in Python 2.x.

Reason for increasing popularity


1. Emphasis on code readability, shorter codes, ease of writing
2. Programmers can express logical concepts in fewer lines of code in
comparison to languages such as C++ or Java.
3. Python supports multiple programming paradigms, like object-oriented,
imperative and functional programming or procedural.
4. There exists inbuilt functions for almost all of the frequently used concepts.

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​4


PYTHON
1.3. Language Feature

1. Interpreted
a. There are no separate compilation and execution steps like C and C++
b. Directly run the program from the source code.
c. Internally, Python converts the source code into an intermediate form
called bytecodes which is then translated into the native language of
the specific computer to run it​.

2. Platform Independent
a. Python programs can be developed and executed on multiple
operating system platforms.
b. Python can be used on Linux, Windows, Macintosh, Solaris and many
more.

3. High-level Language
a. In Python, no need to take care of low-level details such as managing
the memory used by the program​.
4. Simple
a. Closer to the English language; Easy to Learn
b. More emphasis on the solution to the problem rather than the syntax
5. Embeddable
a. Python can be used within C/C++ program to give scripting capabilities
for the program’s users.
6. Robust:
a. Exceptional handling features
b. Memory management techniques inbuilt
7. Rich Library Support
a. The Python Standard Library is vary vast.
b. Known as the “batteries included” philosophy of Python; It can help
do various things involving regular expressions, documentation
generation, unit testing, threading, databases, web browsers, CGI,
email, XML, HTML, WAV files, cryptography, GUI and many more.
c. Besides the standard library, there are various other high-quality
libraries such as the Python Imaging Library which is an amazingly
simple image manipulation library.

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​5


PYTHON
1.4. Python vs JAVA

Python Java

Dynamically Typed Statically Typed

Concise Verbose

Compact Less Compact

Uses Indentation for structuring


Uses braces for structuring code
code

1.5. Similarity with Java

● Require some form of runtime on your system (JVM/Python runtime)


● Can probably be compiled to executables without the runtime (this is
situational, none of them are designed to work this way)

1.6. Current Applications of Python


1. A number of Linux distributions use installers written in Python example in
Ubuntu we have the Ubiquity
2. Python has seen extensive use in the information security industry, including in
exploit development.
3. Raspberry Pi– single-board computer uses Python as its principal
user-programming language.
4. Python is now being used in Game Development areas also.
Pros:
1. Ease of use
2. Multi-paradigm Approach
Cons:

1. Slow speed of execution compared to C, C++.


2. Absence from mobile computing and browsers.
3. For the C, C++ programmers switching to python can be irritating as the language
requires proper indentation of code. Certain variable names commonly used like
sum are functions in python. So C, C++ programmers have to look out for these.

1.7. Statement, Indentation and Comment in Python


1.7.1. Statements
Instructions written in the source code for execution are called statements. There are
different types of statements in the Python programming language like Assignment

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​6


PYTHON
statement, Conditional statement, Looping statements etc. These all help the user to get the
required output. For example, n = 50 is an assignment statement.
Multi-Line Statements: ​Statements in Python can be extended to one or more lines using
parentheses (), braces {}, square brackets [], semi-colon (;), continuation character slash (\).
When the programmer needs to do long calculations and cannot fit his statements into one
line, one can make use of these characters.
Example :

1.7.2. Indentation
A block is a combination of all these statements. Block can be regarded as the grouping of
statements for a specific purpose. Most of the programming languages like C, C++, Java use
braces { } to define a block of code. One of the distinctive features of Python is its use of
indentation to highlight the blocks of code. Whitespace is used for indentation in Python. All
statements with the same distance to the right belong to the same block of code. If a block
has to be more deeply nested, it is simply indented further to the right. You can understand
it better by looking at the following lines of code:

1.7.3. Comments
Python developers often make use of the comment system as, without the use of it, things
can get real confusing, real fast. Comments are the useful information that the developers
provide to make the reader understand the source code. It explains the logic or a part of it
used in the code. Comments are usually helpful to someone maintaining or enhancing your
code when you are no longer around to answer questions about it. These are often cited as
a useful programming convention that does not take part in the output of the program but
improves the readability of the whole program. There are two types of comment in Python:
Single line comments: Python single line comment starts with hashtag symbol with no white
spaces (#) and lasts till the end of the line. If the comment exceeds one line then put a
hashtag on the next line and continue the comment. Python’s single-line comments are

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​7


PYTHON
proved useful for supplying short explanations for variables, function declarations, and
expressions.

Multi-line string as comment: Python multi-line comment is a piece of text enclosed in a


delimiter (""") on each end of the comment. Again there should be no white space between
delimiter ("""). They are useful when the comment text does not fit into one line; therefore
needs to span across lines. Multi-line comments or paragraphs serve as documentation for
others reading your code. See the following code snippet demonstrating multi-line
comment:

1.8. Python Language advantages and applications


It is used in many organizations as it supports multiple programming paradigms. It also
performs automatic memory management​.

1.8.1. Advantages :
1) Presence of third-party modules
2) Extensive support libraries(NumPy for numerical calculations, Pandas for data analytics
etc)
3) Open source and community development
4) Easy to learn
5) User-friendly data structures
6) High-level language
7) Dynamically typed language(No need to mention data type based on value assigned, it
takes data type)
8) Object-oriented language
9) Portable and Interactive
1.8.2. Applications :
1) ​GUI based desktop applications(Games, Scientific Applications)
2) Web frameworks and applications
3) Enterprise and Business applications
4) Operating Systems
5) Language Development
6) Prototyping

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​8


PYTHON
1.8.3. Organizations using Python :
1​) Google(Components of Google spider and Search Engine)
2) Yahoo(Maps)
3) YouTube
4) Mozilla
5) Dropbox
6) Microsoft
7) Cisco

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​9


PYTHON
CHAPTER 2
DATA STRUCTURES
Data structure is a data organization, management, and storage format that enables
efficient​ access and modifica​tion.there are six data types in python. They are.
● Strings
● List
● Tuples
● Sets
● Dictionary
● Arrays
2.1. String
​Strings ​are arrays of bytes representing Unicode characters. However, Python does not
have a character data type, a single character is simply a string with a length of 1. Square
brackets can be used to access elements of the string.

Creating a String
Strings in Python can be created using single quotes or double quotes or even triple quotes

Strings can be indexed (subscripted), with the first character having index 0. There is no
separate character type; a character is simply a string of size one:

Indices may also be negative numbers, to start counting from the right:

Note that since -0 is the same as 0, negative indices start from -1. In addition to indexing,
slicing is also supported. While indexing is used to obtain individual characters, slicing allows
you to obtain substring:

Note how the start is always included, and the end always excluded. This makes sure that s[:
i] + s[i:] is always equal to s:

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​10


PYTHON
Python strings cannot be changed — they are immutable. Therefore, assigning to an indexed
position in the string results in an error:

If you need a different string, you should create a new one:

The built-in function len() returns the length of a string:

2.2. Python List


Lists ​are just like the arrays, declared in other languages. Lists need not be homogeneous
always which makes it the most powerful tool in Python. A single list may contain DataTypes
like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered
even after their creation.
List in Python are ordered and have a definite count. The elements in a list are indexed
according to a definite sequence and the indexing of a list is done with 0 being the first
index. Each element in the list has its definite place in the list, which allows duplicating of
elements in the list, with each element having its own distinct place and credibility
Example:-

-
Like strings (and all other built-in sequence types), lists can be indexed and sliced:

Lists also support operations like concatenation:

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​11


PYTHON
Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change
their content:

You can also add new items at the end of the list, by using the append() method (we will see
more about methods later):

The built-in function len() also applies to lists:

Assignment to slices is also possible, and this can even change the size of the list or clear it

entirely:
It is possible to nest lists (create lists containing other lists), for example,:

List Method​s

FUNCTION DESCRIPTION

Append() Add an element to the end of the list

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​12


PYTHON
Extend() Add all elements of a list to the another list

Insert() Insert an item at the defined index

Remove() Removes an item from the list

Pop() Removes and returns an element at the given index

Clear() Removes all items from the list

Index() Returns the index of the first matched item

Returns the count of number of items passed as an


Count()
argument

Sort() Sort items in a list in ascending order

Reverse() Reverse the order of items in the list

copy() Returns a copy of the list

Built-in functions with List


FUNCTION DESCRIPTION

apply a particular function passed in its argument to


reduce() all of the list elements stores the intermediate result
and only returns the final summation value

sum() Sums up the numbers in the list

Returns an integer representing the Unicode code


ord()
point of the given Unicode character

This function returns 1 if the first list is “greater” than


cmp()
the second list

max() return maximum element of given list

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​13


PYTHON

min() return minimum element of given list

all() Returns true if all elements are true or if list is empty

return true if any element of the list is true. if list is


any()
empty, return false

len() Returns length of the list or size of the list

enumerate() Returns enumerate object of list

apply a particular function passed in its argument to


accumulate() all of the list elements returns a list containing the
intermediate results

filter() tests if each element of a list true or not

returns a list of the results after applying the given


map()
function to each item of a given iterable

This function can have any number of arguments but


lambda() only one expression, which is evaluated and
returned.

2.3. Python Tuples

Tuple is a collection of Python objects much like a list. The sequence of values stored in a
tuple can be of any type, and they are indexed by integers. The important difference
between a list and a tuple is that tuples are immutable. Also, Tuples are hashable whereas
lists are not.
Values of a tuple are syntactically separated by ‘commas’. Although it is not necessary, it is
more common to define a tuple by closing the sequence of values in parentheses. This helps
in understanding the Python tuples more easily.
Tuples are immutable, and usually, they contain a sequence of heterogeneous elements
that are accessed via unpacking or indexing (or even by attribute in the case of named
tuples). Lists are mutable, and their elements are usually homogeneous and are accessed by
iterating over the list.
Creating a Tuple
In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or
without the use of parentheses for grouping of data sequence. Tuples can contain any

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​14


PYTHON
number of elements and of any datatype (like strings, integers, list, etc.). Tuples can also be
created with a single element, but it is a bit tricky. Having one element in the parentheses is
not sufficient, there must be a trailing ‘comma’ to make it a tuple.
Note – ​The creation of Python tuple without the use of parentheses is known as Tuple
Packing.

Concatenation of Tuples
The concatenation of tuple is the process of joining two or more Tuples. Concatenation is
done by the use of ‘+’ operator. Concatenation of tuples is done always from the end of the
original tuple. Other arithmetic operations do not apply on Tuples.
Note- Only same datatypes can be combined with concatenation, an error arises if a list and
a tuple are combined.

Slicing of Tuple
Slicing of a Tuple is done to fetch a specific range or slice of sub-elements from a Tuple.
Slicing can also be done to lists and arrays. Indexing in a list results in fetching a single
element whereas Slicing allows us to fetch a set of elements.
Note-​ Negative Increment values can also be used to reverse the sequence of Tuples
Example:-

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​15


PYTHON
Output:-

Deleting a Tuple
Tuples are immutable and hence they do not allow deletion of a part of it. The entire tuple
gets deleted by the use of del() method.
Note-​ Printing of Tuple after deletion results to an Error.
Example:-

Built-In Methods
BUILT-IN
DESCRIPTION
FUNCTION

Returns true if all elements are true or if tuple is


all()
empty

return true if any element of the tuple is true. if tuple


any()
is empty, return false

len() Returns length of the tuple or size of the tuple

enumerate() Returns enumerate object of tuple

max() return maximum element of given tuple

min() return minimum element of given tuple

sum() Sums up the numbers in the tuple

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​16


PYTHON

input elements in the tuple and return a new sorted


sorted()
list

tuple() Convert an iterable to a tuple.

2.4. Python Sets

In Python, Set is an unordered collection of data type that is iterable, mutable and has no
duplicate elements. The order of elements in a set is undefined though it may consist of
various elements.
The major advantage of using a set, as opposed to a list, is that it has a highly optimized
method for checking whether a specific element is contained in the set.
Creating a Set
Sets can be created by using the built-in set() function with an iterable object or a sequence
by placing the sequence inside curly braces, separated by ‘comma’.
Note – ​A set cannot have mutable elements like a list, set or dictionary, as its elements.

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​17


PYTHON
Example:-

Output:-

A set contains only unique elements but at the time of set creation, multiple duplicate
values can also be passed. Order of elements in a set is undefined and is unchangeable. Type
of elements in a set need not be the same, various mixed-up data type values can also be
passed to the set.

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​18


PYTHON
Adding Elements to a Set
Using add() method
Elements can be added to the Set by using built-in ​add() function. Only one element at a
time can be added to the set by using add() method, loops are used to add multiple
elements at a time with the use of add() method.
Note – Lists cannot be added to a set as elements because Lists are not hashable whereas
Tuples can be added because tuples are immutable and hence Hashable.
Example:-

Output:-

Using update() method


For the addition of two or more elements Update() method is used. The update() method
accepts lists, strings, tuples as well as other sets as its arguments. In all of these cases,
duplicate elements are avoided.
Example:-

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​19


PYTHON

Output:-

Accessing a Set
Set items cannot be accessed by referring to an index, since sets are unordered the items
has no index. But you can loop through the set items using a for loop, or ask if a specified
value is present in a set, by using the in keyword.
Example:-

Output:-

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​20


PYTHON
Removing elements from the Set
Using remove() method or discard() method
Elements can be removed from the Set by using built-in remove() function but a KeyError
arises if the element doesn’t exist in the set. To remove elements from a set without
KeyError, use discard(), if the element doesn’t exist in the set, it remains unchanged.
Example:-

-Output:-

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​21


PYTHON
Using pop() method
Pop() function can also be used to remove and return an element from the set, but it
removes only the last element of the set.
Note – ​If the set is unordered then there’s no such way to determine which element is
popped by using the pop() function.
Example:​-

Output:-

2.4.1. Frozen sets


F​rozen sets in Python are immutable objects that only support methods and operators that
produce a result without affecting the frozen set or sets to which they are applied. While
elements of a set can be modified at any time, elements of the frozen set remain the same
after creation.

If no parameters are passed, it returns an empty frozenset.


Example:-

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​22


PYTHON
Output:-

Set Methods
FUNCTION DESCRIPTION

add() Adds an element to a set

Removes an element from a set.


remove() If the element is not present in
the set, raise a KeyError

clear() Removes all elements form a set

copy() Returns a shallow copy of a set

Removes and returns an arbitary


pop() set element. Raise KeyError if the
set is empty

Updates a set with the union of


update()
itself and others

Returns the union of sets in a


union()
new set

Returns the difference of two or


difference()
more sets as a new set

Removes all elements of another


difference_update()
set from this set

Removes an element from set if it


discard() is a member. (Do nothing if the
element is not in set)

Returns the intersection of two


intersection()
sets as a new set

Updates the set with the


intersection_update()
intersection of itself and another

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​23


PYTHON
Returns True if two sets have a
isdisjoint()
null intersection

Returns True if another set


issubset()
contains this set

Returns True if this set contains


issuperset()
another set

Returns the symmetric difference


symmetric_difference()
of two sets as a new set

Updates a set with the symmetric


symmetric_difference_update()
difference of itself and another

2.5. Python Dictionary

Dictionary in Python is an unordered collection of data values, used to store data values like
a map, which unlike other Data Types that hold only single value as an element, Dictionary
holds key: value pair. Key-value is provided in the dictionary to make it more optimized.
Each key-value pair in a Dictionary is separated by a colon:, whereas each key is separated
by a ‘comma’.
A Dictionary in Python works similar to the Dictionary in the real world. Keys of a Dictionary
must be unique and of ​immutable d ​ ata type such as Strings, Integers, and tuples, but the
key-values can be repeated and be of any type.
Note – ​Keys in a dictionary doesn’t allow Polymorphism.
Creating a Dictionary
In Python, a Dictionary can be created by placing the sequence of elements within curly ​{}
braces, separated by ‘comma’. Dictionary holds a pair of values, one being the Key and the
other corresponding pair element being its ​Key: value​. Values in a dictionary can be of any
data type and can be duplicated, whereas keys can’t be repeated and must be ​immutable.​
Note – ​Dictionary keys are case sensitive, same name but different cases of Key will be
treated distinctly. Example:-

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​24


PYTHON

Output:-

Accessing elements from a Dictionary


In order to access the items of a dictionary refer to its key name. Key can be used inside
square brackets. There is also a method called ​get() that will also help in accessing the
element from a dictionary.
Example:-

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​25


PYTHON

Output:-

Dictionary Methods
METHODS DESCRIPTION

They copy() method returns a shallow


copy()
copy of the dictionary.

The clear() method removes all items


clear()
from the dictionary.

Removes and returns an element from


pop()
a dictionary having the given key.

Removes the arbitrary key-value pair


popitem() from the dictionary and returns it as
tuple.

It is a conventional method to access a


get()
value for a key.

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​26


PYTHON
returns a list of all the values available
dictionary_name.values()
in a given dictionary.

Produces a printable string


str()
representation of a dictionary.

Adds dictionary dict2’s key-values pairs


update()
to dict

Set dict[key]=default if key is not


setdefault()
already in dict

keys() Returns list of dictionary dict’s keys

Returns a list of dict’s (key, value) tuple


items()
pairs

Returns true if key in dictionary dict,


has_key()
false otherwise

Create a new dictionary with keys from


fromkeys()
seq and values set to value.

type() Returns the type of the passed variable.

Compares elements of both dict.


cmp()

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​27


PYTHON
CHAPTER 3
CONTROL FLOW STATEMENT

3.1. Loops in python


Python programming language provides the following types of loops to handle looping
requirements. Python provides three ways for executing the loops. While all the ways
provide similar basic functionality, they differ in their syntax and condition checking time.
3.1.1. While Loop:​-
In python, while loop is used to execute a block of statements repeatedly until a given
condition is satisfied. And when the condition becomes false, the line immediately after the
loop in program is executed.
Syntax :

In Python, all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements.Example:-

Output:-

Using else statement with while loops: As discussed above, while loop executes the block
until a condition is satisfied. When the condition becomes false, the statement immediately
after the loop is executed.
The else clause is only executed when your while condition becomes false. If you break out
of the loop, or if an exception is raised.

3.1.2. For in Loop:


For loops are used for sequential traversal. For example: traversing a list or string or array
etc. In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for in” loop which
is similar to for each loop in other languages. Let us learn how to use for in loop for
sequential traversals.
Syntax:

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​28


PYTHON

output:-

3.2. Looping Techniques in Python

Python supports various looping techniques by certain inbuilt functions, in various


sequential containers. These methods are primarily very useful in competitive programming
and also in various project which require a specific technique with loops maintaining the
overall structure of code.

Where they are used?


Different looping techniques are primarily useful in the places where we don’t need to
actually manipulate the structure and ordering of overall container, rather only print the
elements for a single-use instance, no in-place change occurs in the container. This can also
be used in instances to save time.
Different looping techniques using Python data structures are:

3.2.1. Using enumerate():


enumerate() is used to loop through the containers printing the index number along with
the value present in that particular index
Example:-

Output:-

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​29


PYTHON
3.2.2. Using zip()
zip() is used to combine 2 similar containers(list-list or dict-dict) printing the values
sequentially. The loop exists only till the smaller container ends.
Example:-

.
Output:-

3.2.3. Using items():


items() performs the similar task on dictionary as iteritems() but have certain
disadvantages when compared with iteritems().
○ It is very time-consuming. Calling it on large dictionaries consumes
quite a lot of time.
○ It takes a lot of memory. Sometimes it takes double the memory
when called on a dictionary.
Example:-

Output:-

3.2.4. Using sorted()


sorted() is used to print the container is sorted order. It doesn’t sort
the container, but just prints the container in sorted order for

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​30


PYTHON
instance. Use of set() can be combined to remove duplicate
occurrences.
Example:-

Output :-

3.2.5. Using reversed()


reversed() is used to print the values of container in the descending order as
declared.
Example:-

Output:-

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​31


PYTHON
CHAPTER 4
FUNCTIONS

A function is a set of statements that take inputs, do some specific computation and
produces output. The idea is to put some commonly or repeatedly done task together and
make a function so that instead of writing the same code again and again for different
inputs, we can call the function.
Python provides built-in functions like print(), etc. but we can also create your own
functions. These functions are called user-defined functions.

Output:-

4.1. Pass by Reference or pass by value


One important thing to note is, in Python every variable name is a reference. When we pass
a variable to a function, a new reference to the object is created. Parameter passing in
Python is same as reference passing in Java.
4.2. Default arguments
A default argument is a parameter that assumes a default value if a value is not provided in
the function call for that argument.The following example illustrates Default arguments.

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​32


PYTHON
Output:-

4.3. Keyword arguments


The idea is to allow the caller to specify the argument name with values so that the caller
does not need to remember the order of parameters

.
Output:-

4.4. Variable-length arguments


We can have both normal and keyword variable number of arguments. Please see this for
details.

Output:-

4.5. Class Method

The @classmethod decorator is a builtin function decorator that is an expression that gets
evaluated after your function is defined. The result of that evaluation shadows your function
definition.
A class method receives the class as implicit first argument, just like an instance method
receives the instance.

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​33


PYTHON
● A class method is a method which is bound to the class and not the object of
the class.
● They have access to the state of the class as it takes a class parameter that
points to the class and not the object instance.
● It can modify a class state that would apply across all the instances of the class.
For example, it can modify a class variable that will be applicable to all the
instances.

4.6. Static Method

A static method does not receive an implicit first argument.


● A static method is also a method which is bound to the class and not the object
of the class.
● A static method can’t access or modify class state.
● It is present in a class because it makes sense for the method to be present in
class.

4.7.7. Class method vs Static Method

● A class method takes cls as the first parameter while a static method needs no
specific parameters.
● A class method can access or modify class state while a static method can’t
access or modify it.
● In general, static methods know nothing about class state. They are utility type
methods that take some parameters and work upon those parameters. On the
other hand class methods must have class as a parameter.
● We use @classmethod decorator in python to create a class method and we
use @staticmethod decorator to create a static method in python
When to use what?
● We generally use class method to create factory methods. Factory methods
return class object ( similar to a constructor ) for different use cases.
● We generally use static methods to create utility functions.

How to define a class method and a static method?


To define a class method in python, we use @classmethod decorator and to define a static
method we use @staticmethod decorator.
Let us look at an example to understand the difference between both of them. Let us say we
want to create a class Person. Now, python doesn’t support method overloading like C++ or
Java so we use class methods to create factory methods. In the below example we use a
class method to create a person object from birth year.
As explained above we use static methods to create utility functions. In the below example
we use a static method to check if a person is an adult or not.

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​34


PYTHON

Output:-

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​35


PYTHON
CHAPTER 5
OBJECT ORIENTED PROGRAMMING

Object-oriented programming: As the name suggests, Object-Oriented Programming or


OOPs refers to languages that use objects in programming. Object-oriented programming
aims to implement real-world entities like inheritance, hiding, polymorphism etc in
programming. The main aim of OOP is to bind together the data and the functions that
operate on them so that no other part of the code can access this data except that function.

OOPs Concepts:

5.1. Classes
Just like every other Object Oriented Programming language Python supports classes. Let’s
look at some points on Python classes.
● Classes are created by keyword class.
● Attributes are the variables that belong to class.
● Attributes are always public and can be accessed using dot (.) operator. Eg.: My
class.My attribute

Output:-

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​36


PYTHON
5.2. Methods

Method is a bunch of code that is intended to perform a particular task in your Python’s
code.
● The function that belongs to a class is called a Method.
● All methods require ‘self’ parameter. If you have coded in other OOP language
you can think of ‘self’ as the ‘this’ keyword which is used for the current object.
It unhides the current instance variable.’self’ mostly work like ‘this’.
● ‘def’ keyword is used to create a new method.

Output:-

5.3. Inheritance
Inheritance is defined as a way in which a particular class inherits features from its base
class. Base class is also known as ‘Superclass’ and the class which inherits from the
Superclass is knows as ‘Subclass​’

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​37


PYTHON

As shown in the figure the Derived class can inherit features from its base class, also it can
define its own features too.

Output:-

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​38


PYTHON
5.4. Iterators
Iterators are objects that can be iterated upon.
● Python uses the __iter__() method to return an iterator object of the class.
● The iterator object then uses the __next__() method to get the next item.
● for loops stops when StopIteration Exception is raised.

Output:-

5.5. Generators
● Another way of creating iterators.
● Uses a function rather than a separate class
● Generates the background code for the next() and iter() methods
● Uses a special statement called yield which saves the state of the generator
and set a resume point for when next() is called again.

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​39


PYTHON

Output:-

5.6. The self


1. Class methods must have an extra first parameter in method definition. We do
not give a value for this parameter when we call the method, Python provides
it
2. If we have a method which takes no arguments, then we still have to have one
argument – the self. See fun() in above simple example.
3. This is similar to this pointer in C++ and this reference in Java.
When we call a method of this object as myobject.method(arg1, arg2), this is automatically
converted by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self
is about.

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​40


PYTHON
5.7. The __init__ method
The __init__ method is similar to constructors in C++ and Java. It is run as soon as an object
of a class is instantiated. The method is useful to do any initialization you want to do with
your object.

Output:-

5.8. Class and Instance Variables (Or attributes)


In Python, instance variables are variables whose value is assigned inside a constructor with
self.

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​41


PYTHON
Output:-

5.9. Data hiding

In Python, we use double underscore (Or __) before the attributes name and those
attributes will not be directly visible outside.

Output:-

In the above program, we tried to access hidden variable outside the class using object and
it threw an exception.

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​42


PYTHON
We can access the value of hidden attribute by a tricky syntax:

Output:-

Private methods are accessible outside their class, just not easily accessible. ​Nothing in
Python is truly private; internally​, the names of private methods and attributes are
mangled and unmangled on the fly to make them seem inaccessible by their given names

5.10. Printing Objects

Printing objects gives us information about objects we are working with. In C++, we can do
this by adding a friend ostream& operator << (ostream&, const Foobar&) method for the
class. In Java, we use toString() method. In python this can be achieved by using __repr__ or
__str__ methods.

Output:

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​43


PYTHON

5.11. Inheritance
One of the major advantages of Object-Oriented Programming is re-use. Inheritance is one
of the mechanisms to achieve the same. In inheritance, a class (usually called superclass) is
inherited by another class (usually called subclass). The subclass adds some attributes to the
superclass.
Below is a sample Python program to show how inheritance is implemented in Python.

Output:-

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​44


PYTHON
How to check if a class is subclass of another?
Python provides a function issubclass() that directly tells us if a class is subclass of another
class.

Output:-

What is object class?


Like Java Object class, in Python (from version 3.x), object is root of all classes.
In Python 3.x, “class Test(object)” and “class Test” are same.
In Python 2.x, “class Test(object)” creates a class with object as parent (called new style
class) and “class Test” creates old style class (without object parent).

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​45


PYTHON
Does Python support Multiple Inheritance?
Unlike Java and like C++, Python supports multiple inheritance. We specify all parent classes
as comma-separated list in bracket.

Output:-

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​46


PYTHON
How to access parent members in a subclass?
Using Parent class name

Output:​-

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​47


PYTHON
Using super()
We can also access parent class members using super.

Output:-

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​48


PYTHON
5.12. Polymorphism in Python
The word polymorphism means having many forms. In programming, polymorphism means
same function name (but different signatures) being uses for different types.
Example of inbuilt polymorphic functions :

Output:-

Polymorphism with class methods:


Below code shows how python can use two different class types, in the same way. We
create a for loop that iterates through a tuple of objects. Then call the methods without
being concerned about which class type each object is. We assume that these methods
actually exist in each class.

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​49


PYTHON

Output:-

5.13. Polymorphism with Inheritance:


In Python, Polymorphism lets us define methods in the child class that have the same name
as the methods in the parent class. In inheritance, the child class inherits the methods from
the parent class. However, it is possible to modify a method in a child class that it has
inherited from the parent class. This is particularly useful in cases where the method
inherited from the parent class doesn’t quite fit the child class. In such cases, we
re-implement the method in the child class. This process of re-implementing a method in
the child class is known as ​Method Overriding​.

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​50


PYTHON

Output:-

Polymorphism with a Function and objects:


It is also possible to create a function that can take any object, allowing for polymorphism.
In this example, let’s create a function called “func()” which will take an object which we will
name “obj”. Though we are using the name ‘obj’, any instantiated object will be able to be
called into this function. Next, lets give the function something to do that uses the ‘obj’
object we passed to it. In this case lets call the three methods, viz., capital(), language() and
type(), each of which is defined in the two classes ‘India’ and ‘USA’. Next, let’s create
instantiations of both the ‘India’ and ‘USA’ classes if we don’t have them already. With
those, we can call their action using the same func() function:

Implementing Polymorphism with a Function

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​51


PYTHON

Output:

Dept. of EC, July-Dec 2019 AKASH CHAUDHARY 1652531004 Page ​52