Python All Chapter
Python All Chapter
Python All Chapter
What is Programming?
Just like we use Hindi or English to communicate with each other, we use a
Programming language to communicate with the computer.
Programming is a way to instruct the computer to perform various tasks.
What is Python?
Python is a simple and easy-to-understand language that feels like reading simple
English. This Pseudo code nature of Python makes it easy to learn and understandable
for beginners.
Features of Python:
Installation
Python can be easily installed from python.org
When you click on the download button, python can be installed right after you
complete the setup by executing the file for your platform.
Tip: Just install it like a game ☻
Copy
Execute this file (.py file) by typing python hello.py, and you will see Hello World printed
on the screen.
Modules
A module is a file containing code written by somebody else (usually) which can be
imported and used in our programs.
Pip
Pip is a package manager for python. You can use pip to install a module on your
system.
E.g., pip install flask (It will install flask module in your system)
Types of modules
There are two types of modules in Python:
a=30
b=‛Harry‛
c=71.22
Copy
Variable – Container to store a value
Keywords – Reserved words in Python
Identifiers – class/function/variable name
Data Types:
Primarily there are the following data types in Python:
1. Integers
2. Floating point numbers
3. Strings
4. Booleans
5. None
Python is a fantastic language that automatically identifies the type of data for us.
a = 71 #Identifies a as
class<int>
b = 88.44 #Identifies b as
class<float>
Copy
Rules for defining a variable name: (Also applicable to other identifiers)
a = 31
type(a) #class<int>
b = ‚31‛
type(b) #class<str>
Copy
A number can be converted into a string and vice versa (if possible)
There are many functions to convert one data type into another.
Copy
… and so on
Here “31” is a string literal, and 31 is a numeric literal.
input() function
This function allows the user to take input from the keyboard as a string.
a = input(‚Enter name‛) #if a is ‚harry‛, the
user entered harry
Copy
Note: The output of the input function is always a string even if the number is entered
by the user.
Suppose if a user enters 34, then this 34 will automatically convert to “34” string literal.
Chapter 3 – Strings
String Slicing:
A string in Python can be sliced for getting a part of the string.
Consider the following string:
The index in a string starts from 0 to (length-1) in Python. To slice a string, we use the
following syntax:
Negative Indices: Negative indices can also be used as shown in the figure above. -1
corresponds to the (length-1) index, -2 to (length-2).
Slicing with skip value
We can provide a skip value as a part of our slice like this:
word = ‚amazing‛
Copy
Other advanced slicing techniques
word = ‘amazing’
Copy
String Functions
Some of the most used functions to perform operations on or manipulate strings are:
len(‘harry’) #Returns 5
Copy
2. endswith(“rry”) : This function tells whether the variable string ends with the string
“rry” or not. If string is “harry”, it returns for “rry” since harry ends with rry.
3. count(“c”) : It counts the total number of occurrences of any character.
4. capitalize() : This function capitalizes the first character of a given string.
5. find(word) : This function finds a word and returns the index of first occurrence of that
word in the string.
6. replace(oldword, newword) : This function replaces the old word with the new word in
the entire string.
<|DATE|>
Copy
Python Lists are containers to store a set of values of any data type.
Copy
The list can contain different types of elements such as int, float, string, Boolean, etc.
Above list is a collection of different types of elements.
List Indexing
A list can be index just like a string.
L1 = [7, 9, ‘harry’]
L1[0] – 7
L1[1] – 9
L1[70] – Error
Copy
List Methods
Consider the following list:
Copy
Tuples in Python:
A tuple is an immutable (can‟t change or modified) data type in Python.
Copy
Once defined, tuple elements can‟t be manipulated or altered.
Tuple methods:
Consider the following tuple,
a = (1, 7, 2)
Copy
a = (7, 0, 8, 0, 0, 9)
Copy
Copy
Properties of Python Dictionaries
1. It is unordered
2. It is mutable
3. It is indexed
4. It cannot contain duplicate keys
Dictionary Methods
Consider the following dictionary,
a = {‚name‛: ‚Harry‛,
‚from‛: ‚India‛,
‚marks‛: [92,98,96]}
Copy
S.add(1)
S.add(2)
# or Set = {1,2}
Copy
If you are a programming beginner without much knowledge of mathematical
operations on sets, you can simply look at sets in python as data types containing
unique values.
Properties of Sets
Operations on Sets
Consider the following set:
S = {1,8,2,3}
Copy
1. Write a program to create a dictionary of Hindi words with values as their English
translation. Provide the user with an option to look it up!
2. Write a program to input eight numbers from the user and display all the unique
numbers (once).
3. Can we have a set with 18(int) and “18”(str) as a value in it?
4. What will be the length of the following set S:
S = Set()
S.add(20)
S.add(20.0)
S.add(‚20‛)
Copy
What will be the length of S after the above operations?
Copy
'''
if (condition1): // if condition 1 is true
print(‚yes‛)
elif (condition2): // if condition 2 is true
print(‚No‛)
else: // otherwise
print(‚May be‛)
'''
Copy
Code example:
a = 22
if (a>9):
print(‚Greater‛)
else:
print(‚lesser‛)
Copy
Quick Quiz: Write a program to print yes when the age entered by the user is greater
than or equal to 18.
Relational Operators
Relational operators are used to evaluate conditions inside if statements. Some
examples of relational operators are:
= = -> equals
<=, etc.
Copy
Logical Operators
In python, logical operators operate on conditional statements. Example:
Copy
elif clause
elif in python means [else if]. If statement can be chained together with a lot of these elif
statements followed by an else statement.
'''
if (condition1):
#code
elif (condition 2):
#code
elif (condition 2):
#code
….
else:
#code '''
Copy
Important Notes:
1. Write a program to find the greatest of four numbers entered by the user.
2. Write a program to find out whether a student is pass or fail if it requires a total of 40%
and at least 33% in each subject to pass. Assume 3 subjects and take marks as an input
from the user.
3. A spam comment is defined as a text containing the following keywords:
“make a lot of money”, “buy now”, “subscribe this”, “click this”. Write a program to
detect these spams.
4. Write a program to find whether a given username contains less than 10 characters or
not.
5. Write a program that finds out whether a given name is present in a list or not.
6. Write a program to calculate the grade of a student from his marks from the following
scheme:
90-100 Ex
80-90 A
70-80 B
60-70 C
50-60 D
<50 F
7. Write a program to find out whether a given post is talking about “Harry” or not.
Sometimes we want to repeat a set of statements in our program. For instance: Print 1
to 1000
Loops make it easy for a programmer to tell the computer, which set of instructions to
repeat, and how!
Types of loops in Python
Primarily there are two types of loops in Python
1. While loop
2. For loop
Copy
In while loops, the condition is checked first. If it evaluates to true, the body of the loop
is executed, otherwise not!
If the loop is entered, the process of condition check and execution is continued until
the condition becomes false.
Quick Quiz: Write a program to print 1 to 50 using a while loop.
An Example:
i = 0
while i<5:
print(‚Harry‛)
i = i+1
Copy
(Above program will print Harry 5 times)
Note: if the condition never becomes false, the loop keeps getting executed.
Quick Quiz: Write a program to print the content of a list using while loops.
For loop
A for loop is used to iterate through a sequence like a list, tuple, or string (iterables)
The syntax of a for loop looks like this:
l = [1, 7, 8]
for item in l:
print(item)
Copy
(Above program will print 1, 7, and 8)
Range function in Python
The range function in python is used to generate a sequence of numbers.
We can also specify the start, stop, and step-size as follows:
range(start, stop, step_size)
Copy
For loop with else
An optional else can be used with a for loop if the code is to be executed when the loop
exhausts.
Example:
l = [1, 7, 8]
for item in l:
print(item)
else:
print(‚Done‛) #This is printed when the loop
exhausts!
Copy
Output:
Done
Copy
The break statement
„break‟ is used to come out of the loop when encountered. It instructs the program to –
Exit the loop now.
Example:
Copy
The continue statement
„continue‟ is used to stop the current iteration of the loop and continue with the next
one. It instructs the program to “skip this iteration.”
Example:
for i in range(4):
print(‚printing‛)
if i == 2: #if i is 2, the iteration is skipped
continue
print(i)
Copy
pass statement
pass is a null statement in python. It instructs to “Do nothing.”
Example:
l = [1, 7, 8]
for item in l:
pass #without pass, the program will throw an
error
Copy
1. Write a program to print the multiplication table of a given number using for loop.
2. Write a program to greet all the person names stored in a list l1 and which starts with S.
Copy
*
***
Copy
**
*** for n = 3
Copy
* * *
* * #For n=3
* * *
Copy
10. Write a program to print the multiplication table of n using for loop in reversed
order.
def func1():
print(‚Hello‛)
Copy
This function can be called any number of times, anywhere in the program.
Function call
Whenever we want to call a function, we put the name of the function followed by
parenthesis as follows:
Copy
Function definition
The part containing the exact set of instructions that are executed during the function
call.
Quick Quiz: Write a program to greet a user with “Good day” using functions.
Types of functions in Python
There are two types of functions in Python:
def greet(name):
gr = ‚Hello‛ + name
return gr
Copy
Copy
Default Parameter Value
We can have a value as the default argument in a function.
If we specify name = “stranger” in the line containing def, this value is used when no
argument is passed.
For Example:
def greet(name=’stranger’):
#function body
Copy
Copy
Recursion
Recursion is a function which calls itself.
It is used to directly use a mathematical formula as a function. For example:
factorial(n) = n * factorial(n-1)
Copy
This function can be defined as follows:
def factorial(n):
if i == 0 or i == 1 : #Base condition which doesn’t call
the function any further
return i
else:
return n*factorial(n-1) #Function calling itself
Copy
This works as follows:
The programmer needs to be extremely careful while working with recursion to ensure
that the function doesn‟t infinitely keep calling itself.
Recursion is sometimes the most direct way to code an algorithm.
1. Write a program using the function to find the greatest of three numbers.
2. Write a python program using the function to convert Celsius to Fahrenheit.
3. How do you prevent a python print() function to print a new line at the end?
4. Write a recursive function to calculate the sum of first n natural numbers.
5. Write a python function to print the first n lines of the following pattern.
***
** #For n = 3
*
Copy
We all have played snake, water gun game in our childhood. If you haven‟t, google the
rules of this game and write a Python program capable of playing this game with the
user.
The random access memory is volatile, and all its contents are lost once a program
terminates.
In order to persist the data forever, we use files.
A file is data stored in a storage device. A python program can talk to the file by reading
content from it and writing content to it.
Types of Files
There are 2 types of files:
Python has a lot of functions for reading, updating, and deleting files.
Opening a file
Python has an open() function for opening files. It takes 2 parameters: filename and
mode.
open(‚this.txt‛, ‚r‛)
Copy
Here, “this” is the file name and “r” is the mode of opening (read mode)
Reading a file in Python
Copy
We can also specify the number of characters in read() function:
Copy
Other methods to read the file
We can also use f.readline() function to read one full line at a time.
Copy
Modes of opening a file
r – open for reading
w – open for writing
a – open for appending
+ -> open for updating
„rb‟ will open for read in binary mode
„rt‟ will open for read in text mode
Writing Files in Python
In order to write to a file, we first open it in write or append mode, after which, we use
the python‟s f.write() method to write to the file!
f = open(‚this.txt‛, ‚w‛)
f.close()
Copy
With statement
The best way to open and close the file automatically is the “with” statement.
with open(‚this.txt‛) as f:
f.read()
Copy
#There is no need to write f.close() as it is done automatically
1. Write a program to read the text from a given file, “poems.txt” and find out whether it
contains the word „twinkle‟.
2. The game() function in a program lets a user play a game and returns the score as an
integer. You need to read a file “Hiscore.txt” which is either blank or contains the
previous Hi-score. You need to write a program to update the Hi-score whenever
game() breaks the Hi-Score.
3. Write a program to generate multiplication tables from 2 to 20 and write it to the
different files. Place these files in a folder for a 13- year old boy.
4. A file contains the word “Donkey” multiple times. You need to write a program which
replaces this word with ###### by updating the same file.
5. Repeat program 4 for a list of such words to be censored.
6. Write a program to mine a log file and find out whether it contains „python‟.
7. Write a program to find out the line number where python is present from question 6.
8. Write a program to make a copy of a text file “this.txt.”
9. Write a program to find out whether a file is identical and matches the content of
another file.
10. Write a program to wipe out the contents of a file using python.
11. Write a python program to rename a file to “renamed_by_python.txt.”
Copy
Object
An object is an instantiation of a class. When class is defined, a template(info) is defined.
Memory is allocated only after object instantiation.
Objects of a given class can invoke the methods available to it without revealing the
implementation details to the user. #Abstraction & Encapsulation!
Modelling a problem in OOPs
We identify the following in our problem
Noun -> Class -> Employee
Adjective -> Attributes -> name,age,salary
Verbs -> Methods -> getSalary(), increment()
Class Attributes
An attribute that belongs to the class rather than a particular object.
Example:
Class Employee:
company = ‚Google‛ #Specific to each class
harry = Employee() #Object instantiation
harry.company
Employee.company = ‚YouTube‛ #changing class attribute
Copy
Instance Attributes
An attribute that belongs to the Instance (object)
Assuming the class from the previous example:
harry.name = ‚Harry‛
harry.salary = ‚30K‛ #Adding instance attributes
Copy
Note: Instance attributes take preference over class attributes during assignment and
retrieval.
harry.attribute1 :
„self‟ parameter
self refers to the instance of the class.
It is automatically passed with a function call from an object.
harry.getSalary()
Copy
here, self is harry, and the above line of code is equivalent to Employee.getSalary(harry)
This function getsalary is defined as:
class Employee:
company = ‚Google‛
def getSalary(self):
print(‚Salary is not there‛)
Copy
Static method
Sometimes we need a function that doesn‟t use the self-parameter. We can define a
static method like this:
Copy
__init__() constructor
__init__() is a special method which runs as soon as the object is created.
__init__() method is also known as constructor.
It takes self-argument and can also take further arguments.
For Example:
class Employee:
def __init__(self,name):
self.name = name
def getSalary(self):
#Some code…
harry = Employee(‚Harry‛) #Object can be instantiated
using constructor like this!
Copy
Copy
We can use the methods and attributes of Employee in Programmer object.
Also, we can overwrite or add new attributes and methods in the Programmer class.
Type of Inheritance
1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
Single Inheritance
Single inheritance occurs when a child class inherits only a single parent class.
Base -> Derived
Multiple Inheritance
Multiple inheritances occurs when the child class inherits from more than one parent
class.
Multilevel Inheritance
When a child class becomes a parent for another child class.
Super() method
Super method is used to access the methods of a superclass in the derived class.
Copy
Class methods
A class method is a method which is bound to the class and not the object of the class.
@classmethod decorator is used to create a class method.
Syntax to create a class method:
@classmethod
def (cls, p1, p2):
#code
Copy
@property decorators
Consider the following class
class Employee:
@property
def name(self):
return self.ename
Copy
if e = Employee() is an object of class employee, we can print (e.name) top print the
ename/call name() function.
@.getters and @.setters
The method name with @property decorator is called getter method.
We can define a function + @name.setter decorator like below:
@name.setter
def name(self, value):
self.ename = value
Copy
Operator overloading in Python
Operators in python can be overloaded using dunder methods.
These methods are called when a given operator is used on the objects.
Operators in python can be overloaded using the following methods:
p1 + p2 -> p1.__add__(p2)
p1 – p2 -> p1.__sub__(p2)
p1 * p2 -> p1.__mul__(p2)
p1 / p2 -> p1.__truediv__(p2)
p1 // p2 -> p1.__floordiv__(p2)
Copy
Other dunder/magic methods in Python
Copy
1. Create a class C-2d vector and use it to create another class representing a 3-d vector.
2. Create a class of pets from a class Animals and further create class Dog from Pets. Add a
method bark to class Dog.
3. Create a class Employee and add salary and increment properties to it.
4. Write a class complex to represent complex numbers, along with overloaded operators
+ and * which adds and multiplies them.
5. Write a class vector representing a vector of n dimension. Overload the + and * operator
which calculates the sum and the dot product of them.
6. Write __str__() method to print the vector as follows:
7i + 8j + 10k
Copy
Assume vector of dimension 3 for this problem.
7. Override the __len__() method on vector of problem 5 to display the dimension of the
vector.
We are going to write a program that generates a random number and asks the user to
guess it.
If the player‟s guess is higher than the actual number, the program displays “Lower
number please”. Similarly, if the user‟s guess is too low, the program prints “higher
number please”.
When the user guesses the correct number, the program displays the number of
guesses the player used to arrive at the number.
Hint: Use the random module
'''
try:
#code #Code that might throw an exception
except Exception as e:
print(e)
'''
Copy
When the exception is handled, the code flow continues without program interruption.
We can also specify the exceptions to catch like below:
'''
try:
#code
except ZeroDivisionError:
#code
except TypeError:
#code
except:
#code (All other exceptions are handled here)
'''
Copy
Raising Exceptions
We can raise custom exceptions using the raise keyword in python.
try with else clause
Sometimes we want to run a piece of code when try was successful.
'''
try:
#some code
except:
#some code
else:
#Code (This is executed only if the try was successful)
'''
Copy
try with finally
Python offers a finally clause which ensures execution of a piece of code irrespective of
the exception.
'''
try:
#some code
except:
#some code
finally:
#some code (executed regardless of error!)
'''
Copy
if __name__==‟__main__‟ in Python
__name__ evaluates to the name of the module in Python from where the program is
ran.
If the module is being run directly from the command line, the __name__ is set to string
“__main__”.
Thus this behavior is used to check whether the module is run directly or imported to
another file.
The global keyword
global keyword is used to modify the variable outside of the current scope.
enumerate function in Python
The enumerate function adds counter to an iterable and returns it.
Copy
List comprehensions
List comprehensions is an elegant way to create lists based on existing lists.
list1 = [1, 7, 12, 11, 22]
list2 = [i for item in list1 if item>8]
1. Write a program to open three files 1.txt, 2.txt, and 3.txt. if any of these files are not
present, a message without exiting the program must be printed prompting the same.
2. Write a program to print the third, fifth, and seventh elements from a list using the
enumerate function.
3. Write a list comprehension to print a list that contains the multiplication table of a user-
entered number.
4. Write a program to display a/b where a and b are integers. If b=0, display infinite by
handling the ZeroDivisionError.
5. Store the multiplication tables generated in problem 3 in a file named Tables.txt.
Virtual Environment
An environment that is same as the system interpreter but is isolated from the other
python environments on the system.
Installation
To use virtual environments, we write
pip install virtualenv #Installs the package
We create a new environment using:
virtualenv myprojectenv #Creates a new venv
The next step after creating the virtual environment is to activate it.
We can now use this virtual environment as a separate python installation.
pip freeze command
pip freeze returns all the packages installed in a given python environment along with
the versions.
“pip freeze > requirements.txt”
The above command creates a file named requirements.txt in the same directory
containing the output of pip freeze.
We can distribute this file to other users and they can recreate the same environment
using:
pip install –r requirements.txt
Lambda functions
Functions created using an expression using the lambda keyword
Syntax:
lambda arguments: expressions (can be used as a normal function)
Example:
Copy
bin method(Strings)
Creates a string from iterable objects
Copy
The above line will return “apple, and, mango, and, banana”
Format method(Strings)
Formats the values inside the string into the desired output
template.format(p1, p2, …) #p1, p2 … are the arguments
The syntax for format looks like:
Copy
Output for 1:
Harry is a good boy
Output for 2:
boy is a good Harry
Map, Filter & Reduce
Map applies a function to all the items in an input_list.
Syntax:
map(function, input_list) #function can be lambda function
Filter creates a list of items for which the function returns true.
list(filter(function)) #function can be a lambda function
Reduce applies a rolling computation to sequential pair of elements.
from functools import reduce
val = reduce(function, list1) #function can be a lambda function
If the function computes sum of two numbers and the list is [1, 2, 3, 4]
Chapter 13 – Practice Set
1. Create two virtual environments, install few packages in the first one. How do you create
a similar environment in the second one?
2. Write a program to input name, marks and phone number of a student and format it
using the format function like below:
“The name of the student is Harry, his marks are 72 and the phone number is 99999888”
Implement a student library system using OOPs where students can borrow a book from
the list of books.
Create a separate Library and Student class.
Your program must be menu-driven.
You are free to choose the methods and attributes of your choice to implement this
functionality.