0% found this document useful (0 votes)
249 views

A Beginner - S Guide To Python

Phyton

Uploaded by

maracaverik
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
249 views

A Beginner - S Guide To Python

Phyton

Uploaded by

maracaverik
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 120

About the Author

Abhijit Tripathy is the founder of eduAlgo organization as well as the creator of


the algorithm python software package, named as eduAlgo. His python
package has crossed a mark of 10000 downloads within 100 days of release on
PyPI (Python Packaging Index). He is a python developer as well as the chief
editor of the e-magazine named "The Developer Quest", that aims to serve as a
companion to the students and professionals in the software industry. Other
than these, he is a young entrepreneur who loves to spend time in solitude and
mentor students.

Abhijit has a demonstrated history of leading technical communities,


participating in programming competitions and hackathons. He has been a part
of 10+ opensource programs and competitions in India as a mentor as well as a
participant. More than 200 peoples have been mentored by him in different
opensource programs to get started with their contributions.

Currently, Abhijit is an undergraduate doing B.Tech(Computer Science &


Engineering) from Guru Ghasidas Vishwavidyalaya, Bilaspur,India . He also
holds a position of the Director of Strategic Cell, at dockship.io.
 
 
A beginner’s guide to 

Python 
 
ABHIJIT TRIPATHY 
Founder, eduAlgo  

 
 

First published in India in 2021 by Abhijit Tripathy


An imprint of independent publication

Copyright © Abhijit Tripathy. 2021

ISBN - 9798590685851

Typeset by
eduAlgo

 
 

" This book is dedicated to my family, that encouraged me to create it. "

 
References
Python is vast and modern, there are changes added to the programming
language every year. To follow the industry standards, some reference from
some already existing texts has been taken in this book. The following list
mentions each reference with the name of the author,

Python official documentation- by python.org


Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly
Beautiful World of Computers and Code by Zed A. Shaw
Automate the Boring Stuff with Python by Al Sweigart
Python programming problems by W3resources.com
Software Needed
This book follows the modern standard IDEs and software which are listed
below, all are free and opensource,

Editors/ IDEs (choose any one of the below)

VS Code from code.visualstudio.com


Atom Text Editor from atom.io
Jupyter Notebook & Anaconda Distribution from anaconda.com
(recommended)

Python 3.0+ version should be installed in your system to perform the coding
problems.

Version Control System like git is recommended but not a necessary requirement for
this book.
 
BOOK CONTENT
Sr.No Topic Name Page No

01 The FIrst Program 1

02 Numbers and Math 4

03 Variables and Printing 6

04 How to take input from users ? 13

05 Conditional Statements 15

06 Operators in python 19

07 Loops in python 22

08 File handling in python 27

09 Functions in python 30

10 Object Oriented Programming in python 35

11 Encapsulation in python 43

12 Inheritance in python 46

13 Python special functions 52

14 Exception handling in python 57

15 Python lists 61

16 Python tuples 71

17 Important methods in python strings 75

18 Python sets 77

19 Python dictionary 83

20 Programming problems in python 88

21 End of the book 108

 
The First Program
After setting up the editor the next step is to learn how to use the editor and
write the first program. So let's start.

Write a program to print your name using python


Thinking Procedure

As this is the first program, there should be a python executable file having
a .py extension in which we have to write the piece of code. So the first
step is to Making a .py file.
The program asks us to print something, means we have to use a
tool/technique which can be helpful in printing.

Moving further

The tool/technique which we are going to use for printing is known as print()
function in python which is an inbuilt function.

Let's look into a piece of code,

# program to print the name --> comment statement

print("My name is eduAlgo")

As it can be clearly seen in the above piece of code, it contains mainly three
components,

A line starting with # which is an indicator that the line is a comment


statement. A comment statement in programming is a statement which is
not executed when the compiler finds a delimiter. In python the delimiter is
#, also known as the octothorpe.

Here it is # program to print the name

A print() function which is a basic in-built function of python that helps in


printing something that's passed into the (....) of the function. Technically
this "something" is known as an object which we will be discussing in the
later part of the book when we will study about OOP.

Finally here comes something in the format of "......." , where we have


passed a text saying My name is eduAlgo . In python this is known as a
string.
1
Strings are combination of characters that helps in using text type objects in
programming. We will study an extensive topic on sting in our upcoming
chapters.

Let's now run the program, but here comes another study drill. As we are using
VS Code and we have to write a python program.

Here are the steps,

1. Create a new folder named Python_Programs.


2. Open your VS Code from this folder.
3. Create a file inside the folder by VS Code using the file creation option, let's
name the file as print_name.py.
4. Now inside the editor our work is to write the code and save it by ctrl+s.
5. Open up the terminal by using ctrl+`.
6. Navigate to the target folder of yours by using the command cd
<your_folder_name> in the terminal window. For example - cd
Python_Programs
7. Now execute the python program by using the command python
print_name.py and you are done.

Congratulations on completing your first program !

Exercise your way out

Q - Create a folder named "My_Bio_Data" and create a file named "bio_data.py"


inside it. Now your task is to print your bio data using print() function.

The bio data must contain the following,

Your name
Father's name
Mother's name
Date of birth
College/School/Company Name

Q - Write an essay on "Your favorite food" using python and print it to the
terminal.

Experiments with print()


As a developer, you are encouraged to perform different experiments with the
code and for that reasons, the experiment section answers will not be given
here directly.

Let's begin !
2
Experiment No - 01

# what will be the output ?


print("Amogh","Himanshi","Himanshu")

Experiment No - 02

# what will be the output ?


print("eduAlgo")
print("is")
print("Good")

Experiment No - 03

# what will be the output ?


print("eduAlgo",end=" ")
print("is",end=" ")
print("Good",end=" ")

Experiment No - 04

# what will be the output ?


print("eduAlgo",end="p")
print("is",end="l")
print("Good",end="a")

Experiment No - 05

# what will be the output ?


print("eduAlgo",end="p\n")
print("is",end="l\n")
print("Good",end="a\n")

PS - As you have witnessed above, the \n is the newline character that enables
the printout in the newline. Whenever the compiler encounter the newline
character the rest of the text just moves to a new line..

3
 

Numbers and Math


This exercise has lots of math symbols. Here are the names:

The symbol The Name The Work

+ plus Addition

- minus Subtraction

* asterisk Multiplication

% percent Division

< less-than compare

> greater-than compare

<= less-than equal-to compare

>= greater-than equal-to compare

Let's write a piece of code and check the outputs,

# normal maths
print("Apples", 3+4+2/3)   # fist-case
print("Banana", 10*6+2-3)  # second-case

# comparison
print(3 + 9 < 9 - 8)       # third-case

# modulus action
print(15 % 4)              # fourth-case

So, run the code now and try to understand the output

OUTPUT :

Apples 7.666666666666667
Banana 59
False
3

4
observations

In the first case & second case, the print() function has one string and one
mathematical expression separated by comma, where the mathematical
expression is solved by the normal BODMAS rule.
In the third case, we had a comparison and it returns Boolean datatype.
Which means binary (0 & 1) . True is treated as 1 and False is treated as 0.
In the fourth case we are dealing with the % operator which simply means
modulus but not percent here. In simpler words a % b means, the reminder
obtained when a is divided by b. For example here 15 is divided by 4 and
the reminder obtained is 3.

Exercise your way out

Q - You are given a list of marks(out of 100) for a student. Your aim is to print
the corresponding percentage of the student.

Mathematics - 50

Physics - 85

Social Science - 60

Also print the total aggregate percentage.

Experiments with numbers


Experiment No - 01

# what will be the output ?


print("eduAlgo"*5)

Experiment No - 02

# what will be the output ?


print(10*5)
print("10"*5)

Experiment No - 03

# what will be the output ?


print(3%10%2)

 
5
 

Variables and Printing


A variable is nothing more than a name for something in python, which can be
visualized as an empty bucket, where we can place any datatype.

For example,

# assigning integer datatype


a = 10                            # a is the variable name
b = 20

# assigning float datatype


p = 6.787                         # p is the variable name
q = 9.867

# assigning boolean datatype


clause = False                    # clause is a variable name
harm = True

# assigning character datatype


front = 'c'                       # front is a variable name
back = '\n'

# assigning string datatype


name = "eduAlgo"                  # name is a variable name
work = "digital publication"

Not only the in-built data types like float,integer,Boolean Etc. are the only
supported types, but also an user can define their own datatype which can be
further assigned to a variable name. These type of used defined data types are
known as class and instances of the class are known as objects. What makes
python so strong, is the ability of Object Oriented Programming. Technically
python is not an Object Oriented language, but it's a scripting language that
supports Object Oriented Programming. We will learn about OOP in the
upcoming chapters in great details.

Let's have some hands on programming problems, to learn simply.

6
Can we print out a variable at a certain position inside a
string(or a text in python) ?

Thinking Procedure

First of all we have to print, hence it's clear we are going to use print()
function for the work.
The question asks about some variables, definitely we have some variables
defined earlier, now we have a simpler work, i.e. format the printout text in
such a way that the variables appear in a certain position. But the question
is how to format ?

Code it out

There can be numerous methods is python to achieve this task as python is


quite flexible as well as it's growing at a large scale every year.

But, we are going to discuss three important methods, one of which is quite
faster than the other two

1. The % method

String objects have a built-in operation using the % operator, which you
can use to format strings. This method can be used for both one variable
and a multivariable conditions. For example,

# formatting string using %


name = "eduAlgo"
age = 21

print("I am %s" % name)


print("I am %s and I am %d years old" % (name,age))

Here is the output,

OUTPUT:

I am eduAlgo
I am eduAlgo and I am 21 years old

As you can see %s and %d are the format specifiers for string and integer
respectively. This method can be used with objects as well, see the code
below,

# declaring a BioData class


class BioData:
7
   def __init__(self,name,age):
       self.name = name
       self.age = age
 
# declaring an instance of the BioData class
person = BioData("eduAlgo",21)

# printing using %s only


print("My name is %s and I am %s years old" %
(person.name,person.age))

# printing using %s and %d


print("My name is %s and I am %s years old" %
(person.name,person.age))

The output is,

My name is eduAlgo and I am 21 years old


My name is eduAlgo and I am 21 years old

As you can see the format specifier thing doesn't matter in case of OOP.
Don't worry about the class and object thing at this point of time. It's just
for an illustration and example purpose, we will discuss more about OOP in
the upcoming chapters. Unfortunately, this kind of formatting isn’t great
because it is verbose and leads to errors, like not displaying tuples or
dictionaries correctly.

2. The str.format() method

It's similar to the % format method with a few syntax changes, but the
concept remains the same. We just have to plugin the proper value inside
the empty curly braces, {} of our text by passing proper parameters in the
.format() method.

Have a look at the code,

# using .format() method to format our string


name = "eduAlgo"
age = 21

print("I am {} and I am {} years old".format(name,age))


print("I am {} years old".format(age))
print("I am {}".format(name))

8
OUTPUT:

I am eduAlgo and I am 21 years old


I am 21 years old
I am eduAlgo

It's quite simple but have the similar problem as that of % formatting. It
leads to longer code writing and it requires the programmer to be cautious
while passing the parameters to the format() function.

But the aim of python is to make it easier, isn't it. Hence we have
something better than the above two.

3. The f-string method (faster and better)

According to the official python documentation,

F-strings provide a way to embed expressions inside string literals,


using a minimal syntax. It should be noted that an f-string is really an
expression evaluated at run time, not a constant value. In Python
source code, an f-string is a literal string, prefixed with f , which
contains expressions inside braces. The expressions are replaced with
their values.

Let's code it out,

# using f-string for string formatting


name = "eduAlgo"
age = 21

print(f"I am {name} and I am {age} years old")


print(f"I am {name}")

OUTPUT:

I am eduAlgo and I am 21 years old


I am eduAlgo

It's quite effective and easier than the other two methods. For the rest of
the book, we will be using the third method for our coding purpose.

9
Experiment your way out

Experiment No - 01

# what will be the output ?

fruit1 = "Apple"
price1 = 20

fruit2 = "Banana"
price2 = 30

fruit3 = "Orange"
price3 = 40

# first program
print("I have %s, and the price is %d rupees a kilo" %
(fruit1,price1))
print("I have %s, and the price is %d rupees a kilo" %
(fruit2,price2))
print("I have %s, and the price is %d rupees a kilo" %
(fruit3,price3))

# second program
class Fruits:
   def __init__(self,name,price):
       self.fruit = name
       self.price = price
       
first_fruit = Fruits(fruit1,price1)
print("I have %s, and the price is %d rupees a kilo" %
(first_fruit.fruit,first_fruit.price))

# Can you see some difference in both the programs ?

Exercise your way out

Q - Write your biodata in a text format as shown below, by using variables and
string formatting,

My name is <your_name> and I am <your_profession>. My father's name is


<father's_name> and I am <you r_age> years old. My date of birth is
<your_DOB>.

10
Q - Write a paragraph to summarize your previous semester marks, by using
variables and string formatting,

I am <your_name>

My marks are as below,

Math - <your_math_marks>

Physics - <your_physics_marks>

Social Studies - <your_socialstudy_marks>

I have scored a total of <your_total_mark> which is an aggregate of


<your_aggregate_percentage>

Q - Can you write a passage on your favorite food where each line is a new line
and each line has some formatting ? Remember to use only one print() function
[Have a look at the next section]

Escape Sequences

This \ (backslash) character encodes difficult-to-type characters into a string.


There are various ”escape
sequences” available for different characters you might want to use.

Let's try it out,

11
# use of the '\n' aka the newline escape character
print("Ring the bell \nEnter the home")

# use of the '\t' aks the tab space escape character


print("We teach python \t we teach Machine Learning too")

# use of the '\b' aka the backspace escape characters


print("We promote opensource\b")

OUTPUT:

Ring the bell


Enter the home
We teach python we teach Machine Learning too
We promote opensourc

Exercise your way out

Q - Write your biodata, with every line in a new line with the help of "\n".

Q - Make a table-like structure as shown below, using escape sequences and


print() function.

Commodity name Price(in Rs.)


Oil 40
Salt 10
Spices 100
Sugar 60
Vegetables 90

 
12
 

How to take input from user in python ?


Is it even possible to take some input from the user in python ? Let's get
introduced to the input() function.

Write this code in one of your python files and run it from the terminal,

# age is a variable used to store the input from the user


age = input("What's your age\n")

# printing out the age in the terminal


print(f"Your age is {age}")

OUTPUT:

What's your age


20
Your age is 20

You might have witnessed that the cursor at the terminal stopped and waited
for your input after printing the line "What's your age", this is because of the
input() function which is an inbuilt function, that takes a string as parameter,
which is nothing but the question you want to ask the user. If you don't want to
ask the question but still want to take the input, your code might look like, age
= input() , this will not ask any question as a string, but will take an input from
the user and place it in the variable age which is an empty bucket to hold
objects in python, as discussed earlier.

So, we are more powerful now with our bio-data exercise, we can do something
like the following and make our code user specific. It's the best thing about
python, you don't need to write a ton of code, neither there exists a heavy
syntax.

# taking your name as input from the terminal


name = input("What's your name ?\n")

# taking your father's name as input from the terminal


father_name = input("What's your father's name ?\n")

# taking your age input from the terminal

13
age = input("What's your age ?\n")

# taking your profession input from the terminal


profession = input("What do you do?\n")

# printing out the formatted text


print(f"Hello ! I am {name} and my father's name is
{father_name}. I am {profession} and I am {age} years old.")

What's your name ?


Abhijit
What's your father's name ?
Sasank Sekhar
What's your age ?
21
What do you do?
an entrepreneur
Hello ! I am Abhijit and my father's name is Sasank Sekhar. I am
an entrepreneur and I am 21 years old.

Code your way out

Q- Write a python program to take your friend's previous semester marks as


input and print it to the terminal.

Q- Write a program to take length and breadth of a rectangle as input and


print the corresponding area and perimeter as output.

Q - Write a program that takes an integer n as input and prints the sum of all
positive integers between 0 to n (both inclusive)

Q - Write a program that takes two integer m and n from the user and prints
the maximum of them.

14
Conditional Statements in Python
Can we check for some conditions in python ? We have seen earlier that we
have <, > , <= , >= as comparison operators. But the need of the time is
not only to compare, but also to put some conditions and execute certain lines
of code depending upon the output of the condition.

For example, consider the following,

You have to check if a given number n is an even number or an odd number. If


n is even, you have to print, "n is an even number", else you have to print "n is
an odd number".

It's clear from the above problem statement that the rest of our program
execution depends on a simple check - "n is divisible by 2 or not"

These type of problems are handled swiftly by using the in-built conditional
operators in python, if...........else.

Let's have a look at the syntax,

if( <condition> ):
<some code, when the condition is True>

else:
<some code, when the condition is False>

The code goes as below,

# program to check is an user input number n is even or odd

# taking input from the user

n = input("please enter a number")

# using conditional statements


if(n % 2 == 0):
   print(f"{n} is even\n")            # if (n%2 == 0) is True
else:
   print(f"{n} is odd\n")   # if (n%2 == 0) is False

15
OUTPUT:

-----------------------------------------------------------------
----------
TypeError                                 Traceback (most recent
call last)
<ipython-input-6-d4d385c90321> in <module>
    6
    7 # using conditional statements
----> 8 if(n % 2 == 0):
    9     print(f"{n} is even\n")           # if (n%2 == 0) is
True
    10 else:

TypeError: not all arguments converted during string formatting

It gives an error !

The reason of giving an error is quite important for python and needs special
attention. The input() function we have studied earlier takes input from the
user and stores it as a string object, which means we have, n="20" instead of
n=20 . And the difference being the datatype. "20" is a string but 20 is an
integer. We can't use modulus operator on "20" , hence the compiler gives an
error at the conditional statement. This problem can be solved by introducing a
typecasting method in python.

Have a look at the below code.

# first-case
age1 = input("What's your age ? ")

# second-case
age2 = int(input("What's your age ? "))

In the first-case, the input() has prompted the user and the user entered some
value x, here age1 stores x as a string because the default return type of the
input() function is string [Will discuss more about functions in few pages]. In
the second-case we have applied something like int() as a cover to the input()
function, this just converted the string x that we got from the user to an integer.
Hence age2 stores an integer.

This int() cover is also known as a technique called as typecasting.

Now writing the correct code for even & odd checking, we get,

16
# program to check is an user input number n is even or odd

# taking input from the user


n = int(input("please enter a number"))

# using conditional statements


if(n % 2 == 0):
   print(f"{n} is even\n")            # if (n%2 == 0) is True
else:
   print(f"{n} is odd\n")   # if (n%2 == 0) is False

please enter a number20


20 is even

Now there me a simple question in your mind at this point of time, i.e. what to
do when there are multiple conditions ? For example, suppose we have a
question, check if n is divisible by only 2, only 3 or both by 2 & 3 ? In this case
we have three cases to check, if n is divisible by 2 or n is divisible by 3 or n is
divisible by both 2 & 3 ?

These types of problems can be solved by using if........elif......else statement in


python.

Let's jump into code and have a look,

# taking input from the user


n = int(input("Please enter a number\n"))

# using conditional statements


if(n % 2 == 0 and n % 3 == 0):
   print(f"{n} is divisible by both 2 & 3")
elif(n % 2 == 0 and n % 3 != 0):
print(f"{n} is divisible by only 2")
elif(n % 3 == 0 and n % 2 != 0):
print(f"{n} is divisible by only 3")
else:
   print("Condition fails")

Please enter a number


9
9 is divisible by only 3

17
As you can notice we have used something like and here, which is a logical
operator and it returns true is both the conditional statements[(n % 2 == 0) &
(n % 3 == 0)] are true. Also we have used assignment operator like ==,!= etc.
Let's study about these operators in the next section.

18
Operators in Python
Python Assignment Operators

These operators are normally used to assign values to the variables.

Python Comparison Operator

Comparison operators are used to compare two values.

Python Logical Operator

Logical operators are normally used wherever there is a need to combine


conditions into a single one.

19
Python Identity Operator

Identity operators are used to compare the objects, not if they are equal, but if
they are actually the same object, with the same memory location

Python Membership Operator

Membership operators are used to test if a sequence is presented in an object

Python Bitwise Operator

Bitwise operators are used to compare (binary) numbers.

Let's solve some basic programming problems,

Exercise your way out:

Q - Given an integer, n , perform the following conditional actions:

If n is odd, print Weird


If n is even and in the inclusive range of 2 to 5 , print Not Weird
20
If n is even and in the inclusive range of 6 to 20 , print Weird
If n is even and greater than 20 , print Not Weird

Q - eduAlgo is interested to buy a new plot of land for it's brand new office. If
the land has an area greater than 4 Sq. Kms, then the founder is going to buy
that plot for the office. Create a program that calculated the area of the plot,
provided the following,

The plot can only be circular,rectangular,square and triangular shape. The


user enters the plot category.
Depending upon the plot category you have to take the required inputs for
the area calculation from the user.
And if the final area is greater than 4 Sq. Kms, then print "Accepted", else
print "Not Accepted".

Q - Given the marks of a student for five subjects, write a program to check if
the student is passed or failed ! Threshold to pass the exam is 35%.

 
21
 

Loops in python
Sometimes the programs are going to be repetitive in nature. For example,
suppose there is a problem statement to print 1 to 10(1,2,3,.....,9,10) . By
looking into the problem in a deeper way we can see, to print 10 numbers we
need 10 print() functions, which is not a scalable and perfect way to write code.
The repetition being printing the number, but there is a small change, the
number to be printed increases by 1 with each print() statement.

This becomes a necessity to use something which allows repetition in python as


well as takes care of the changes.

In python(and every other programming language), such technicality is called


as looping and normally python has two primitive loop commands, for and
while loop.

A loop statement allows us to execute a statement or group of statements


multiple times.

Let's check the syntax of both the while and for loop and use them to print
from 1 to 10.

# syntax - while loop

while expression:
   statement(s)
   

# syntax - for loop

for iterator_var in sequence:


   statements(s)

iterator_var is the variable used for iteration/traversing. Normally the for


loop is used in traversing.

Let's print 1 to 10 using these loops,

22
# declaring an iteration variable
iter_var = 1

# using the loop method


while(iter_var <= 10):
   
   # the statement which repeats
   print(iter_var,end=" ")
   
   # the change
   iter_var += 1

# using the for loop method


for iter_var in range(1,11):
   print(iter_var,end=" ")

OUTPUT:

1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10

Breaking apart the loops,

iter_var = 1 this denotes the declaration of an iteration variable and


initially it's set to be 1.
while() is the loop and iter_var <= 10 is the condition, here the
condition is to print from 1 to 10 which ,means we have to traverse from 1
to 10 and print the value of each iter_var .
print(iter_var,end=" ") is the statement which repeats itself with each
iteration.
iter_var+=1 is the change that we have explained above, with each
iteration the number is increased by 1.

Similarly in for loop, we have used something known as range() in python,


which is also an in-built function and takes two parameters (a,b), where a is
inclusive and b is exclusive, that simply means the traverse will take place from
a to b-1.

Nested Loops
Can we place one loop inside another ?

Let's check that with a piece of code,

23
for iter_var in range(0,2):
   for iter_ma in range(0,2):
       print(iter_var + iter_ma,end = " ")
   print()

OUTPUT:

0 1
1 2

Understanding what happened

To understand nested loops always break the loops in the following way,

for iter_var in range(0,2):


   <statement>

This is the outer-loop, when the outer loop executes, the <statement> part of
the loop also executes.

The <statement> execution can take place only when the inner loop executes,
this means the execution of the entire outer-loop is directly dependent on the
results obtained from the inner loops. One of the ways to solve a nested loop is
to start executing from the inner loop.

Here due to the inner loop the value of iter_ma changes from 0 to 1, with each
execution of the outer loop. It means for every iter_var in the outer loop
there exists two iter_ma , which is a better visualization of the problem here.

Loop control statements

Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope
are destroyed.

Python supports the following control statements.

break statement

It terminates the current loop and resumes execution at the next


statement. The break statement can be used in both while and for loops. If
you are using nested loops, the break statement stops the execution of the
innermost loop and start executing the next line of code after the block.

For example,

24
for i in range(0,10):
   if(i==7):
       break
   else:
       print(i,end=" ")

0 1 2 3 4 5 6

continue statement

The continue statement rejects all the remaining statements in the current
iteration of the loop and moves the control back to the top of the loop.

The continue statement can be used in both while and for loops.

for i in range(0,10):
   if(i==7):
       continue
   else:
       print(i,end=" ")

0 1 2 3 4 5 6 8 9

pass statement

It is used when a statement is required syntactically but you do not want


any command or code to execute.

The pass statement is a null operation; nothing happens when it executes.


The pass is also useful in places where your code will eventually go, but has
not been written yet.

for i in range(0,10):
   if(i==7):
       pass
   else:
       print(i,end=" ")

0 1 2 3 4 5 6 8 9

Exercise your way out

Q - For each , print , where is the taken from user.

Q - Write a program to print the following matrix to the terminal,

25
0 1 2
1 2 3
2 3 4

Q - Write a program to print A to Z, five characters per line.

 
26
 

File Handling in Python


open () function in python is used to open a file in read or write mode. open ( )
will returns a file object basically. We use two arguments, that accepts file name
and the mode, as shown below,

Mode Arguement Work

"r" for reading

"w" for writing

"a" for appending

"r+" for both read and write

Syntax

open(filename, mode)

Creating a file in python

To create a file, we are going to use the open() function along with the write
mode operation. Let's execute the following code to have a look at how things
are taking place.

Inside your folder create a .py file and place the following code inside it,

# opening a file, if it doen't exist then creating the file


file = open('edualgo.txt', 'w')

# writing a string to the "edualgo.txt" file


file.write("eduAlgo is an opensource organization and we promote
learning")

# closing the opened file


file.close()

.txt is an extension for the text files. We are creating a text file named as
"edualgo.txt", by using the "w" mode as that file did not exist before. You may
observe that a file of the same name "edualgo.txt" has been appeared in the
same folder, which has contained the same string that has been passed as a
parameter to the file.write() function.

27
Reading a file in python

To read a file, we are going to use the read() function along with the read
mode operation. In the same folder create a new .py extension file and place
the following block of code inside it.

# opening file in a read mode


file = open("edualgo.txt", "r")  

# reading file and storing the content as an object


element = file.read()

# printing the content


print (element)

OUTPUT Terminal:

(base) PS D:\Book-Py\Python_Programs> python .\program1.py


eduAlgo is an opensource organization and we promote learning

As you can see the file.read() operation has output the same string that we
have passed in the previous file creating block of code. This way we can read a
file and store it as an object in some variable and print the variable. Everything
can be treated as an object in python and that's what makes python so strong
and comfortable.

Adding new content to the file

Adding some new content to the files are relatively easy, we just need to
change the mode of the file to "a" which means appending some more
content.

Let's have a look at the code,

# opening a file in the append mode


file = open('edualgo.txt','a')

# writing a newline to the file


file.write("\nWe are currently teaching python")

# closing the openened file


file.close()

28
The above block of code will add a new line, that has been passed as a string in
the file.write() function.

Experiment your way out

Experiment No 1

# what is the output ?


with open("edualgo.txt") as file:  
   data = file.read()
   print(data)

Experiment No 2

with open("edualgo.txt", "w") as f:  


   f.write("Hello Learners !")

with open("edualgo.txt",'r') as f:
   print(f.read())

Exercise your way out

Q - Write a program using file handling to list out the table of n, to a file named
"table.txt", where n being given input by the user.

Q - Write a program to read length and breadth of a rectangle from a file


named "rectangle.txt", and write back the area of the rectangle. The initial
content of the file "rectangle.txt" is given below,

# content of "rectangle.txt"

21
45

 
29
 

Functions in python
Functions is an important topic in every programming language as it gives the
power of reusability to the programmer. Remember the "area" finding exercise
above, each time you had to write a statement like area = length*breadth .
As a programmer, it's quite frustrating to write the same logic every time.

But as programmers are smart, they have devised a way to get rid of this
repetitive logic writing. They have come up with an idea to create a box, which
has one (or many) input tunnels and one (or many) output tunnels. The only
thing we have to do is to supply the parameters to the input channels and the
output is ready every-time we need it. We just need to write the logic once.

For an illustration, let's consider the method of preparing curry.

We have to wash the vegetables, cut the vegetables, put them in a container
having some water, mix the required spices, follow an entire cooking
methodology of proper heat and proper stirring and finally after some 30-40
minutes of work the curry will be prepared. Now imagine you have to make the
curry daily, it will take a 30-40 minutes of time daily to follow the procedure (or
the logic you may say). That is quite repetitive.

But what if we have a box, where we just need to put the vegetables, spices
and some water only & the rest will be taken care of by some system ? Cooking
will be quite easier !

This box in programming, is known as functions. These are the basic pillars of
software designing. Technically known as black-boxes, the programmer who is
using a function, needs to know only about the input and the output but not
the logic inside. The logic is written just once, may be by some other
programmers.

In this segment of the book, we are going to discuss about both the logic
writing as well as function designing. So let's get started.

Creating a function

A function is a block of code which only runs when it is called. We can pass
data, known as parameters, into a function and the function returns data as a
result.

In python, we define a function using a special keyword def .

30
# the function syntax

def <function_name>(parameters):
   <logic>

For example, lets write an area() function which takes two parameters,length
and breadth, it returns the area of the rectangle. The function naming and the
parameter naming follows the same rule as that of variable naming.

# function to return the rectangle area

def area(length,breadth):
   return length*breadth

Let's break the above block of code,

def is the keyword for function, as explained earlier, whenever the


compiler gets a def it understands that this is a function definition.
area here is the function name and this name can be anything like
rectangle_area or area_of_rectangle etc. The same naming convention
as that of variable naming is used for function naming.
length & breadth are the name of the parameters and these name can
also be anything like l & b etc according to the variable naming
convention. It matters on the arguments we are passing as length and
breadth but not really on their values.
return statement returns something from the function, which is some
data in most of the cases.

So basically in one line, the area() function, takes two arguments as


parameters namely length and breadth and returns the area as the function
return data.

Calling a function

To call a function, we use the function name with the parenthesis and the
required arguments are passed as parameters.

Foe example,

31
# function to return the rectangle area
def area(length,breadth):
   return length*breadth

answer = area(10,3)
print(answer)

OUTPUT:

30

We have called the function as area(10,3) and stored the returned data in the
variable answer . 10 and 3 are known as arguments passed to the length and
breadth parameter of the function respectively. The order of argument matters
here because you have to send the arguments in the order of the parameters
in the function. If the order is changes, the return data will also be changed.

Keyword Arguments

Arguments can also be sent with the key = value syntax. This way the order of
the arguments does not matter.

For example, have a look at the code below,

def fruit_named(fruit1,fruit2,fruit3):
   print(f"{fruit2} is a good fruit")
   
fruit_named(fruit1 = "Apple", fruit2 = "Orange", fruit3 =
"Grapes")
fruit_named(fruit2 = "Mango", fruit1 = "Coconut", fruit3 =
"Jackfruit")

OUTPUT:

Orange is a good fruit


Mango is a good fruit

Arbitrary Arguments

If there is no certainty on how many arguments that will be passed into the
function, we add a * before the parameter name in the function definition, like
*args .

32
The function can receive as many arguments as you wish. The internal working
mechanism of *args follows something named as tuple , which is an in-built
python data structure.

def my_function(*fruits):
 print(f"{fruits[1]} is a good fruit")

my_function("Apple", "Mango", "Coconut")

# in tuples, it starts from zero,


# fruits[0] = "Apple"
# fruits[1] = "Mango"
# fruits[2] = "Coconut"

OUTPUT:

Mango is a good fruit

Arbitrary Keyword Arguments

If there is no certainty on how many keyword arguments that will be passed


into your function, add two asterisk: ** before the parameter name in the
function definition.

The function can now receive as many keyword argument as wished. The
internal working mechanism of **kwarg follows something known as dictionary
in python, which is an in-built python data structure.

def fruit_function(**fruits):
   print(fruits["fruit2"] + " is a good fruit")

fruit_function(fruit1 = "Apples", fruit2 = "Mango", fruit3 =


"Orange")

Mango is a good fruit

Default parameter passing

In case of a need, we can even pass a default parameter to a python


function,when a function is passed as having no parameters in it, the default
parameter will be used.

33
def name_function(name="eduAlgo"):
   print(f"{name} is an organization")
   
name_function("Google")
name_function("Netflix")
name_function() # blank parameter
name_function("XYZ")

Exercise your way out

Q - Write a function to print provided,

Q - Write a function, that takes n as an input from the user and prints out the
table of n in another file, the file name being passed as a parameter to the
function.

Q - Write a function, which can have as many parameters as the user wish i.e.
and returns their multiplication table one by one.

34
 

Object Oriented Programming in Python


Till now, we have studied about the basic operations in python like printing, file
handling, writing functions, performing some mathematics etc. Now it's the
time to take a step forward and learn the core concepts of object oriented
programming which is quite important for becoming a good software
developer.

We have written some procedures and functions in our previous exercises that
performed different operations with the data. This paradigm of programming is
technically known as Procedural programming.

But, in object oriented programming, it's all about creating certain objects of
some manually created, user defined building blocks known as class, that has
both data members and member functions included. We will be discussing
about the technical terms in detail, in the upcoming segments. To understand
what OOP is, let's consider a real life example.

Consider we have a class of Cars under which Santro Xing, Alto and WaganR
represents individual Objects. In this context each Car Object will have its own,
Model,Year of Manufacture, Color, Top Speed, Engine Power etc.,which form
Properties of the Car class and the associated actions i.e., object functions like
Start, Move, Stop form the Methods of Car Class.

So,every programming or real life problem can be designed in such a way that
can be solved using the OOP paradigm. Let's discuss each term one by one
briefly to get the idea and the intuition behind.

Objects

Object is the basic unit of object-oriented programming, having their unique


name. An object represents a particular instance of a class. There can be more
than one instance of an object. Each instance of an object can hold its own
relevant data.

An Object is a collection of data members and associated member functions


also known as methods.

Class

Classes are data types based on which objects are created. Objects with similar
properties and methods are grouped together to form a Class. Thus a Class
represent a set of individual objects. Characteristics of an object are
represented in a class as Properties. The actions that can be performed by
35
objects becomes functions of the class and is referred to as Methods.

Creating classes and objects in Python


A class is like blueprint for an object, let's create one to check the syntax and
the code.

Syntax:

class ClassName:
   # Statement-1
   <Attributes>
   <member functions>
   # Statement-N
   
# syntax for creating an object
ObjectName = ClassName()

Let's break it to understand,

Classes are created by keyword class .


ClassName is the name of the class, that follows the same naming
convention as that of variables.
The variables that belongs to the class are known as attributes.
Attributes can be publicly accessed by using the dot(.) operator.
ObjectName is the name of the object that we want to create. This also
follows the naming convention as that of variables.

We will be taking a sample real life problem of a Library, where there are
different books on different shelfs. Each book has a name and topic associated
with it. Every book has an author as well as a library ref. No mentioned.

Breaking the above mentioned context to fit OOP paradigm, we will get that
Library is a class where the book is an object. Each object has different
datatypes like - name, topic, author's name and ref.No.

Now, as the design is clear, let's write some code.

36
# defining the class
class Library:
   name = "A beginner's guide to python programming"
   topic = "Python"
   author_name = "Abhijit Tripathy"
   ref_no = 1
   
# creating an object
book1 = Library()

print(f"In the library there is a book named {book1.name}, which


is written by {book1.author_name} on the topic of {book1.topic}.
It has a library reference number of {book1.ref_no}.")

OUTPUT:

In the library there is a book named A beginner's guide to python


programming, which is written by Abhijit Tripathy on the topic of
Python. It has a library reference number of 1.

Let's understand this block properly, take some more time to understand it as
it's the most basic thing needed to solve a problem through any software.

Library is the class name having four attributes namely


name,topic,author_name,ref_no.
When we created an object of the Library class namely book1 , we have
applied the class blueprint to the object which means the object has the
same attributes now as that of the class which created it. So as soon as the
line book1 = Library() has been executed, one of the things that
happened internally is that the object book1 has been assigned the same
attributes as that of the class Library . Along with that, another important
thing has been taken place i.e. memory allocation. No memory is allocated
when a class is created. Memory is allocated only when an object is
created, i.e., when an instance of a class is created.
The second point is quite evident from the print() function, which prints the
attributes of book1 by using f-string formatting.

How to declare methods/functions inside the class ?

In our Library class we can assign a method to each of our class instances
that prints the details of the book, whenever called. To perform this, we just
need to declare a function inside the class(just like the normal function
declaration), along with a slightest change in the parameters passed.
37
We have to pass self as parameter along with other parameters while
declaring it inside the class.

class ClassName:
   
   def function_name(self,*args):
       <logic>

Have a look at the code below,

# defining the class


class Library:
   name = "A beginner's guide to python programming"
   topic = "Python"
   author_name = "Abhijit Tripathy"
   ref_no = 1
   
   # defining the member function
   def print_details(self):
       print(f"Name : {self.name}")
       print(f"Topic : {self.topic}")
       print(f"Author : {self.author_name}")
       print(f"Ref. NO : {self.ref_no}")
   
# creating an object
book1 = Library()

book1.print_details()

OUTPUT :

Name : A beginner's guide to python programming


Topic : Python
Author : Abhijit Tripathy
Ref. NO : 1

Let's get deeper to the self keyword and it's use.

self is an extra first parameter in method definition. We do not give a


value for this parameter, but when the function is called, python provides it
for us.
If we have a method which takes no arguments, then we still have to have
one argument. [For example, the print_details() method in the above
code].
38
Basically,when we call a method of this object as
ObjectName.MethodName(arg1, arg2) , this is automatically converted into
ClassName.MethodName(ObjectName, arg1, arg2) in python.

Constructors in Python
Till now we have performed all the basic operations related to classes and
objects like declaring member functions, accessing data members and member
functions etc.

But, one thing if you have noticed is that, our Library class is not flexible, i.e. it
contains only the data member for one book that we have declared. How to
make it possible for the classes to hold data members and member functions
for different book objects ?

In python and other programming languages, such limitations are covered up


by something called as constructors.

Constructors are generally used for instantiating an object. The task of


constructors is to initialize(assign values) to the data members of the class
when an object of class is created. In Python the __init__() method is called
the constructor and is always called when an object is created.

# syntax of the constructor


def __init__(self):
   # constructor body

Declaring constructor is just like declaring member functions in python, with


one difference that the function name is fixed as __init__() . Let's write the
Library class code again by passing some parameters to the constructor.

# defining the class


class Library:
   name = ""
   topic = ""
   author_name = ""
   ref_no = 0
   
   # defining a constructor
   def __init__(self,name,topic,author_name,ref_no):
       self.name = name
       self.topic = topic
       self.author_name = author_name
       self.ref_no = ref_no

39
   
   # defining the member function
   def print_details(self):
       print(f"Name : {self.name}")
       print(f"Topic : {self.topic}")
       print(f"Author : {self.author_name}")
       print(f"Ref. NO : {self.ref_no}",end="\n\n")
   
# creating an object
book1 = Library("A beginner's guide to Python","Python","Abhijit
Tripathy",1)
book2 = Library("Learning Python In a Practical
Way","Python","Abhijit Tripathy",2)
book3 = Library("A beginner's guide to Machine Learning","Machine
Learning","Abhijit Tripathy",3)

# printing the book details using the member function


book1.print_details()
book2.print_details()
book3.print_details()

OUTPUT :

Name : A beginner's guide to Python


Topic : Python
Author : Abhijit Tripathy
Ref. NO : 1

Name : Learning Python In a Practical Way


Topic : Python
Author : Abhijit Tripathy
Ref. NO : 2

Name : A beginner's guide to Machine Learning


Topic : Machine Learning
Author : Abhijit Tripathy
Ref. NO : 3

40
Destructors in Python
Destructors are called when an object gets destroyed. In Python, destructors
are not needed as much needed because Python has a garbage collector that
handles memory management automatically.
The __del__() method is a known as a destructor method in Python. It is
called when all references to the object have been deleted i.e when an object is
garbage collected.

def __del__(self):
 # body of destructor

Let's use the keyword del and delete our book objects manually.

# defining the class


class Library:
   name = ""
   topic = ""
   author_name = ""
   ref_no = 0
   
   # defining a constructor
   def __init__(self,name,topic,author_name,ref_no):
       self.name = name
       self.topic = topic
       self.author_name = author_name
       self.ref_no = ref_no
   
   # defining the member function
   def print_details(self):
       print(f"Name : {self.name}")
       print(f"Topic : {self.topic}")
       print(f"Author : {self.author_name}")
       print(f"Ref. NO : {self.ref_no}",end="\n\n")
       
   def __del__(self):
       print(f"{self.ref_no} Destroyed")
   
# creating an object
book1 = Library("A beginner's guide to Python","Python","Abhijit
Tripathy",1)
book2 = Library("Learning Python In a Practical
Way","Python","Abhijit Tripathy",2)

41
book3 = Library("A beginner's guide to Machine Learning","Machine
Learning","Abhijit Tripathy",3)

# printing the book details using the member function


book1.print_details()
del book1
book2.print_details()
del book2
book3.print_details()
del book3

OUTPUT:

Name : A beginner's guide to Python


Topic : Python
Author : Abhijit Tripathy
Ref. NO : 1

1 Destroyed
Name : Learning Python In a Practical Way
Topic : Python
Author : Abhijit Tripathy
Ref. NO : 2

2 Destroyed
Name : A beginner's guide to Machine Learning
Topic : Machine Learning
Author : Abhijit Tripathy
Ref. NO : 3

3 Destroyed

Exercise your way out


Q - Design a program for the car class, where the attributes being, name,
model, color, price, mileage etc.

Q - Imagine there is a 5 floor building in your town and each floor has different
company offices. Design a program to imitate the same

Q - Design a program using OOP for some college mark list.

42
 

Encapsulation in Python
Till now, we have used the default public access modifier in our class, which
enabled us to access any data member and member function from outside of
the class. But in some cases we need to hide some data and restrict the access
to some member functions.

Imagine a real life situation of an University, there are different departments


namely Physics, Chemistry, Mathematics, Journalism, Literature etc. Suppose
you are a student of the Mathematics department and you want to access the
student's data from the Chemistry department for one of your statistical
models. Now you have no ways to access the data from the chemistry
department as it's restricted, or in technical terms, it's encapsulated. To access
the data in such situation, you will need to contact someone from the
Chemistry department administration and request them.

In a similar way, inside a software, there are few blocks of code whose access is
private and they can't be modified by any method outside of the class. Using
OOP in Python, we can restrict access to methods and variables. This prevents
data from direct modification which is called encapsulation.

Private Access Modifier


The class members declared private should neither be accessed outside the
class. There is no existence of Private instance variables that cannot be
accessed except inside a class in python. However, to define a private member
prefix the member name with double underscore “__”.

Have a look at the following code,

# defining the class


class Library:
   
   # defining a constructor
   def __init__(self,name,topic,author_name,ref_no):
       self.name = name
       self.topic = topic
       self.author_name = author_name
       self.__ref_no = ref_no # private
attribute
   
   # defining the member function
   def print_details(self):
43
       print(f"Name : {self.name}")
       print(f"Topic : {self.topic}")
       print(f"Author : {self.author_name}")
       print(f"Ref. NO : {self.__ref_no}",end="\n\n")
       
   # defining a destructor
   def __del__(self):
       print(f"{self.ref_no} Destroyed")
   
# creating an object
book1 = Library("A beginner's guide to Python","Python","Abhijit
Tripathy",1)

# printing the book details using the member function


book1.print_details()

# trying to print the ref_no by directly accessing


print(book1.__ref_no)

OUTPUT:

Name : A beginner's guide to Python


Topic : Python
Author : Abhijit Tripathy
Ref. NO : 1

-----------------------------------------------------------------
----------
AttributeError                           Traceback (most recent
call last)
<ipython-input-46-8c10ac780031> in <module>
    26
    27 # trying to print the ref_no by directly accessing
---> 28 print(book1.__ref_no)

AttributeError: 'Library' object has no attribute '__ref_no'

It generates an AttributeError when we tried to access the data member


outside of the class, but the program output correctly when we have used the
member function defined inside the class to print the book details. The
member function of the Library class is defined inside the class, hence is able
to access the private member `__ref_no .

44
Exercise your way out

Q - Design a program, where there is a class named students that holds the
details of students like the name,roll_no,marks obtained etc and you have to
print the percentage obtained by the student, providing the mark attribute and
the function for converting marks to percentage are private. Create 5 student
objects and test your design on each one of them. The program should contain
proper constructor and destructor too.

 
45
Inheritance in Python
Inheritance generally means transfer of characters from the parents to the
children. Consider a situation where we have a person class which has data
attributes like name,addresses,height,weight,gender etc. Now in the same
program it's required to design another class named as students that has all
the attributes of the person class like name,addresses,height,weight along
with some more attributes specific to the students class like the
college_name,branch,semester etc. In this case, we can see that the students
class inherit all the properties of the person class and has some more data
attributes present, which are not really necessary for the person class.

In such cases, the inheritance ability of python comes into play.

Inheritance is the capability of one class to derive or inherit the properties from
another class. It provides reusability of a code. The same code needn't to be
written again and again. Also, it allows us to add more features to a class
without modifying it. It is transitive in nature, which means that if class B
inherits from another class A, then all the subclasses of B would automatically
inherit from class A.

Let's learn by coding it out,

# the parent class


class person:
   def __init__(self,name,age,gender):
       self.name = name
       self.age = age
       self.gender = gender
       
   def print_details(self):
       print(f"Name : {self.name}")
       print(f"Age : {self.age}")
       print(f"Gender : {self.gender}")

# the child class      


class Student(person):
   def __init__(self,name,age,gender,college_name,semester):
       # When you add the __init__() function, the child class
will no
       # longer inherit the parent's __init__() function.
       
       # To keep the inheritance of the parent's __init__()
function,
46
       # add a call to the parent's __init__() function:
       person.__init__(self,name,age,gender)
       self.college_name = college_name
       self.semester = semester
   
   def print_student_details(self):
       # using the member function of the parent class
       person.print_details(self)
       print(f"College : {self.college_name}")
       print(f"Semester : {self.semester}")
       
# creating an object of the child class
student1 = Student("Abhijit",21,"Male","Central
University,Bilaspur","3")

# printing the student details, using the function in the child


class
student1.print_student_details()

OUTPUT:

Name : Abhijit
Age : 21
Gender : Male
College : GGV,Bilaspur
Semester : 3

As we can see we have a parent class of person and a child class of student ,
one important thing to notice is that, we are adding our own __init__()
function in the child class, which is breaking it's inheritance from the base class,
due to the reason that both the constructors are taking different number of
parameters, it makes both the class as two different entity. Hence to link the
parent class with the child class, we are calling person.__init__() .

Experiment your way out

# what will be the output ?

# the base class


class person:
   def __init__(self,name,age,gender):
       self.name = name
       self.age = age
       self.gender = gender
47
       
   def print_details(self):
       print(f"Name : {self.name}")
       print(f"Age : {self.age}")
       print(f"Gender : {self.gender}")

# the child class      


class Student(person):
   def __init__(self,name,age,gender,college_name,semester):
       super().__init__(name,age,gender)
       self.college_name = college_name
       self.semester = semester
   
   def print_student_details(self):
       person.print_details(self)
       print(f"College : {self.college_name}")
       print(f"Semester : {self.semester}")
       
# creating an object of the child class
student1 = Student("Abhijit",21,"Male","GGV,Bilaspur","3")

# printing the student details, using the function in the child


class
student1.print_student_details()

Types of Inheritance
Mainly there are five types of inheritance, that can be observed in a software
design.

Single Inheritance

When a child class inherits from one parent class it's called as Single
Inheritance. The person and Student class that we have designed above are
the example of Single Inheritance.

Multiple Inheritance

When a child class inherits from multiple parent classes, it is called multiple
inheritance.

# the base classes


class first_base:
   def __init__(self):
       self.str1 = "First Base Class"
 
48
class second_base:
   def __init__(self):
       self.str2 = "Second Base Class"        
 
# multiple inheritance, derived from two base classes
class derived(first_base, second_base):
   def __init__(self):
       first_base.__init__(self)
       second_base.__init__(self)

Multilevel Inheritance

When there is a child class as well as a grandchild class which is derived from
the child class, we call it as multilevel inheritance.

# the base class


class Base:
   def __init__(self, a):
       self.a = a
 
# inherited child class  
49
class Child(Base):
   def __init__(self, a, b):
       Base.__init__(self, a)
       self.b = b
 
# inherited grand child class
class GrandChild(Child):
   def __init__(self, a, b, c):
       Child.__init__(self, a, b)
       self.c = c

Hierarchical inheritance

When more than one derived class are constructed from a single base class we
call it as Hierarchical inheritance.

# the base class


class Base:
   def __init__(self, a):
       self.a = a
 
# inherited child class  
class Child1(Base):
   def __init__(self, a, b):
       Base.__init__(self, a)
       self.b = b
 
# inherited child class
class Child2(Base):
   def __init__(self, a, c):
       Base.__init__(self, a)
       self.c = c

Hybrid inheritance:

If more than one form of inheritance is present then it's known as Hybrid
inheritance.

# the base class


class Base:
   def __init__(self, a):
       self.a = a
 
# inherited child class from the base class  
class Child1(Base):
50
   def __init__(self, a, b):
       Base.__init__(self, a)
       self.b = b

# inherited grand child class from the child class


class GrandChild(Child1):
   def __init__(self,a,b,d):
       Child1.__init__(self,a,b)
       self.d = d
       
# ingerited child class from base class
class Child2(Base):
   def __init__(self, a, c):
       Base.__init__(self, a)
       self.c = c

# inherited from the grand child class of the base class      


class derived_grand(GrandChild):
   def __init__(self,a,b,c,e,f):
       GrandChild.__init__(self,a,b,c)
       self.e = e
       self.f = f

Exercise your way out

Q - Design a program to have a base class of library , having child classes of


book , magazine , news_paper and grand child of
science_stream , business_stream & story . Design some member functions
to print their details. Remember to put the ref_no of the library books as
private in all the inherited class.

Q - Design a program to have a base class of company , having child class of


developer_team , finance_team , sales_team etc, with some person specific
grandchildren like employee , manager , project_lead etc. Design some
member functions to print their details and their work. employee has some
child of interns , trainee , part_time , full_time too.

51
Python Special Functions
Class functions that begin with double underscore __ are called special
functions in Python.

These functions are not the typical functions that we define for a class. The
__init__() function we defined above is one of them. It gets called every time
we create a new object of that class.

There are numerous other special functions in Python available in the official
python documentations. Using special functions, we can make our class
compatible with built-in functions. Let's have a look at some blocks of code to
understand the need.

# declaring a student class


class Student:
   def __init__(self,maths,phy):
       self.maths = maths
       self.phy = phy
       
# declaring two students
monty = Student(75,80)

# printing the object


print(monty)

OUTPUT:

<__main__.Student object at 0x000001F06623CA20>

As we can see when we tried to print out an object, it printed out the memory
location that the object has been assigned in the computer memory. This is
because the in-built print() function is not designed to print custom objects.

But as python is powerful, we can make the print() function compatible by


using a __str__() method in our class that controls how the object gets
printed.

# defining a student class


class Student:
   def __init__(self,maths,phy):
       self.maths = maths
       self.phy = phy
   
52
   # the special method in python
   def __str__(self):
       return f"The math marks is {self.maths}, and the physics
marks is {self.phy}"
       
# declaring two students
monty = Student(75,80)

# printing the object


print(monty)

The math marks is 75, and the physics marks is 80

It printed correctly. There are numerous special functions in python available to


be used from python documentation.

Operator Overloading in Python


Consider the following code,

# defining a student class


class Student:
   def __init__(self,maths,phy):
       self.maths = maths
       self.phy = phy
   
   # the special method in python
   def __str__(self):
       return f"The math marks is {self.maths}, and the physics
marks is {self.phy}"

# declaring two students along with the marks


monty = Student(75,80)
parker = Student(32,78)

# adding their marks


print(monty + parker)

53
-----------------------------------------------------------------
----------
TypeError                                 Traceback (most recent
call last)
<ipython-input-5-7af7a86df8ea> in <module>
    10 parker = Student(32,78)
    11
---> 12 print(monty + parker)

TypeError: unsupported operand type(s) for +: 'Student' and


'Student'

It created a TypeError !!

This error is generated, because we have used an inbuilt operator + that's not
designed to add two objects, just like we have seen in the special function
segment (the print() function). Python has special functions to carry out
operator overloading and modify the behavior of the inbuilt operators.

To overload the + operator, we will need to implement __add__() function in


the class.

# defining a student class


class Student:
   def __init__(self,maths,phy):
       self.maths = maths
       self.phy = phy
   
   # the special method in python
   def __str__(self):
       return f"The math marks is {self.maths}, and the physics
marks is {self.phy}"
   
   # overloading the addition operator
   def __add__(self,other):
       maths = self.maths + other.maths
       phy = self.phy + other.phy
       return Student(maths,phy)

# declaring two students along with the marks


monty = Student(75,80)
parker = Student(32,78)

# printing the sum of the marks


print(monty + parker)
54
 

What actually happens is that, when you use monty + parker , Python calls
monty.__add__(parker) which in turn is Student.__add__(monty,parker) .
After this, the addition operation is carried out the way we specified.

Similarly, we can overload other operators as well. The special function that we
need to implement is tabulated below.

55
Exercise your way out

Q - Design a program to take two fruit objects and compare their price using
operator overloading.

Q - Design a program to take 10 student objects and and rank them


according to their percentage using operator overloading.

56
Exception handling in Python
Whenever there is an error in the program, python raises a traceback and
generates an error statement. In python, it's quite easy to test a code using
try keyword and generate an error statement using except keyword. When
an error occurs, or exception as we call it, Python will normally stop and
generate an error message.

These exceptions can be handled using the try statement:

class Student:
   def __init__(self,maths,phy):
       self.maths = maths
       self.phy = phy
   
   def __str__(self):
       return f"The math marks is {self.maths}, and the physics
marks is {self.phy}"
       
monty = Student(75,80)
parker = Student(32,78)

# using exception handling


try:
   print(monty + parker)
except:
   print("An error occures")

OUPUT:

An error occures

It generates an error because of the + operator being used to add two user
defined objects. Instead of getting a traceback our error has been handled by
the except statement.

Even we can design except block of code for special kind of errors, like here
the error generated is a TypeError as seen earlier.

class Student:
   def __init__(self,maths,phy):
       self.maths = maths
       self.phy = phy
   
57
   def __str__(self):
       return f"The math marks is {self.maths}, and the physics
marks is {self.phy}"
       
monty = Student(75,80)
parker = Student(32,78)

try:
   print(monty + parker)
except TypeError:
   print("A TypeError occured")
except:
   print("An error occures")

OUTPUT:

A TypeError occured

else keyword in error handling

We can use the else keyword to define a block of code to be executed if no


errors were raised.

class Student:
   def __init__(self,maths,phy):
       self.maths = maths
       self.phy = phy
   
   def __str__(self):
       return f"The math marks is {self.maths}, and the physics
marks is {self.phy}"
   
   def __add__(self,other):
       maths = self.maths + other.maths
       phy = self.phy + other.phy
       return Student(maths,phy)
       
monty = Student(75,80)
parker = Student(32,78)

# handling exceptions
try:
   print(monty + parker)
except:
   print("An error occures")
58
else:
   print("There are no errors")

OUTPUT :

The math marks is 107, and the physics marks is 158


There are no errors

finally keyword in exception handling

The finally block will be executed regardless if the try block raises an error or
not.

class Student:
   def __init__(self,maths,phy):
       self.maths = maths
       self.phy = phy
   
   def __str__(self):
       return f"The math marks is {self.maths}, and the physics
marks is {self.phy}"
       
monty = Student(75,80)
parker = Student(32,78)

# exception handling
try:
   print(monty + parker)
except:
   print("An error occures")
finally:
   print(monty)
   print(parker)

OUTPUT :

An error occures
The math marks is 75, and the physics marks is 80
The math marks is 32, and the physics marks is 78

59
raise an exception from any condition

You can choose to throw an exception if a condition occurs. To throw (or raise)
an exception, use the raise keyword.

x = 10

if x%3 != 0:
   raise Exception("Sorry not divisible by 3")

OUTPUT:

-----------------------------------------------------------------
----------
Exception                                 Traceback (most recent
call last)
<ipython-input-18-e6bb540e6824> in <module>
    2
    3 if x%3 != 0:
----> 4     raise Exception("Sorry not divisible by 3")

Exception: Sorry not divisible by 3

60
 

Python Lists
Python, being versatile, provides us with many compound data types, one of
which is list. As the name suggests, it's a combination of different objects
enclosed inside a box. The box in python being [ ] , square brackets. List is
used frequently in python, making python a great choice for modern
developers.

creating a list in python

A list is created by placing all the items (elements) inside square brackets [] ,
separated by commas. It can have any number of items and they may be of
different data types.

# empty list
my_list = []

# list of strings
my_list = ["Apple","Orange","Banana"]

# list of integers
my_list = [1,4,5]

# list of mixed data types


my_list = [2,"Coconut",4,7.68]

The most important thing, a list in python can contain another list, i.e. nested
list.

# a nested list
my_list = [4,["Apple","grapes"],[3.45,6.776556],"eduAlgo"]

One thing to notice here is that, my_list is also an object in python of the list
type.

how to access elements from a list

list objects in python can be accessed through indexing. Suppose we have


my_list as given below,

# creating a list of items


my_list = ["Apple","Orange","Jackfruit"]

61
As we can see, there are three elements in the my_list object. And the
indexing starts from 0 . Run the below code to understand the indexing in a
better way.

# creating a list of items


my_list = ["Apple","Orange","Jackfruit"]

# printing the list elements starting from 0


print(my_list[0])
print(my_list[1])
print(my_list[2])

# trying to access the 3rd index


try:
   print(my_list[3])
except:
   print("An error occured")

OUTPUT :

Apple
Orange
Jackfruit
An error occured

As we have tried to access the 3rd index, the program generated an error as
expected. So we get a conclusion, that if a list has elements, then the
maximum index that can be used to access the element is .

To check the length of any list we can use the following code by using the
len() function ,

print(len(my_list))

Python also allows negative indexing for its sequences. The index of -1 refers to
the last item, -2 to the second last item and so on.

62
# creating a list of items
my_list = ["Apple","Orange","Jackfruit"]

# printing the list elements starting from 0


print(my_list[-1])
print(my_list[-2])
print(my_list[-3])

# trying to access the 3rd index


try:
   print(my_list[-4])
except:
   print("An error occured")

OUTPUT :

Apple
Orange
Jackfruit
An error occured

how to access a range of elements in a list ?

We can access a range of items in a list by using the slicing operator : (colon).
This method is also known as slicing.

# List slicing in Python


my_list = ['e','d','u','a','l','g','o']

# elements 3rd to 5th


print(my_list[2:5])

# elements beginning to 3rd


print(my_list[:-4])

OUTPUT :

['u', 'a', 'l']


['e', 'd', 'u']

63
changing elements of a list

As the python lists are mutable, their content can be changed by using the
assignment operator ( = ) .

# declaring a list in python


my_list = [1,2,3,5,6]

# changing one item of the list


my_list[3] = 10
print(my_list)

# changing a list of items of the list


my_list[:3] = [23,24,25]
print(my_list)

OUTPUT :

[1, 2, 3, 10, 6]
[23, 24, 25, 10, 6]

adding elements to the list

To add one item to the list we can use the append() function that's applicable
to the python lists. To add several items we can use extend() function for the
list.

# declaring a list in python


my_list = [1,2,3,5,6]

# adding one element to the python list


my_list.append(20)
print(my_list)

# extending the python list by adding three elements


my_list.extend([23,24,25])
print(my_list)

OUTPUT :

[1, 2, 3, 5, 6, 20]
[1, 2, 3, 5, 6, 20, 23, 24, 25]

64
concatenation in a list

We can use the + operator to combine two lists, which in term known as list
concatenation.

# creating the lists


list1 = [1,2,3,4]
list2 = [ "Apple","coconut"]

# adding the lists


list3 = list1 + list2

# printing the added list


print(list3)

OUTPUT :

[1, 2, 3, 4, 'Apple', 'coconut']

inserting element(s) in a list

Inserting into the list can be achieved by using the insert() function.
insert(position,element) , it takes two arguments, first one being the
position of the list where to insert the element. To insert multiple items use an
empty slice of a list.

my_list = [1,2,3,4,5]

# inserting a single element to the list


my_list.insert(2,10)
print(my_list)

# inserting a group of elements to the list


my_list[2:2] = [25,26,27]
print(my_list)

OUTPUT:

[1, 2, 10, 3, 4, 5]
[1, 2, 25, 26, 27, 10, 3, 4, 5]

65
deleting an element from the list

del keyword can be used both to delete an element from the list as well as
delete the entire list.

my_list = ["Apple","Orange","Coconut","Jackfruit","Banana"]

# deleting a single element from the list


del my_list[3]
print(my_list)

# deleting the entire list


del my_list

# trying to print the deleted list


try:
   print(my_list)
except:
   print("An error occured")

OUTPUT :

['Apple', 'Orange', 'Coconut', 'Banana']


An error occured

We can use the remove method to remove a given item or the pop method to
remove item from a given position.

my_list = ["Apple","Orange","Coconut","Jackfruit","Banana"]

# removing a given element from the list


my_list.remove("Apple")
print(my_list)

# poping an element from the given list from a certain postion


print(my_list.pop(1))
print(my_list)

# poping out the last element of the list


print(my_list.pop())
print(my_list)

66
OUTPUT :

['Orange', 'Coconut', 'Jackfruit', 'Banana']


Coconut
['Orange', 'Jackfruit', 'Banana']
Banana
['Orange', 'Jackfruit']

One thing to notice here, pop() with a null parameter, pops out the last
element from the list. This property of python list helps in the Stack data-
structure. [Discussing about data-structures like Stack, Queue, Graph etc are
out of the scope of this book]

List Methods in Python

Method Name Actions by the Method

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

extend() Add all element of the list to another list

insert() Insert an item at the defined index

remove() Removes an item at the defined index

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

count() Returns the number of items in the passed argument

sort() Sort a list in an ascending order

reverse() Reverse the item order in the list

copy() Returns a shallow copy of the list

List Comprehension
What if, there is a question to create a list of n integers where the list contains
for

We can write something like,

67
# creating an empty list
square_list = []

# taking input from the user


n = int(input())

# generating square of numbers and appending back to the list


for i in range(1,n+1):
   square_list.append(i ** 2)

# print the list


print(square_list)

OUTPUT :

7
[1, 4, 9, 16, 25, 36, 49]

List comprehension is a concise way to create a new list. A list comprehension


consists of an expression followed by a for statement inside square brackets.

The above program can be achieved easily in very less lines of code,

# taking input from the user


n = int(input())

# creating a list of square numbers using list comprehension


square_list = [i ** 2 for i in range(1,n+1)]

# printing the square list


print(square_list)

OUTPUT :

7
[1, 4, 9, 16, 25, 36, 49]

Using membership operators

We can test if an item exists in a list or not, using the keyword in . Also by using
a for loop we can iterate through each item in a list.

68
# creating a list
fruits = ["Apple","Orange","Coconut","Jackfruit"]

# using membership operator "in"


for fruit in fruits:
   print(f"{fruit} is a good fruit")

OUTPUT :

Apple is a good fruit


Orange is a good fruit
Coconut is a good fruit
Jackfruit is a good fruit

Exercise your way out

1. Write a Python program to sum all the items in a list.

2. Write a Python program to multiplies all the items in a list.

3. Write a Python program to get the largest number from a list.

4. Write a Python program to get the smallest number from a list.

5. Write a Python program to count the number of strings where the string
length is 2 or more and the first and last character are same from a given list of
strings.

Sample List : ['abc', 'xyz', 'aba', '1221']


Expected Result : 2

6. Write a Python program to remove duplicates from a list.

7. Write a Python program to check a list is empty or not.

8. Write a Python program to clone or copy a list

9. Write a Python program to find the list of words that are longer than n from
a given list of words.

10. Write a Python function that takes two lists and returns True if they have at
least one common member.

11. Write a Python program to print a specified list after removing the 0th, 4th
and 5th elements.

69
Sample List : ['Red', 'Green', 'White', 'Black', 'Pink',
'Yellow']
Expected Output : ['Green', 'White', 'Black']

12. Write a Python program to print the numbers of a specified list after
removing even numbers from it.

13. Given the names and grades for each student in a class of students, store
them in a nested list and print the name(s) of any student(s) having the second
lowest grade.

Note: If there are multiple students with the second lowest grade, order their
names alphabetically and print each name on a new line.

Example

records = [["Abhijit",90],["Himanshu",98],["Amogh",97],
["Himanshi",100],["Smriti",97]]

The ordered list of scores is [90,97,98,100], so the second lowest score is 97 .


There are two students with that score: ["Amogh","Smriti"]. Ordered
alphabetically, the names are printed as:

Amogh
Smriti

14. Given the participants' score sheet for your University Sports Day, you are
required to find the runner-up score. You are given scores. Store them in a list
and find the score of the runner-up.

15. Create a list of 20 student class objects having name and total_mark as
the data members and print the list in the sorted order of their marks, in a
tabular format.

 
70
Python Tuples
A t tuple in Python is similar to python list that we have previously
discussed. The difference between the two is that we cannot change the
elements of a tuple once it is assigned whereas we can change the elements of
a list. Tuple is normally enclosed by ( ) .

creating a tuple in python

A tuple is created by placing all the items (elements) inside parentheses () ,


separated by commas. It can have any number of items and they may be of
different data types.

# empty tuple
my_tuple = ()

# tuple of strings
my_tuple = ("Apple","Orange","Banana")

# tuple of integers
my_tuple = (1,4,5)

# tuple of mixed data types


my_tuple = (2,"Coconut",4,7.68)

There can be nested tuples as well,

# nested tuple containing tuples as well as lists


my_tuple = (2,["Coconut","Apple","Orange"],4,7.68,(1,2,2))

One thing to notice here is that, my_tuple is also an object in python of the
tuple type. Tuple can be created without using ( ) , which is known as tuple
packing.

how to access elements from a tuple

tuple objects in python can be accessed through indexing, similar to that of


list .

71
# creating a tuple of items
my_tuple = ("Apple","Orange","Jackfruit")

# printing the tuple elements starting from 0


print(my_tuple[1])
print(my_tuple[-2])
print(my_tuple[2])

# trying to access the 3rd index


try:
   print(my_tuple[-4])
except:
   print("An error occured")

OUTPUT :

Orange
Orange
Jackfruit
An error occured

how to access a range of elements in a tuple ?

We can access a range of items in a tuple by using the slicing operator colon : ,
similar to that of list .

# tuple slicing in Python


my_tuple = ('e','d','u','a','l','g','o')

# elements 3rd to 5th


print(my_tuple[2:5])

# elements beginning to 3rd


print(my_tuple[:-4])

OUTPUT :

('u', 'a', 'l')


('e', 'd', 'u')

72
changing elements of a tuple

Unlike lists, tuples are immutable. This means that elements of a tuple cannot
be changed once they have been assigned. But, if the element is itself a
mutable data type like list, its nested items can be changed. This is one of the
important difference between the tuple and the list data type.

# declaring a tuple in python


my_tuple = (1,2,3,5,6)

# changing one item of the tuple


try:
   my_list[3] = 10
   print(my_list)
except:
   print("Error occured")

OUTPUT :

Error occured

adding/inserting elements to a tuple

Unlike lists, we can't add/insert elements to a tuple. Tuples are immutable in


nature, hence there are no such methods in python which can enable addition
of new elements to the tuple. But there are few techniques that can be used to
add elements to the tuple. One of which is tuple concatenation.

concatenating in a tuple

The + operator can be used for the concatenation of tuples, similar to lists.

# creating the tuples


tuple1 = (1,2,3,4)
tuple2 = ("Apple","coconut")

# adding the tuples


tuple3 = tuple1 + tuple2

# printing the added tuples


print(tuple3)

73
OUTPUT :

(1, 2, 3, 4, 'Apple', 'coconut')

deleting elements from the tuple

As tuples are immutable in nature, deleting an element is not possible, unlike


lists. But the entire deletion of the tuple is possible by using the del keyword.

# creating the tuples


tuple1 = (1,2,3,4)

del tuple1

try:
   print(tuple1)
except:
   print("An error occured")

OUTPUT :

An error occured

Exercise your way out

1. Write a Python program to add an item in a tuple.

2. Write a Python program to find the repeated items of a tuple.

3. Write a Python program to check whether an element exists within a tuple.

4. Write a Python program to reverse a tuple.

5. Write a Python program to unzip a list of tuples into individual lists.

6. Write a Python program to convert a tuple of string values to a tuple of


integer values.

Original tuple values:


(('333', '33'), ('1416', '55'))
New tuple values:
((333, 33), (1416, 55))

 
74
Important Methods in Python Strings
A string is a sequence of characters. In Python, a string is a sequence of
Unicode characters. Unicode was introduced to include every character in all
languages and bring uniformity in encoding. Strings can be created by
enclosing characters inside a single quote or double-quotes. Triple quotes are
used to represent multiline strings and docstrings.

accessing characters from a string

Just like lists and tuples we can access characters of a string by indexing and
range of characters by slicing.

name = "Abhijit Tripathy"

# accessing single character


print(name[6])

# accessing range of characters


print(name[2:6])

# trying to access something out of the index


try:
   print(name[25])
except:
   print("An error occured")

OUTPUT :

t
hiji
An error occured

changing or deleting string

Like tuples and unlike lists strings are immutable. This means that elements of
a string cannot be changed once they have been assigned. Deleting a string can
be carried out by using the del keyword similar to that of the tuple.

75
Methods in string

Method Name Work of the method

endswith() Check if the string ends with some special character

capitalize() Convert the first character to capital letter

find() Returns the index of the first occurrence of the substring

index() Returns the index of the substring

join() Used for string concatenation

upper() Returns upper case string

lower() Returns lower case string

 
76
 

Python sets
In mathematics a set is an unordered collection of items, where every set items
are unique. Python supports a similar built-in data type known as set that can
also be used to perform mathematical set operations like union, intersection,
symmetric difference, etc.

creating a set in python

A set is created by placing all the items (elements) inside curly braces {} ,
separated by comma, or by using the built-in set() function. Set can have
different data types as it's elements except mutable elements like lists. Have a
look at the below code to understand how to create a set and how an error
occurs when we include any mutable element inside the set.

# creating an empty set


my_set = set()

# creating a non-empty set


my_set = {1,2,3,4,5}
print(my_set)

# creating a set having immutable data types


my_set = {2,"Hello",(90,45,67)}
print(my_set)

# trying to create a set having mutable data types


try:
   my_set = {3,4,"Torso",[1,2,3]}
except:
   print("An error occured")

OUTPUT :

{1, 2, 3, 4, 5}
{(90, 45, 67), 2, 'Hello'}
An error occured

One thing to notice, the set is unordered data type. Like in the second line of
the output, we can see it's been printed in a different order than the assigned
order.

77
changing elements of set

As we have seen above sets are unordered, hence the indexing has no
meaning. We cannot access or change an element of a set using indexing or
slicing. Set data type does not support it. Though sets are mutable, the slicing
method doesn't work.

adding elements to the set

We can add a single element using the add() method, and multiple elements
using the update() method.

my_set = {1,2,3,4,5}

# adding a new element


my_set.add(56)
print(my_set)

# adding an element that already exists inside the set


my_set.add(3)
print(my_set)

# adding a tuple of elements


my_set.update((4,90,34))
print(my_set)

# adding both tuple and list elements


my_set.update([13,44],(23,45))
print(my_set)

# in all the cases above the duplicates are avoided

OUTPUT :

{1, 2, 3, 4, 5, 56}
{1, 2, 3, 4, 5, 56}
{1, 2, 3, 4, 5, 34, 56, 90}
{1, 2, 3, 4, 5, 34, 44, 13, 45, 23, 56, 90}

removing elements from a set

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

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

# declaring a set
my_set = {1,2,3,4,5}

# removing an existing element


my_set.remove(3)
print(my_set)

# discarding an existing element


my_set.discard(2)
print(my_set)

# discarding a non-existing element


my_set.discard(10)
print(my_set)

# removing a non-existing element


try:
   my_set.remove(10)
except:
   print("An error occured")

OUTPUT :

{1, 2, 4, 5}
{1, 4, 5}
{1, 4, 5}
An error occured

python set operations

Sets can be used to carry out mathematical set operations like union,
intersection, difference and symmetric difference.

Set Union

79
Union of A and B is a set of all elements from both sets. Union is performed
using | operator. Same can be accomplished using the union() method.

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# using | operator
print(A | B)

{1, 2, 3, 4, 5, 6, 7, 8}

Set Intersection

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

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# using & operator


print(A & B)

{4, 5}

80
Set Difference

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

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# using - operator on A
print(A - B)

{1, 2, 3}

Set Symmetric Difference

Symmetric Difference of A and B is a set of elements in A and B but not in both


(excluding the intersection). Symmetric difference is performed using ^
operator. Same can be accomplished using the method
symmetric_difference() .

81
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# using ^ operator
print(A ^ B)

{1, 2, 3, 6, 7, 8}

built-in methods in set

Method Description

sum() returns the sum of all elements in the set

returns a sorted list of the elements in the set (doesn't change


sorted()
the set)

min() returns the smallest item of the set

max() returns the largest item of the set

returns the length of the set or the number of elements in the


len()
set

82
Python Dictionary
Python dictionary is an unordered collection of items. Each item of a dictionary
has a key/value pair. Whenever the key is known to us, dictionary can retrieve
the value in an optimized way.

creating a python dictionary

Creating a dictionary is as simple as placing items inside curly braces {}


separated by commas. An item has a key and a corresponding value that is
expressed as a pair (key: value). While the values can be of any data type and
can repeat, keys must be of immutable type and must be unique.

# creating an empty dictionary


my_dict = {}

# creating a dictionary
my_dict = {1:"Apple",2:"Banana"}
print(my_dict)

# creating a dictionary of different data types


my_dict = {"first":"edualgo",1:"book",(1,2,3):"nothing"}
print(my_dict)

OUTPUT :

{1: 'Apple', 2: 'Banana'}


{'first': 'edualgo', 1: 'book', (1, 2, 3): 'nothing'}

accessing elements from the dictionary

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

If we use the square brackets [] , KeyError is raised in case a key is not found
in the dictionary. On the other hand, the get() method returns None if the key
is not found.

# creating a dictionary of different data types


my_dict = {"first":"edualgo",1:"book",(1,2,3):"nothing"}

# accessing through key


print(my_dict["first"])

83
print(my_dict[1])
print(my_dict[(1,2,3)])

# accessing through key by using get method


print(my_dict.get(1))
print(my_dict.get(3))

# trying to access a non-existing key


try:
   print(my_dict[3])
except:
   print("An error occured")

OUTPUT :

edualgo
book
nothing
book
None
An error occured

changing and adding dictionary elements

Dictionaries are mutable. We can add new items or change the value of existing
items using an assignment operator.

If the key is already present, then the existing value gets updated. In case the
key is not present, a new (key: value) pair is added to the dictionary.

# creating a dictionary of different data types


my_dict = {"first":"edualgo",1:"book",(1,2,3):"nothing"}

my_dict["first"] = "banana"
print(my_dict)

my_dict["second"] = "coconut"
print(my_dict)

OUTPUT :

{'first': 'banana', 1: 'book', (1, 2, 3): 'nothing'}


{'first': 'banana', 1: 'book', (1, 2, 3): 'nothing', 'second':
'coconut'}

84
removing elements from the dictionary

We can remove a particular item in a dictionary by using the pop() method.


This method removes an item with the provided key and returns the value .

# creating a dictionary of different data types


my_dict = {"first":"edualgo",1:"book",(1,2,3):"nothing"}

my_dict.pop("first")
print(my_dict)

OUTPUT :

{1: 'book', (1, 2, 3): 'nothing'}

Dictionary Comprehension

Dictionary comprehension is an elegant and concise way to create a new


dictionary.

Dictionary comprehension consists of an expression pair (key: value) followed


by a for statement inside curly braces {} .

# creating a dictionary
cubes = {i: i**3 for i in range(10)}

# printing the dictionary out


print(cubes)

OUTPUT :

{0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512,


9: 729}

It's just similar to that of list comprehension.

Exercise your way out

1. Write a Python script to sort (ascending and descending) a dictionary by


value.

2. Write a Python script to concatenate following dictionaries to create a new


one.

85
Sample Dictionary :
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

3. Write a Python script to check whether a given key already exists in a


dictionary.

4. Write a Python program to iterate over dictionaries using for loops.

5. Write a Python script to print a dictionary where the keys are numbers
between 1 and 15 (both included) and the values are square of keys.

Sample Dictionary
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81,
10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}

Python import statement and scope


When our program grows bigger, it is a good idea to break it into different
modules.

A module is a file containing Python definitions and statements. Python


modules have a filename and end with the extension .py . Definitions/methods
inside a module can be imported to another module or the interactive
interpreter in Python. We use the import keyword to do this.

For example, we can import the math module, which is in-built by typing the
following line:

import math
print(math.pi)

3.141592653589793

import sys
print(sys.path)

86
['C:\\Users\\Abhijit Tripathy', 'C:\\Users\\Abhijit
Tripathy\\AppData\\Roaming\\nltk_data', 'C:\\Users\\Abhijit
Tripathy\\tic tac toe game', 'C:\\Users\\Abhijit Tripathy',
'C:\\Users\\Abhijit Tripathy\\Anaconda3\\python37.zip',
'C:\\Users\\Abhijit Tripathy\\Anaconda3\\DLLs',
'C:\\Users\\Abhijit Tripathy\\Anaconda3\\lib',
'C:\\Users\\Abhijit Tripathy\\Anaconda3', '', 'C:\\Users\\Abhijit
Tripathy\\AppData\\Roaming\\Python\\Python37\\site-packages',
'C:\\Users\\Abhijit Tripathy\\Anaconda3\\lib\\site-packages',
'C:\\Users\\Abhijit Tripathy\\Anaconda3\\lib\\site-
packages\\win32', 'C:\\Users\\Abhijit
Tripathy\\Anaconda3\\lib\\site-packages\\win32\\lib',
'C:\\Users\\Abhijit Tripathy\\Anaconda3\\lib\\site-
packages\\Pythonwin', 'C:\\Users\\Abhijit
Tripathy\\Anaconda3\\lib\\site-packages\\IPython\\extensions',
'C:\\Users\\Abhijit Tripathy\\.ipython']

Python variable scope

A scope is the portion of a program from where a variable can be accessed


directly without any prefix.

At any given moment, there are at least three nested scopes.

1. Scope of the current function which has local names


2. Scope of the module which has global names
3. Outermost scope which has built-in names

When a reference is made inside a function, the name is searched in the local
namespace, then in the global namespace and finally in the built-in namespace.
If there is a function inside another function, a new scope is nested inside the
local scope.

 
87
Programming Problems in Python
In the following programs, try to solve each one of them using OOP methods
and prefer taking user input instead of using hardcoded values. Try to use the
entire concepts that you have learnt from the book. Obviously, we are not
going to provide the solutions because we want to come up with the solution
by yourself, that's the best programming practice.

1. Write a python program to add two numbers using functions.

2. Write a python program to find the factorial of a number.

3. Write a python program to calculate simple interest.

4. Write a python program to calculate compound interest.

5. Given a number x, determine whether the given number is Armstrong


number or not. A positive integer of n digits is called an Armstrong number
of order n (order is number of digits) if.

6. Write a python program to find the area of a circle.

7. Write a python script to print all prime numbers in an interval.

8. Write a program to print ASCII value of a character.

9. Write a program for the sum of squares of the first n natural number.

10. Write a program for the sum of cubes of first n natural numbers.

11. Write a python program to interchange first and last elements in a list.

12. Write a python program to swap two elements in a list.

13. Write a python program to find N largest elements from a list.

14. Write a python program to print even numbers in a list.

15. Write a python program to print odd numbers in a list.

16. Write a python program to add two matrices.

17. Write a python program to multiply two matrices.

18. Write a python program to find the transpose of a matrix.

19. Write a python program to get the Kth column of the matrix.

20. Write a python program to check if a string is palindromic or not.

21. Write a python program to reverse the words in a given string.

22. Write a python program to convert from snake case to camel and pascal
case.

88
23. Write a python program to print event length words in the string.

24. Write a python program to accept the string which contains all vowels.

25. Write a python program to remove all duplicates from the string.

26. Write a Python program to read file word by word.

27. Write a Python program to read character by character from a file.

28. Write a Python program to get number of characters, words, spaces and
lines in a file.

29. Write a Python program to Count the Number of occurrences of a key-


value pair in a text file.

30. Write a Python Program to obtain the line number in which given word is
present.

31. Write a Python program to count number of lines in a text file in Python.

32. Write a Python Program to remove lines starting with any prefix.

33. Write a Python Program to Eliminate repeated lines from a file.

34. Write a Python Program to read List of Dictionaries from file.

35. Write a python program to Append content of one text file to another.

36. Write a Python program to copy odd lines of one file to other.

37. Write a Python Program to merge two files into a third file.

38. Write a Python program to Reverse a single line of a text file.

39. Write a Python program to reverse the content of a file and store it in
another file.

40. Write a Python program to create a set.

41. Write a Python program to iterate over sets.

42. Write a Python program to add member(s) in a set.

43. Write a Python program to remove item(s) from set

44. Write a Python program to remove an item from a set if it is present in the
set.

45. Write a Python program to create an intersection of sets.

46. Write a Python program to create a union of sets.

47. Write a Python program to create set difference.

48. Write a Python program to create a symmetric difference.

49. Write a Python program to check if a set is a subset of another set.

89
50. Write a Python program to create a shallow copy of sets. (Note : Shallow
copy is a bit-wise copy of an object. A new object is created that has an
exact copy of the values in the original object.)

51. Write a Python program to clear a set.

52. Write a Python program to use of frozensets (Note: Frozensets behave just
like sets except they are immutable.)

53. Write a Python program to find maximum and the minimum value in a set.

54. Write a Python program to find the length of a set.

55. Write a Python program to check if a given value is present in a set or not.

56. Write a Python program to check if two given sets have no elements in
common.

57. Write a Python program to check if a given set is superset of itself and
superset of another given set.

58. Write a Python program to find the elements in a given set that are not in
another set.

59. Write a Python program to check a given set has no elements in common
with other given set

60. Write a Python program to remove the intersection of a 2nd set from the
1st set.

61. Write a Python function that takes a sequence of numbers and determines
whether all the numbers are different from each other.

62. Write a Python program to create all possible strings by using 'a', 'e', 'i', 'o',
'u'. Use the characters exactly once.

63. Write a Python program to remove and print every third number from a list
of numbers until the list becomes empty.

64. Write a Python program to find unique triplets whose three elements gives
the sum of zero from an array of n integers.

65. Write a Python program to create the combinations of 3 digit combo.

66. Write a Python program to print a long text, convert the string to a list and
print all the words and their frequencies.

67. Write a Python program to count the number of each character of a given
text of a text file

68. Write a Python program to get a list of locally installed Python modules.

69. Write a Python program to display some information about the OS where
the script is running.
90
70. Write a Python program to check the sum of three elements (each from an
array) from three arrays is equal to a target value. Print all those three-
element combinations.

Sample data:

X = [10, 20, 20, 20]


Y = [10, 20, 30, 40]
Z = [10, 30, 40, 20]
target = 70

71. Write a Python program to create all possible permutations from a given
collection of distinct numbers.

72. Write a Python program to get all possible two digit letter combinations
from a digit (1 to 9) string.

string_maps =
{
"1": "abc",
"2": "def",
"3": "ghi",
"4": "jkl",
"5": "mno",
"6": "pqrs",
"7": "tuv",
"8": "wxy",
"9": "z"
}

73. Write a Python program to add two positive integers without using the '+'
operator (Note: Use bit wise operations to add two numbers.)

74. Write a Python program to check the priority of the four operators (+, -, *,
/).

75. Write a Python program to get the third side of right angled triangle from
two given sides.

76. Write a Python program to get all strobogrammatic numbers that are of
length n.A strobogrammatic number is a number whose numeral is
rotationally symmetric, so that it appears the same when rotated 180
degrees. In other words, the numeral looks the same right-side up and
upside down (e.g., 69, 96, 1001).

91
For example,

Given n = 2, return ["11", "69", "88", "96"].

Given n = 3, return ['818', '111', '916', '619', '808', '101',


'906', '609', '888', '181', '986', '689']

77. Write a Python program to find the median among three given numbers.

78. Write a Python program to find the value of n where n degrees of number 2
are written sequentially in a line without spaces.

79. Write a Python program to find the number of zeros at the end of a
factorial of a given positive number. Range of the number(n): (
).

80. Write a Python program to create a sequence where the first four members
of the sequence are equal to one, and each successive term of the
sequence is equal to the sum of the four previous ones. Find the Nth
member of the sequence.

81. Write a Python program that accept a positive number and subtract from
this number the sum of its digits and so on. Continues this operation until
the number is positive.

82. Write a Python program to find the number of divisors of a given integer is
even or odd.

83. Write a Python program to find the digits which are absent in a given
mobile number.

84. Write a Python program to compute the summation of the absolute


difference of all distinct pairs in an given array (non-decreasing order).

Sample array: [1, 2, 3]


Then all the distinct pairs will be:
1 2
1 3
2 3

85. Write a Python program to find the type of the progression (arithmetic
progression/geometric progression) and the next successive member of a
given three successive members of a sequence. According to Wikipedia, an
arithmetic progression (AP) is a sequence of numbers such that the
difference of any two successive members of the sequence is a constant.
For instance, the sequence 3, 5, 7, 9, 11, 13, . . . is an arithmetic progression
with common difference 2. For this problem, we will limit ourselves to
92
arithmetic progression whose common difference is a non-zero integer. On
the other hand, a geometric progression (GP) is a sequence of numbers
where each term after the first is found by multiplying the previous one by
a fixed non-zero number called the common ratio. For example, the
sequence 2, 6, 18, 54, . . . is a geometric progression with common ratio 3.
For this problem, we will limit ourselves to geometric progression whose
common ratio is a non-zero integer.

86. Write a Python program to print the length of the series and the series
from the given 3rd term, 3rd last term and the sum of a series.

Sample Data:
Input third term of the series: 3
Input 3rd last term: 3
Sum of the series: 15
Length of the series: 5
Series:
1 2 3 4 5

87. Write a Python program to find common divisors between two numbers in
a given pair.

88. Write a Python program to count the number of carry operations for each
of a set of addition problems. According to Wikipedia " In elementary
arithmetic, a carry is a digit that is transferred from one column of digits to
another column of more significant digits. It is part of the standard
algorithm to add numbers together by starting with the rightmost digits
and working to the left. For example, when 6 and 7 are added to make 13,
the "3" is written to the same column and the "1" is carried to the left".

89. Write a python program to find heights of the top three building in
descending order from eight given buildings.

Input:
0 <= height of building (integer) <= 10,000
Input the heights of eight buildings:
25
35
15
16
30
45
37
39
Heights of the top three buildings:
93
45
39
37

90. Write a Python program which solve the equation

Print the values of x, y where a, b, c, d, e and f are given.

input:
a,b,c,d,e,f separated by a single space.
(-1,000 <= a,b,c,d,e,f <= 1,000)
Input the value of a, b, c, d, e, f:
5 8 6 7 9 4
Values of x and y:
-2.000 2.000

91. Write a Python program to compute the amount of the debt in n months.
The borrowing amount is $100,000 and the loan adds 5% interest of the
debt and rounds it to the nearest 1,000 above month by month.

Input:
An integer n (0 <= n <= 100)
Input number of months: 7
Amount of debt: $144000

92. Write a Python program which reads an integer n and find the number of
combinations of a,b,c and d (0 <= a,b,c,d <= 9) where (a + b + c + d) will be
equal to n.

Input:
n (1 <= n <= 50)
Input the number(n): 15
Number of combinations: 592

93. Write a program to compute the radius and the central coordinate (x, y) of
a circle which is constructed by three given points on the plane surface.

94
Input:
x1, y1, x2, y2, x3, y3 separated by a single space.
Input three coordinate of the circle:
9 3 6 8 3 6
Radius of the said circle:
3.358
Central coordinate (x, y) of the circle:
6.071 4.643

94. Write a Python program to check whether a point (x,y) is in a triangle or


not. There is a triangle formed by three points.

Input:
x1,y1,x2,y2,x3,y3,xp,yp separated by a single space.
Input three coordinate of the circle:
9 3 6 8 3 6
Radius of the said circle:
3.358
Central coordinate (x, y) of the circle:
6.071 4.643

95. Write a Python program to compute and print sum of two given integers
(more than or equal to zero). If given integers or the sum have more than
80 digits, print "overflow".

input first integer:


25
Input second integer:
22
Sum of the two integers: 47

96. Write a Python program that accepts six numbers as input and sorts them
in descending order.

Input:
Input consists of six numbers n1, n2, n3, n4, n5, n6 (-100000
<= n1, n2, n3, n4, n5, n6 <= 100000). The six numbers are
separated by a space.
Input six integers:
15 30 25 14 35 40
After sorting the said integers:
40 35 30 25 15 14

95
97. Write a Python program to test whether two lines PQ and RS are parallel.
The four points are P(x1, y1), Q(x2, y2), R(x3, y3), S(x4, y4).

Input:
x1,y1,x2,y2,x3,y3,xp,yp separated by a single space
Input x1,y1,x2,y2,x3,y3,xp,yp:
2 5 6 4 8 3 9 7
PQ and RS are not parallel

98. Write a Python program to find the maximum sum of a contiguous


subsequence from a given sequence of numbers a1, a2, a3, ... an. A
subsequence of one element is also a continuous subsequence.

Input:
You can assume that 1 <= n <= 5000 and -100000 <= ai <=
100000.
Input numbers are separated by a space.
Input 0 to exit.
Input number of sequence of numbers you want to input (0 to
exit):
3
Input numbers:
2
4
6
Maximum sum of the said contiguous subsequence: 12
Input number of sequence of numbers you want to input (0 to
exit):
0

99. There are two circles C1 with radius r1, central coordinate (x1, y1) and C2
with radius r2 and central coordinate (x2, y2).

Write a Python program to test the followings -

"C2 is in C1" if C2 is in C1

"C1 is in C2" if C1 is in C2

"Circumference of C1 and C2 intersect" if circumference of C1 and C2


intersect, and

"C1 and C2 do not overlap" if C1 and C2 do not overlap.

96
Input:
Input numbers (real numbers) are separated by a space.
Input x1, y1, r1, x2, y2, r2:
5 6 4 8 7 9
C1 is in C2

100. Write a Python program which reads a text (only alphabetical characters
and spaces.) and prints two words. The first one is the word which is arise
most frequently in the text. The second one is the word which has the
maximum number of letters.

Input:
A text is given in a line with following condition:
a. The number of letters in the text is less than or equal to
1000.
b. The number of letters in a word is less than or equal to
32.
c. There is only one word which is arise most frequently in
given text.
d. There is only one word which has the maximum number of
letters in given text.
Input text: Thank you for your comment and your participation.
Output: your participation.

101. Write a Python program that reads n digits (given) chosen from 0 to 9 and
prints the number of combinations where the sum of the digits equals to
another given number (s). Do not use the same digits in a combination.

Input:
Two integers as number of combinations and their sum by a
single space in a line. Input 0 0 to exit.
Input number of combinations and sum, input 0 0 to exit:
5 6
2 4
0 0
2

102. Write a Python program which reads the two adjoined sides and the
diagonal of a parallelogram and check whether the parallelogram is a
rectangle or a rhombus.

97
Input:
Two adjoined sides and the diagonal.
1 <= ai, bi, ci <= 1000, ai + bi > ci
Input two adjoined sides and the diagonal of a parallelogram
(comma separated):
3,4,5
This is a rectangle.

103. Write a Python program to replace a string "Python" with "Java" and "Java"
with "Python" in a given string.

Input:
English letters (including single byte alphanumeric
characters, blanks, symbols) are given on one line. The length
of the input character string is 1000 or less.
Input a text with two words 'Python' and 'Java'
Python is popular than Java
Java is popular than Python

104. Write a Python program to find the difference between the largest integer
and the smallest integer which are created by 8 numbers from 0 to 9. The
number that can be rearranged shall start with 0 as in 00135668.

Input:
Input an integer created by 8 numbers from 0 to 9.:
2345
Difference between the largest and the smallest integer from
the given integer:
3087

105. Write a Python program to compute the sum of first n given prime
numbers.

106. if you draw a straight line on a plane, the plane is divided into two regions.
For example, if you pull two straight lines in parallel, you get three areas,
and if you draw vertically one to the other you get 4 areas.

Write a Python program to create maximum number of regions obtained


by drawing n given straight lines.

98
Input:
(1 <= n <= 10,000)
Input number of straight lines (o to exit):
5
Number of regions:
16

107. There are four different points on a plane, P(xp,yp), Q(xq, yq), R(xr, yr) and
S(xs, ys). Write a Python program to test AB and CD are orthogonal or not.

Input:
xp,yp, xq, yq, xr, yr, xs and ys are -100 to 100 respectively
and each value can be up to 5 digits after the decimal point
It is given as a real number including the number of. Output:
Output AB and CD are not orthogonal! or AB and CD are
orthogonal!.

108. Write a Python program to sum of all numerical values (positive integers)
embedded in a sentence. Write a Python program to create maximum
number of regions obtained by drawing n given straight lines.

Input:
Sentences with positive integers are given over multiple
lines. Each line is a character string containing one-byte
alphanumeric characters, symbols, spaces, or an empty line.
However the input is 80 characters or less per line and the
sum is 10,000 or less.
Input some text and numeric values ( to exit):
Sum of the numeric values: 80
None
Input some text and numeric values ( to exit):
Sum of the numeric values: 17
None
Input some text and numeric values ( to exit):
Sum of the numeric values: 10
None

109. There are 10 vertical and horizontal squares on a plane. Each square is
painted blue and green. Blue represents the sea, and green represents the
land. When two green squares are in contact with the top and bottom, or
right and left, they are said to be ground. The area created by only one
green square is called "island". For example, there are five islands in the
figure below.

99
Write a Python program to read the mass data and find the number of
islands.

Input:
Input 10 rows of 10 numbers representing green squares
(island) as 1 and blue squares (sea) as zeros
1100000111
1000000111
0000000111
0010001000
0000011100
0000111110
0001111111
1000111110
1100011100
1110001000
Number of islands:
5

110. When character are consecutive in a string , it is possible to shorten the


character string by replacing the character with a certain rule. For example,
in the case of the character string YYYYY, if it is expressed as # 5 Y, it is
compressed by one character.

Write a Python program to restore the original string by entering the


compressed string with this rule. However, the # character does not appear
in the restored character string. Note: The original sentences are uppercase
letters, lowercase letters, numbers, symbols, less than 100 letters, and
consecutive letters are not more than 9 letters.

Input:
The restored character string for each character on one line.
Original text: XY#6Z1#4023
XYZZZZZZ1000023
Original text: #39+1=1#30
999+1=1000

111. A convex polygon is a simple polygon in which no line segment between


two points on the boundary ever goes outside the polygon. Equivalently, it
is a simple polygon whose interior is a convex set. In a convex polygon, all
interior angles are less than or equal to 180 degrees, while in a strictly
convex polygon all interior angles are strictly less than 180 degrees.

100
Write a Python program that compute the area of the polygon . The
vertices have the names vertex 1, vertex 2, vertex 3, ... vertex n according to
the order of edge connections

Note: The original sentences are uppercase letters, lowercase letters,


numbers, symbols, less than 100 letters, and consecutive letters are not
more than 9 letters.

Input:
Input is given in the following format.
x1 , y1
x2 , y2
:
xn , yn
xi , yi are real numbers representing the x and y coordinates
of vertex i , respectively.
Input the coordinates (ctrl+d to exit):
1.0, 0.0
0.0, 0.0
1.0, 1.0
2.0, 0.0
-1.0, 1.0
Area of the polygon;
1.50000000.

112. Internet search engine giant, such as Google accepts web pages around the
world and classify them, creating a huge database. The search engines also
analyze the search keywords entered by the user and create inquiries for
database search. In both cases, complicated processing is carried out in
order to realize efficient retrieval, but basics are all cutting out words from
sentences.

Write a Python program to cut out words of 3 to 6 characters length from a


given sentence not more than 1024 characters.

Input:
English sentences consisting of delimiters and alphanumeric
characters are given on one line.
Input a sentence (1024 characters. max.)
The quick brown fox
3 to 6 characters length of words:
The quick brown fox

101
113. Arrange integers (0 to 99) as narrow hilltop, as illustrated in Figure 1.
Reading such data representing huge, when starting from the top and
proceeding according to the next rule to the bottom. Write a Python
program that compute the maximum value of the sum of the passing
integers.

Input:
A series of integers separated by commas are given in
diamonds. No spaces are included in each line. The input
example corresponds to Figure 1. The number of lines of data
is less than 100 lines.
Output:
The maximum value of the sum of integers passing according to
the rule on one line.
Input the numbers (ctrl+d to exit):
8
4, 9
9, 2, 1
3, 8, 5, 5
5, 6, 3, 7, 6
3, 8, 5, 5
9, 2, 1
4, 9
8
Maximum value of the sum of integers passing according to the
rule on one line.
64

114. Given a list of numbers and a number k, write a Python program to check
whether the sum of any two numbers from the list is equal to k or not.

For example, given [1, 5, 11, 5] and k = 16, return true since 11 + 5 is 16.

Sample Input:
([12, 5, 0, 5], 10)
([20, 20, 4, 5], 40)
([1, -1], 0)
([1, 1, 0], 0)
Sample Output:
True
True
True
False

102
115. Write a Python program to find the longest common prefix string amongst
a given array of strings. Return false If there is no common prefix.

For Example, longest common prefix of "abcdefgh" and "abcefgh" is "abc".

Sample Input:
["abcdefgh","abcefgh"]
["w3r","w3resource"]
["Python","PHP", "Perl"]
["Python","PHP", "Java"]
Sample Output:
abc
w3r
P

116. Write a Python program to reverse only the vowels of a given string.

Sample Input:
("w3resource")
("Python")
("Perl")
("USA")
Sample Output:
w3resuorce
Python
Perl
ASU

117. Write a Python program to calculate the maximum profit from selling and
buying values of stock. An array of numbers represent the stock prices in
chronological order.

For example, given [8, 10, 7, 5, 7, 15], the function will return 10, since the
buying value of the stock is 5 dollars and sell value is 15 dollars.

Sample Input:
([8, 10, 7, 5, 7, 15])
([1, 2, 8, 1])
([])
Sample Output:
10
7
0

103
118. Write a Python program to remove all instances of a given value from a
given array of integers and find the length of the new array.

Sample Input:
([1, 2, 3, 4, 5, 6, 7, 5], 5)
([10,10,10,10,10], 10)
([10,10,10,10,10], 20)
([], 1)
Sample Output:
6
0
5
0

119. Write a Python program to find the starting and ending position of a given
value in a given array of integers, sorted in ascending order.

If the target is not found in the array, return [0, 0].

Input: [5, 7, 7, 8, 8, 8] target value = 8


Output: [0, 5]
Input: [1, 3, 6, 9, 13, 14] target value = 4
Output: [0, 0]

120. Write a Python program that accept two strings and test if the letters in the
second string are present in the first string.

Sample Input:
["python", "ypth"]
["python", "ypths"]
["python", "ypthon"]
["123456", "01234"]
["123456", "1234"]
Sample Output:
True
False
True
False
True

104
Try Something New
Print the following patterns for the given number of rows N,

****
***
**
*

****
***    
**
  *

A
BB
CCC

1111
000
11
0

E
DE
CDE
BCDE
ABCDE

1
3 2
4 5 6
10 9 8 7
11 12 13 14 15

ABCCBA
ABBA
AA

333
233
123

105
0
101
21012

*
**
***
****
***
**
*

  1
  123
12345
1234567
12345
  123
  1

  1
        232
      34543
    4567654
  567898765

*
***
*****
***
*

*
* *
  * * *
    * * * *
  * * *
* *
*

106
4444444
4333334
4322234
4321234
4322234
4333334  
4444444

*********
**** ****
***   ***
**     **
*       *
**     **
***   ***
**** ****
*********

1       1
2     2
3   3
  4 4
  5
  4 4
3   3
2     2
1       1

*       *
*     *
* *   * *
* * * *
* * * * *
* * * *
* *   * *
*     *
*       *

1
23
4567
89123456
7891234567891234
107
Reference

All the programming problems & their solutions, mentioned above are
available on internet. It was taken from different programming contests
and sites to maintain the current trend and standards of programming
problems.

End of the book


As the book has now came to an end, I hope you have enjoyed the book and
the essence of Python programming language. The most important thing about
python is that, it's opensource. Open source licensing encourages innovation
through collaboration. Without it, many of the technologies we take for granted
today would never have developed, or would be locked away behind patent
law. The open source movement is the reason that technology has developed
at such a breakneck pace for the past few decades. Every year/ session a lot of
new features are added to the python programming language that makes it
more modern and more easier to achieve the complex tasks.

As soon as you complete the book and learned so much about programming in
python, there is a hunger to learn more. The next step being jumping into "Data
Structures and Algorithms" and cover topics like different sorting, searching,
graph, tree, heaps based algorithms by using different new data structures like
stack, queue, binary tree, linked list, array etc. The syntax changes with each
language but the concept of the algorithm remains the same in almost every
language.

I am suggesting a two important books below, from my experience, to learn


Data Structures and Algorithms in python,.

Introduction to Algorithms by Thomas H. Cormen, Charles E. Leiserson,


Ronald L. Rivest, and Clifford Stein(also known as CLRS in the industry)
Cracking the coding interview - Gayle Laakmann McDowell (Best book to
practice problems)

Keep Hustling ! Keep Programming

Abhijit Tripathy

Founder @eduAlgo, Writer

 
108
 

109
 

You might also like