You are on page 1of 20

Malnad College of Engineering

Under the auspices of M.T.E.S ®


(An Autonomous Institution Affiliated to VTU, Belgaum)
P.B No. 21, Hassan-573202, Karnataka

Summer Internship 1(21INT1)


Object Oriented Programming in Python
(Duration: 31/10/22 to 19/11/22)

Report Submitted by

Ganesh(4MC21EC030)

Under the guidance of


Mrs Priyanka H.L
Assistant Professor

Department of Information Science & Engineering


Malnad College of Engineering
Hassan - 573 202

2021-22
ACKNOWLEDGEMENT:

I would like to express my deepest appreciation to all those who provided me with the
possibility to complete this report. A special gratitude I give to my mentor whose contribution
in stimulating suggestions and encouragement helped in writing this report. I express my
thanks to my institution Malnad College Of Engineering for giving me an opportunity to learn
this interesting topic. I also convey my regards to the IS faculty who assisted us all through
this training named “Object Oriented Programming”. Once again I would like to thank all my
supporters from the core of my heart.

A
Table of Contents
SL. NO. Title Page Number
01 Introduction 04
Introduction to Python
History of Python

02 Basics of Python 05-08


a. Data types

String methods
a. List, Tuples, Set, Dictionary

03 Functions 09
a. Types of arguments

b.Lambda functions

04 File handling in python 10


05 Object-oriented Programming 11
06 Modules 12-17
a. OS Module

b. Datetime Module

c. Math Module

d. Random Module

07 Internship outcome 17-18


a. Outcome of learning

b. Challenges

08 Conclusion and Future Scope 18-19

B
Department of ISE, MCE
Chapter 1: Introduction Object Oriented Programming in Python

Chapter 1: Introduction

Introduction to Python:-
Python is a widely used general-purpose, high level programming language. It was created by
Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was
designed with an emphasis on code readability, and its syntax allows programmers to express
their concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more
efficiently.

History of Python:-
The language was finally released in 1991. When it was released, it used a lot fewer codes to
express the concepts, when we compare it with Java, C++ & C. Its design philosophy was quite
good too. Its main objective is to provide code readability and advanced developer productivity.
When it was released it had more than enough capability to provide classes with inheritance,
several core data types exception handling and functions.

The two of the most used versions has to Python 2.x & 3.x. There is a lot of competition between
the two and both of them seem to have quite a number of different fanbases.

For various purposes such as developing, scripting, generation, and software testing, this
language is utilized. Due to its elegance and simplicity, top technology organizations like
Dropbox, Google, Quora, Mozilla, Hewlett-Packard, Qualcomm, IBM, and Cisco have
implemented Python.

Python has come a long way to become the most popular coding language in the world. Python
has just turned 30 and just recently at pycon22(python confrence) a new feature was released by
Anaconda foundation it’s known as pyscript with this now python can be written and run in the
browser like javascript which was previously not possible, but it still has that unknown charm & X
factor which can be clearly seen from the fact that Google users have consistently searched for
Python much more than they have searched for Kim Kardashian, Donald Trump, Tom Cruise, etc

Department of ISE, MCE1


Chapter 2: Basics of Python Object Oriented Programming in Python

Chapter 2: Basics of Python

b. Data types
 Integers
In Python , there is effectively no limit to how long an integer value can be. Of course, it is
constrained by the amount of memory your system has, as are all things, but beyond that
an integer can be as long as you need it to be
 Floating-Point Numbers
The float type in Python designates a floating-point number. float values are specified with
a decimal point. Optionally, the character e or E followed by a positive or negative integer
may be appended to specify scientific notation.
Almost all platforms represent Python float values as 64-bit “double-precision” values,
according to the IEEE 754 standard. In that case, the maximum value a floating-point
number can have is approximately 1.8 ⨉ 10308. Python will indicate a number greater
than that by the string .
The closest a nonzero number can be to zero is approximately 5.0 ⨉ 10-324. Anything
closer to zero than that is effectively zero.

 Complex Numbers
Complex numbers are specified as <real part>+<imaginary part>j.

 Strings
Strings are sequences of character data. The string type in Python is called str.
String literals may be delimited using either single or double quotes. All the characters
between the opening delimiter and matching closing delimiter are part of the string
A string in Python can contain as many characters as you wish. The only limit is your
machine’s memory resources. A string can also be empty.

 Escape Sequences in strings

Escape Sequence Usual Interpretation of “Escaped” Interpretation


Character(s) After Backslash

\' Terminates string with single Literal single quote (')


quote opening delimiter character

\" Terminates string with double Literal double quote (")


quote opening delimiter character

\<newline> Terminates input line Newline is ignored


\\ Introduces escape sequence Literal backslash (\) character

 Raw Strings

2
Chapter 2: Basics of Python Object Oriented Programming in Python

A raw string literal is preceded by r or R, which specifies that escape sequences in the
associated string are not translated. The backslash character is left in the string:

 Triple-Quoted Strings
There is yet another way of delimiting strings in Python. Triple-quoted strings are
delimited by matching groups of three single quotes or three double quotes. Escape
sequences still work in triple-quoted strings, but single quotes, double quotes, and
newlines can be included without escaping them. This provides a convenient way to create
a string with both single and double quotes in it

 Boolean Type
Objects of Boolean type may have one of two values, True or False

 Built-In Functions

abs() Returns the absolute value of a number


all() Returns True if all items in an iterable object are true
any() Returns True if any item in an iterable object is true
float() Returns a floating point number
bool() Returns the boolean value of the specified object
bytearray() Returns an array of bytes
bytes() Returns a bytes object
callable() Returns True if the specified object is callable, otherwise False
chr() Returns a character from the specified Unicode code.
classmethod() Converts a method into a class method
compile() Returns the specified source as an object, ready to be executed
complex() Returns a complex number

 Math
Function Description
abs() Returns absolute value of a number

divmod() Returns quotient and remainder of integer division


max() Returns the largest of the given arguments or items in an

iterablemin() Returns the smallest of the given arguments or items in aniterable


pow() Raises a number to a power
round() Rounds a floating-point value
sum() Sums the items of an iterable

 Composite data type

Function Description

Department of ISE, MCE3


Chapter 2: Basics of Python Object Oriented Programming in Python

bytearray() Creates and returns an object of the bytearray class


bytes() Creates and returns a bytes object (similar to bytearray)
dict() Creates a dict object
frozenset() Creates a frozenset object
list() Creates a list object
object() Creates a new featureless object
set() Creates a set object
tuple() Creates a tuple object

 Iterables and Iteraters

Function Description
all() Returns True if all elements of an iterable are true
any() Returns True if any elements of an iterable are true
enumerate() Returns a list of tuples containing indices and values
from an iterable
filter() Filters elements from an iterable
iter() Returns an iterator object
4
len() Returns the length of an object
4
map() Applies a function to every item of an iterable
next() Retrieves the next item from an iterator
range() Generates a range of integer values
reversed() Returns a reverse iterator
slice() Returns a slice object
sorted() Returns a sorted list from an iterable
zip() Creates an iterator that aggregates elements from
iterables

 Input/Output

Department of ISE, MCE3


Chapter 2: Basics of Python Object Oriented Programming in Python

Function Description

format() Converts a value to a formatted representation

input() Reads input from the console

open() Opens a file and returns a file object

print() Prints to a text stream or the console

 Variables, References, and Scope

Function Description

dir() Returns a list of names in current local scope or a list of object attributes

globals() Returns a dictionary representing the current global symbol table

id() Returns the identity of an object

locals() Updates and returns a dictionary representing current local symbols


table
vars() Returns __dict__ attribute for a module, class, or object

5
2
Chapter 2: Basics of Python Object Oriented Programming in Python

c. String methods

Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a
string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the
position of
where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the
position of
where it was found
isalnum() Returns True if all characters in the string are
alphanumeric
isalpha() Returns True if all characters in the string are in the
alphabet
isascii() Returns True if all characters in the string are ascii
characters
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces

Department of ISE, MCE3 6


Chapter 3: Functions Object Oriented Programming in Python

Chapter 3: Functions

b. Types of arguments
1 Types of Arguments in Python Function Definition:
1. Default arguments
 Default arguments are values that are provided while defining functions.
 The assignment operator = is used to assign a default value to the argument.
 Default arguments become optional during the function calls.
 If we provide a value to the default arguments during function calls, it overrides the default
value.
 The function can have any number of default arguments
 Default arguments should follow non-default arguments

2. Keyword arguments
Functions can also be called using keyword arguments of the form kwarg=value.
During a function call, values passed through arguments need not be in the order of
parameters in the function definition. This can be achieved by keyword arguments. But all the
keyword arguments should match the parameters in the function definition.

3. Positional arguments
During a function call, values passed through arguments should be in the order of
parameters in the function definition. This is called positional arguments.
Keyword arguments should follow positional arguments only

4. Arbitrary positional arguments


For arbitrary positional argument, an asterisk (*) is placed before a parameter in function
definition which can hold non-keyword variable-length arguments. These arguments will be
wrapped up in a tuple. Before the variable number of arguments, zero or more normal arguments
may occur.

5. Arbitrary keyword arguments


For arbitrary positional arguments, a double asterisk (**) is placed before a parameter in a
function that can hold keyword variable-length arguments.

c. Lambda functions
Python Lambda Functions are anonymous function means that the function is without a name. As
we already know that the def keyword is used to define a normal function in Python. Similarly, the
lambda keyword is used to define an anonymous function in Python.

Syntax: lambda arguments: expression

This function can have any number of arguments but only one expression, which is evaluated and
returned.
One is free to use lambda functions wherever function objects are required.

Department of ISE, MCE3 7


Chapter 4: File Handling in Python Object Oriented Programming in Python

Chapter 4: File Handling In Python

 File handling in python


Python too supports file handling and allows users to handle files i.e., to read and write files,
along with many other file handling options, to operate on files. The concept of file handling has
stretched over various other languages, but the implementation is either complicated or lengthy,
but like other concepts of Python, this concept here is also easy and short. Python treats files
differently as text or binary and this is important. Each line of code includes a sequence of
characters and they form a text file. Each line of a file is terminated with a special character,
called the EOL or End of Line characters like comma {,} or newline character. It ends the current
line and tells the interpreter a new one has begun. Let’s start with the reading and writing files.

 Working of open() function


Before performing any operation on the file like reading or writing, first, we have to open that file.
For this, we should use Python’s inbuilt function open() but at the time of opening, we have to
specify the mode, which represents the purpose of the opening file.

 Open a File in Python


Python provides inbuilt functions for creating, writing, and reading files. There are two types of
files that can be handled in Python, normal text files and binary files (written in binary language,
0s, and 1s).

 Text files: In this type of file, each line of text is terminated with a special character called EOL
(End of Line), which is the new line character (‘\n’) in Python by default. In the case of
CSV(Comma Separated Files, the EOF is a comma by default.

 Binary files: In this type of file, there is no terminator for a line, and the data is stored after
converting it into machine-understandable binary language, i.e., 0 and 1 format.

Syntax:
File_object = open(r"File_Name", "Access_Mode")

Department of ISE, MCE11 8


Chapter 5: Object-oriented Programming Object Oriented Programming in Python

Chapter 5: Object-oriented Programming

In Python, object-oriented Programming (OOPs) is a programming paradigm that uses objects and classes in
programming. It aims to implement real-world entities like inheritance, polymorphisms, encapsulation, etc. in
the programming. The main concept of OOPs is to bind the data and the functions that work on that together
as a single unit so that no other part of the code can access this data.

Class:- A class is a collection of objects. A class contains the blueprints or the prototype from which the
objects are being created. It is a logical entity that contains some attributes and methods.
o Classes are created by keyword class.
o Attributes are the variables that belong to a class.
o Attributes are always public and can be accessed using the dot (.) operator.
o Eg.: Myclass.Myattribute

Syntax:-
class ClassName:
# Statement-1
.
.
.
# Statement-N

Objects:- The object is an entity that has a state and behavior associated with it.
An object consists of :
o State: It is represented by the attributes of an object. It also reflects the properties of
an object.
o Behaviour: It is represented by the methods of an object. It also reflects the
response of an object to other objects.
o Identity: It gives a unique name to an object and enables one object to interact with
other objects.

The self:- When we call a method of this object as myobject.method(arg1, arg2), this is automatically
converted by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self is about.

The __init__ method:- This method is useful to do any initialization you want to do with your object.

Inheritance:- Inheritance is the capability of one class to derive or inherit the properties from another
class.

Types of Inheritance – 
o Single Inheritance
o Multilevel Inheritance
o Hierarchical Inheritance

Department of ISE, MCE12


Chapter 5: Object-oriented Programming Object Oriented Programming in Python

o Multiple Inheritance

Polymorphism:- Polymorphism simply means having many forms. For example, we need to determine if
the given species of birds fly or not, using polymorphism we can do this using a single function.

Encapsulation:- Encapsulation is one of the fundamental concepts in object-oriented programming


(OOP). It describes the idea of wrapping data and the methods that work on data within one unit. This puts
restrictions on accessing variables and methods directly and can prevent the accidental modification of data.
Those types of variables are known as private variables. A class is an example of encapsulation as it
encapsulates all the data that is member functions, variables, etc

Department of ISE, MCE13 10


Chapter 6: Modules Object Oriented Programming in Python

Chapter 6: Modules

a. Python OS Module:-

Python OS module provides the facility to establish the interaction between the user and the operating
system. It offers many useful OS functions that are used to perform OS-based tasks and get related
information about the operating system. The Python OS module lets us work with the files and
directories. To work with the OS module, we need to import the OS module.  

import os  

There are some functions in the OS module which are given below:
os.name():- This function provides the name of the operating system module that it imports

Example:-
import os   

print(os.name)   

os.mkdir() :- The os.mkdir() function is used to create a new directory. Example:-


import os  
os.mkdir("d:\\newdir")  
It will create the new directory to the path in the string argument of the function in the D drive named folder
newdir.

os.getcwd():- It returns the current working directory(CWD) of the file.

Example:-

import os     
print(os.getcwd())     

os.chdir():-The os module provides the chdir() function to change the current working directory.

Example:-

import os  
os.chdir("d:\\")  

os.rmdir():-The rmdir() function removes the specified directory with an absolute or related path. First, we
have to change the current working directory and remove the folder.
11
Example:-

Department of ISE, MCE18


Chapter 6: Modules Object Oriented Programming in Python

import os  
# It will throw a Permission error; that's why we have to change the current working directory.  
os.rmdir("d:\\newdir")  
os.chdir("..")  
os.rmdir("newdir")  

os.close():-This function closes the associated file with descriptor fr.

Example:-

import os     
fr = "Python1.txt"    
file = open(fr, 'r')     
text = file.read()     
print(text)     
os.close(file)       

os.rename():-A file or directory can be renamed by using the function os.rename(). A user can rename the
file if it has privilege to change the file.

Example:-

import os     
fd = "python.txt"    
os.rename(fd,'Python1.txt')     
os.rename(fd,'Python1.txt')     

b. Datetime Module:-

The datetime module enables us to create custom date objects, and perform various operations on dates like
the comparison, etc. To work with dates as date objects, we have to import the datetime module into the
python source code. Consider the following example to get the datetime object representation for the current
time.
Example:-
import datetime  

print(datetime.datetime.now())    

Creating date objects:-We can create the date objects bypassing the desired date in the datetime
constructor for which the date objects are to be created.Consider the following example. 12

Example:-

import datetime    

Department of ISE, MCE18


Chapter 6: Modules Object Oriented Programming in Python

#returns the datetime object for the specified date    
print(datetime.datetime(2020,04,04))    

We can also specify the time along with the date to create the datetime object. Consider the following
example.
Example:-
import datetime       

print(datetime.datetime(2020,4,4,1,26,40))    

Comparison of two dates:-We can compare two dates by using comparison operators like >, >=, <, and
<=.Consider the following example.

Example:-

from datetime import datetime as dt    
if dt(dt.now().year,dt.now().month,dt.now().day,8)<dt.now()<dt(dt.now().year,dt.now().month,dt.now().day,1
6):    
print("Working hours....")    
else:    
print("fun hours")   

The calendar module:-Python provides a calendar object that contains various methods to work with
calendars. Consider the following example to print the calendar for the last month of 2018.

Example:-

import calendar;    

cal = calendar.month(2020,3)    
print(cal)    

Printing the calendar of whole year:-The prcal() method of calendar module is used to print the
calendar of the entire year. The year of which the calendar is to be printed must be passed into this
method.Example:-
import calendar    
s = calendar.prcal(2020)  

c.Python Math Module:- Python has a built-in math module. It is a standard module, so we don't need
to install it separately. We only have to import it into the program we want to use. We can import the13module,
like any other module of Python, using import math to implement the functions to perform mathematical
operations.
Constants in Math Module:- The value of numerous constants, including pi and tau, is provided in the
math module so that we do not have to remember them
Euler’s Number:- The value 2.71828182845 of Euler's number is returned by the math.e constant.

Department of ISE, MCE18


Chapter 6: Modules Object Oriented Programming in Python

Syntax of this is:- math.e


Code:-
import math
print(“The value of Euler’s Number is: ”,math.e)
Output:-
The value of Euler’s Number is: 2,718281828459045
Tau:- The ratio of a circle's circumference to its radius is known as tau. The value tau returned by the tau
constant is 6.283185307179586.
Syntax of this is:- math.tau  

Infinity:-Infinity refers to anything limitless or never-ending in both directions of the actual number line.
Numbers cannot adequately represent it. The math.inf returns positive infinity constant. We can use -math.inf
to print negative infinity.

Syntax of this is:- math.inf  

Pi:- Pi is known to everyone. It is mathematically represented as either the fraction 22/7 or the decimal
number 3.14. math.pi gives the most accurate value of pi.

Syntax of this is:- math.pi  

NaN:-The math.nan gives us a floating-point nan (Not a Number) value. This amount is not a valid numeric
value. Float("nan") and the nan constant are comparable.

Python Random Module:- The Python Random module is a built-in module for generating random
integers in Python. These are sort of fake random numbers which do not possess true randomness. We can
therefore use this module to generate random numbers, display a random item for a list or string, and so on.

Generate Random Floats:-The random.random() function gives a float number that ranges from 0.0 to
1.0. There are no parameters required for this function.

random.random():- Returns The second random floating point value within [0.0 and 1) is returned.
random.uniform(a, b):- Generates a random floating point R in which a <= R <= b if a <= b and b <=
R <= a if b < a.
14

Department of ISE, MCE18


Chapter 6: Modules Object Oriented Programming in Python

Generate Random Integers:-The random.randint() function generates a random integer from the
range of numbers supplied.

Generate Random Numbers within a Defined Range:-The random.randrange() function selects


an item randomly from the given range defined by the start, the stop, and the step parameters. By default, the
start is set to 0. Likewise, the step is set to 1 by default.

Select Random Elements:-The random.choice() function selects an item from a non-empty series at
random. An IndexError is thrown when the parameter is an empty series.

Shuffle Elements Randomly:-A general sequence, like integers or floating-point series, can be a group
of things like a List / Set. The random module contains methods that we can use to add randomization to the
series. The random.shuffle() function shuffles the entries in a list at random.

Random Seed:-We normally use the time of the system to ensure that the software delivers a different
output each time we execute it because pseudorandom synthesis is dependent on the preceding number. As a
result, we employ seeds. We can specify a seed to have an initial number using Python's random.seed()
function. This seed number determines a random number generator's outcome; therefore, if it stays the same,
the outcome will continue to be the same

15

Department of ISE, MCE18


Chapter 7: Internship Outcome Object Oriented Programming in Python

Chapter 7: Internship outcome

a. The outcome of learning:-

The learning objectives of this course are:


 To understand why Python is a useful scripting language for developers.
 To learn how to design and program Python applications
 To learn how to use lists, tuples, and dictionaries in Python programs.
 To learn how to identify Python objective types.
 To learn how to use indexing and slicing to access data in Python programs.
 To define the structure and components of a Python program.
 To learn how to write functions and pass arguments in Python.
 To learn how to build and package Python modules for reusability.
 To learn how to use exception handling in Python applications for error handling.

b. Challenges:-

 I learned python from basic to advanced level.


 I learned topic-wise implementation of different services.
 Improved my skills to become a stronger developer.
 Developed my logical skills in Python and it also provided the right perspective to use them
efficiently.

This will help me during my career as an “Electronics and Communication Engineer” and also as I
will be surrounded by a lot of real-world problems for which one doesn’t have any solution. One has
to observe the problems in-depth and then one can help the world by finding the solution.

Department of ISE, MCE19


Chapter 8: Conclusion and Future Scope Object Oriented Programming in Python

Chapter 8: Conclusion and Future Scope

I believe the internship has shown conclusively that it is both possible and desirable to use Python as the
principal teaching language:
 It is Free(as in both cost and source code).
 It is trivial to install on a Windows PC allowing students to take their interest further. For
many the hurdle of installing a Pascal or C compiler on a Windows machine is either too
expensive or too complicated;
 It is a flexible tool that allows both the teaching of traditional procedural programming and
modern OOP; It can be used to teach a large number of transferable skills;
 It is a real-world programming language that can be and is used in academia and the
commercial world;
 It appears to be quicker to learn and, in combination with its many libraries, this offers the
possibility of more rapid student development allowing the course to be made more
challenging and varied;
 And most importantly, its clean syntax offers increased understanding and enjoyment for
students;

Future Scope :-

Python is widely used in highly advanced fields like Machine Learning, Data Science, and AI. These fields
are still upcoming and are going to only develop more in the future. Python language has a lot of
advantages:
o A vast number of Libraries
o Interactive Community
o Open Source and Free to use
o Simple and Versatile Language
Python is easy to learn and implement and works across platforms. While working on new
applications, this is a huge advantage.
Due to these advantages, it is highly unlikely that Python will fade away any time soon. With the
progress of fields like Data Science, Python will only find more use in future!

17

Department of ISE, MCE 20

You might also like