A Beginner - S Guide To Python
A Beginner - S Guide To Python
Python
ABHIJIT TRIPATHY
Founder, eduAlgo
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 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
05 Conditional Statements 15
06 Operators in python 19
07 Loops in python 22
09 Functions in python 30
11 Encapsulation in python 43
12 Inheritance in python 46
15 Python lists 61
16 Python tuples 71
18 Python sets 77
19 Python dictionary 83
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.
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.
As it can be clearly seen in the above piece of code, it contains mainly three
components,
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.
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.
Let's begin !
2
Experiment No - 01
Experiment No - 02
Experiment No - 03
Experiment No - 04
Experiment No - 05
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
+ plus Addition
- minus Subtraction
* asterisk Multiplication
% percent Division
# 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.
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
Experiment No - 02
Experiment No - 03
5
For example,
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.
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
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,
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,
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.
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.
8
OUTPUT:
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.
OUTPUT:
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
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))
Q - Write your biodata in a text format as shown below, by using variables and
string formatting,
10
Q - Write a paragraph to summarize your previous semester marks, by using
variables and string formatting,
I am <your_name>
Math - <your_math_marks>
Physics - <your_physics_marks>
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
11
# use of the '\n' aka the newline escape character
print("Ring the bell \nEnter the home")
OUTPUT:
Q - Write your biodata, with every line in a new line with the help of "\n".
12
Write this code in one of your python files and run it from the terminal,
OUTPUT:
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.
13
age = input("What's your age ?\n")
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.
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.
if( <condition> ):
<some code, when the condition is True>
else:
<some code, when the condition 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:
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.
# 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.
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
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 ?
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
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
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,
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.
Let's check the syntax of both the while and for loop and use them to print
from 1 to 10.
while expression:
statement(s)
22
# declaring an iteration variable
iter_var = 1
OUTPUT:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Nested Loops
Can we place one loop inside another ?
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
To understand nested loops always break the loops in the following way,
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 change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope
are destroyed.
break statement
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
for i in range(0,10):
if(i==7):
pass
else:
print(i,end=" ")
0 1 2 3 4 5 6 8 9
25
0 1 2
1 2 3
2 3 4
26
Syntax
open(filename, mode)
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,
.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.
OUTPUT Terminal:
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 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.
28
The above block of code will add a new line, that has been passed as a string in
the file.write() function.
Experiment No 1
Experiment No 2
with open("edualgo.txt",'r') as f:
print(f.read())
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.
# 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.
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.
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.
def area(length,breadth):
return length*breadth
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.
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:
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")
OUTPUT:
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")
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")
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
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
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.
Syntax:
class ClassName:
# Statement-1
<Attributes>
<member functions>
# Statement-N
# syntax for creating an object
ObjectName = ClassName()
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.
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()
OUTPUT:
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.
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>
book1.print_details()
OUTPUT :
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 ?
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)
OUTPUT :
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.
41
book3 = Library("A beginner's guide to Machine Learning","Machine
Learning","Abhijit Tripathy",3)
OUTPUT:
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
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
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.
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.
OUTPUT:
-----------------------------------------------------------------
----------
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)
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.
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.
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__() .
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.
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.
Hierarchical inheritance
When more than one derived class are constructed from a single base class we
call it as Hierarchical inheritance.
Hybrid inheritance:
If more than one form of inheritance is present then it's known as Hybrid
inheritance.
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.
OUTPUT:
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.
53
-----------------------------------------------------------------
----------
TypeError Traceback (most recent
call last)
<ipython-input-5-7af7a86df8ea> in <module>
10 parker = Student(32,78)
11
---> 12 print(monty + parker)
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.
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.
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.
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)
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
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 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")
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.
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]
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.
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.
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"]
OUTPUT :
Apple
Orange
Jackfruit
An error occured
We can access a range of items in a list by using the slicing operator : (colon).
This method is also known as slicing.
OUTPUT :
63
changing elements of a list
As the python lists are mutable, their content can be changed by using the
assignment operator ( = ) .
OUTPUT :
[1, 2, 3, 10, 6]
[23, 24, 25, 10, 6]
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.
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.
OUTPUT :
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]
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"]
OUTPUT :
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"]
66
OUTPUT :
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 Comprehension
What if, there is a question to create a list of n integers where the list contains
for
67
# creating an empty list
square_list = []
OUTPUT :
7
[1, 4, 9, 16, 25, 36, 49]
The above program can be achieved easily in very less lines of code,
OUTPUT :
7
[1, 4, 9, 16, 25, 36, 49]
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"]
OUTPUT :
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.
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]]
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 ( ) .
# empty tuple
my_tuple = ()
# tuple of strings
my_tuple = ("Apple","Orange","Banana")
# tuple of integers
my_tuple = (1,4,5)
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.
71
# creating a tuple of items
my_tuple = ("Apple","Orange","Jackfruit")
OUTPUT :
Orange
Orange
Jackfruit
An error occured
We can access a range of items in a tuple by using the slicing operator colon : ,
similar to that of list .
OUTPUT :
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.
OUTPUT :
Error occured
concatenating in a tuple
The + operator can be used for the concatenation of tuples, similar to lists.
73
OUTPUT :
del tuple1
try:
print(tuple1)
except:
print("An error occured")
OUTPUT :
An error occured
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.
Just like lists and tuples we can access characters of a string by indexing and
range of characters by slicing.
OUTPUT :
t
hiji
An error occured
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
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.
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.
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.
We can add a single element using the add() method, and multiple elements
using the update() method.
my_set = {1,2,3,4,5}
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}
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}
OUTPUT :
{1, 2, 4, 5}
{1, 4, 5}
{1, 4, 5}
An error occured
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}
{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}
81
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# using ^ operator
print(A ^ B)
{1, 2, 3, 6, 7, 8}
Method Description
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 dictionary
my_dict = {1:"Apple",2:"Banana"}
print(my_dict)
OUTPUT :
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.
83
print(my_dict[1])
print(my_dict[(1,2,3)])
OUTPUT :
edualgo
book
nothing
book
None
An error occured
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.
my_dict["first"] = "banana"
print(my_dict)
my_dict["second"] = "coconut"
print(my_dict)
OUTPUT :
84
removing elements from the dictionary
my_dict.pop("first")
print(my_dict)
OUTPUT :
Dictionary Comprehension
# creating a dictionary
cubes = {i: i**3 for i in range(10)}
OUTPUT :
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}
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}
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']
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.
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.
19. Write a python program to get the Kth column of the matrix.
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.
28. Write a Python program to get number of characters, words, spaces and
lines in a 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.
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.
39. Write a Python program to reverse the content of a file and store it in
another file.
44. Write a Python program to remove an item from a set if it is present in the
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.)
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.
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.
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:
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,
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.
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
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
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".
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
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).
"C2 is in C1" if C2 is in C1
"C1 is in C2" if C1 is in C2
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.
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
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
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
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.
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.
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.
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.
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.
Abhijit Tripathy
108
109