You are on page 1of 45

PRACTICAL TRAINING REPORT

ON
PHYTHON

Submitted by: - Submitted to: -


Name:ParthRohilla Mrs: Raveena
Roll No. – 19011001023 (CSE/IT)
Branch: CSE 4th year 7th sem

Mr. Ashu Bansal


HOD (CSE/IT)

Mr. Naveen kumar Malik


Principal

1
DECLARATION
I hereby declare that I have completed my six week summer training at NIEIT
from 29th August,2022 to 7th October,2022 . I have worked with full
dedication during these six weeks of training and my learning outcome fulfil
the requirement of training for the award of degree of Bachelor of Technology
(B.Tech.) in CSE ,Hindu college of Engineering , Sonepat.

………………………………………

(Signature of Student)

Name of Student: - Parth Rohilla

Roll No. :- 19011001023

Date: …………………

2
SUMMER TRAINING
CERTIFICATE

3
TABLE OF CONTENTS
S.No. TOPICS PAGES
1. Introduction 6-9
2. Data types & Operator 10 – 13
3. Loops & Conditional Statements 14 – 15
4. List Tuple Dictionaries 16 – 19
5. Function 20 – 20
6. Uses & Scope 21 – 21
7. Module 22 – 24
8. Exceptions 25 - 33

4
1. Introduction
Python

Python is a widely used high-


level, general-purpose,
interpreted, dynamic
programming language. Its
design philosophy emphasizes
code readability, and
its syntax allows programmers
to express concepts in fewer
lines of code than
would be possible in languages
such as C++ or Java. The
language provides
constructs intended to enable
clear programs on both a small
and large scale.

5
Python supports multiple
programming paradigms,
including object-oriented,
imperative and functional
programming or procedural
styles. It features a
dynamic type system and
automatic memory management
and has a large and
comprehensive standard library.
Python interpreters are available
for
installation on many operating
systems, allowing Python code
execution on a
Python is a widely used high-level, general purpose, interpreted, dynamic programming
language. Its design philosophy emphasizes code readability, and its syntax allows
programmers to express concepts in fewer lines of code than would be in possible language
such as C++ or Java. The language provides constructs intended to enable clear programs on
a both a small and large scale. Python supports multiple programming paradigms, include

6
object-oriented, imperative and functional programming or procedural styles. It features a
dynamic type system and automatic memory management and has a large and comprehensive
standard library. Python interpreters are available for installation on many operating systems,
allowing Python code execution on a wide variety of systems.

Features of Python

1. Easy to Code

Python is a very high-level programming language, yet it is effortless to learn. Anyone can
learn to code in Python in just a few hours or a few days. Mastering Python and all its
advanced concepts, packages and modules might take some more time. However, learning
the basic Python syntax is very easy, as compared to other popular languages like C, C++,
and Java.

2. Easy to Read

Python code looks like simple English words. There is no use of semicolons or brackets, and
the indentations define the code block. You can tell what the code is supposed to do simply
by looking at it.

3. Free and Open-Source

Python is developed under an OSI-approved open source license. Hence, it is completely free
to use, even for comercial purposes. It doesn't cost anything to download Python or to
include it in your application. It can also be freely modified and re-distributed. Python can be
downloaded from the official Python website.

4. Robust Standard Library

Python has an extensive standard library available for anyone to use. This means
that programmers don’t have to write their code for every single thing unlike other
programming languages. There are libraries for image manipulation, databases, unit-testing,
expressions and a lot of other functionalities. In addition to the standard library, there is also a

7
growing collection of thousands of components, which are all available in the Python
Package Index.

5. Interpreted

When a programming language is interpreted, it means that the source code is executed line
by line, and not all at once. Programming languages such as C++ or Java are not interpreted,
and hence need to be compiled first to run them.

1.4 History of python


1.4 History of python
History of Python

Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde &
Informatica (CWI) in the Netherlands as a successor to the ABC programming language,
which was inspired by SETL, capable of exception handling (from the start plus new
capabilities in Python 3.11) and interfacing with the Amoeba operating ..

Guido Van Rossum

8
Installing Python

Visit the link https://www.python.org/downloads/

9
Python was conceived in the late
1980s, and its implementation
was started in
December 1989 by Guido van
Rossum at CWI in the
Netherlands as a successor to the
ABC
language (itself inspired by
SETL) capable of exception
handling and interfacing with
the
Amoeba operating system. Van
Rossum is Python's principal
author, and his continuing
central role in deciding the
direction of Python is reflected
in the title given to him by the
10
Python community, benevolent
dictator for life (BDFL).
Behind the scene of Python

About the origin of Python, Van


Rossum wrote in 1996:
Over six years ago, in December
1989, I was looking for a
"hobby"
programming project that would
keep me occupied during the
week around
Christmas. My office ... would
be closed, but I had a home
Computer, and not
much else on my hands. I
decided to write an interpreter
for the new scripting
11
language I had been thinking
about lately: a descendant of
ABC that would
appeal to Unix/C hackers. I
chose Python as a working title
for the project,
being in a slightly irreverent
mood (and a big fan of Monty
Python's Flying
Circus).
About the origin of Python, Van
Rossum wrote in 1996:
Over six years ago, in December
1989, I was looking for a
"hobby"

12
programming project that would
keep me occupied during the
week around
Christmas. My office ... would
be closed, but I had a home
Computer, and not
much else on my hands. I
decided to write an interpreter
for the new scripting
language I had been thinking
about lately: a descendant of
ABC that would
appeal to Unix/C hackers. I
chose Python as a working title
for the project,

13
being in a slightly irreverent
mood (and a big fan of Monty
Python's Flying
Circus).
Behind the origin of Python, Van Rossum wrote in 1996: Over six year ago, in December
1989, I was looking for a “hobby” programming project that would keep me occupied during
the week around Christmas. My office … would be closed, but I had a home computer, and
not much else on my hands. I decided to write an interpreter for the new scripting language I
had been thinking about lately: a descendant of ABC that would appeal to Unix/C hackers. I
chose Python as a working title for the project, being in a slightly irreverent mood (and a big
fan of Monty Python Flying Circus).

14
2. Data types & Operator

Data Type

Data types determine whether an object can do something, or whether it just would not make
sense. Other programming languages often determine whether an operation makes sense for
an object by making sure the object can never be stored somewhere where the operation will
be performed on the object (this type system is called static typing). Python does not that
Instead it stores the type of an object with the object, and checks when the operation is
performed whether that operation makes sense for that object (this is called dynamic typing).

Python object many native data types. Here are the important ones.

Booleans are either True or False.

Numbers can be integers (1 and 2), floats (1.1 and 1.2), fractions (1/2 and 2/3), or even
complex numbers.

Strings are sequence of Unicode characters, e.g. an HTML document.

Lists are ordered sequences of values.

Tuples are ordered, immutable sequence of values.

Sets are unordered bags of values.

Python Operator

Arithmetic Operator

Operator Meaning Example

+ Add two operands or unary plus x+y+2

- Subtract right operand from the left or unary minus x-y-2

* Multiply two operands x*y

15
/ Divide left operand by the right one (always results into float) x/y

% Modulus - remainder of the division of left operand by the right x % y (remainder)

Comparison Operator

Operator Meaning Example

> Greater that - True if left operand is greater than the right x > y

< Less that - True if left operand is less than the right x<y

== Equal to - true if both operands are equal x==y

!= Not equal to - True if operands are not equal x != y

>= Greater than or equal to - True if left operand is greater than or x >= y

equal to the right

<= Less than or equal to - True if left operand is less than or x <= y

equal to the right

Logical Operator

Operator Meaning Example

and True if both the operands are true x and y

or True if either of the operands is true x or y

not True if operand is false (complements the operand) not x

Bitwise Operator

Operator Meaning Example

& Bitwise AND x&y

| Bitwise OR x|y

~ Bitwise NOT x~y

16
^ Bitwise XOR x^y

>> Bitwise right shift x>>

Assignment Operator

Operator Meaning Example

= Assign value of right side of expression to left x=y+z

side operand

+= Add AND: Add right-side operand with left side operand a+=b

and then assign to left operand a=a+b

-= Subtract AND: Subtract right operand from left operand a-=b

and then assign to left operand a=a-b

*= Multiply AND: Multiply right operand with left operand and a*=b

then assign to left operand a=a*b

/= Divide AND: Divide left operand with right operand and a/=b

then assign to left operand a=a/b

%= Modulus AND: Takes Modulus using left and right operands a%=b

and assign the result to left operand a=a%b

17
Identity Operators
is and is not are the identity operators both are used to check if two values are located on the
same part of the memory. Two variables that are equal do not imply that they are identical.

Is True if the operands are identical

Is not True if the operands are not identical

Example: Identity Operator

a = 10

b = 20

c=a

print(a is not b)

print(a is c)
Output
True

True

18
Membership Operators

In and not in are the membership operators; used to test whether a value or variable is in
sequence.

In True if value is found in the sequence

Not In True if value is not found in the sequence.

Example : Membership Operator

# Python program to illustrate


# not 'in' operator
x = 24
y = 20
list = [10, 20, 30, 40, 50]
 
if (x not in list):
    print("x is NOT present in given list")
else:
    print("x is present in given list")
 
if (y in list):
    print("y is present in given list")
else:
    print("y is NOT present in given list")

Output

19
x is NOT present in given list

y is present in given list

3. Loops & Conditional Statements

Loops

Looping means repeating something over and over until a particular condition is satisfied. A
for loop in Python is a control flow statement that is used to repeatedly execute a group of
statements as long as the condition is satisfied. Such a type of statement is also known as an
iterative statement.

Loops definition & example

There are 3 types of loops in python language.

1. For Loop

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set,
or a string). This is less like the for keyword in other programming languages, and works
more like an iterator method as found in other object-orientated programming languages.

Example

Fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

2. While Loop

What is while loop in Python? The while loop in Python is used to iterate over a block of
code as long as the test expression (condition) is true. We generally use this loop when we
don't know the number of times to iterate beforehand.

Example

# Python program to illustrate


# while loop
count =0
while(count < 3):

20
count =count +1
print("Hello Geek")

3. Nested Loops
You can use one or more loop inside any another while, for or do..while loop.

Example
x =[1, 2]
y =[4, 5]
  
fori inx:
  forj iny:
    print(i, j)

Conditional Statements definition & example


A conditional statement as the name suggests itself, is used to handle conditions in your
program. These statements guide the program while making decisions based on the
conditions encountered by the program. Python has 3 key Conditional Statements that you
should know: if statement

If StatementsAn if statements consists of a Boolean expression followed by one or

more statements.

If…else An if statement can be followed by an optional else statement, which

Statements executes when the Boolean expression is false.

Nested if You can use one if or else if statement inside another if or else if

Statementsstatement(s).

21
4. List, Tuple & Dictionaries

List

The list is a most versatile datatype available in Python which can be written as a list of
comma-separated values (items) between square brackets. Important thing about a list is that
items in a list need not be of the same type. Creating a list is as simple as putting different
comma-separated values between square brackets.

For example –

List1 = [‘physics’, ‘chemistry’, 1997, 2000];

List2 = [1, 2, 3, 4, 5];

List3 = [“a”, “b”, “c”, “d”];

imilar to string indices,


List3 = [“a”, “b”, “c”, “d”];

list indices start at 0, and lists


can be
concatenated and so on
imilar to string indices, list
indices start at 0, and lists can be
sliced,
concatenated and so on

22
imilar to string indices, list
indices start at 0, and lists can be
sliced,
concatenated and so on
imilar to string indices, list
indices start at 0, and lists can be
sliced,
concatenated and so on
imilar to string indices, list
indices start at 0, and lists can be
sliced,
concatenated and so on
Accessing List Values

To access values in lists, use the square brackets for slicing along with the index or
indicesto obtain value available at that index.

For example −
list1 = ['physics', 'chemistry',
1997, 2000];
23
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
For example–

list1 = [‘Physics’, ‘chemistry’, 1997, 2000];

list2 = [1, 2, 3, 4, 5, 6, 7];

Print “list1[0]:”, list1[0]

Print “list2[1:5]:”, list2[1:5]

Output: list1[0]: physics

list2[1:5]: [2, 3, 4, 5]

Operation & Built in Function

Basic in list Operation

Python Expresssion Results Description

Len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

[‘Hi!’] * 4 [‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’] Repetition

3 in [1, 2, 3] True Membership

For x in [1, 2, 3]: print x, 123 Iteration

24
Built in list Functions

SN Function with Description

1 cmp(list1, list2) Compare elements of both lists.

2 len(list) Gives the total length of the list.

3 max (list) Returns item from the list with max value

4 min (list) Returns item from the list with min value.

5 list (seq) Converts a tuple into list.

Tuple

Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-in data
types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all
with different qualities and usage. A tuple is a collection which is ordered and unchangeable.

For example –

Tuple = ("apple", "banana", "cherry")
print (Tuple)

Accessing tuple

To access values in tuple, use


the square brackets for slicing
along with the index or
25
indices to obtain value available
at that index.
To access values in tuple, use the square brackets for slicing along with the index or indices
to obtain value available at that index.

For example–

tup1 = (‘physics’, ‘chemistry’, 1997, 2000);

tup2 = (1, 2, 3, 4, 5, 6, 7);

Print “tup1 [0]:”tup1 [0]

Print “tup2 [1:5]:”tup2 [1:5]

When the above code is executed, it produces the following result-

tup1 [0]: physics

tup2 [1:5]: [2, 3, 4, 5]

Operation & Built in functions

Basic Tuple Operation

Python Expression Results Description

len(1, 2, 3) 3 Length

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6)


Concatenation

3 in (1, 2, 3) True Membership

For x in (1, 2, 3): print x, 123 Iteration

Built in tuple functions

SN Function with Description

26
1 cmp (tuple1, tuple2) Compares elements of both
tuples.

Update: list = ['physics',


'chemistry', 1997, 2000];
print "Value available at
index 2 : "
print list[2]
list[2] = 2001;
print "New value available at
index 2 : "
print list[2]
Output:Value available at
index 2 : 1997
New value available at inde
2 len (tuple) Gives the total length of the tuple.

3 max(tuple) Returns item from the tuple with max


value.

4 min (tuple) Returns item from the tuple with min value.

5 tuple (seq) Converts a list into tuple.

27
Dictionary

Dictionary. Dictionaries are used to store data values in key:value pairs. A dictionary is a


collection which is ordered*, changeable and do not allow duplicates. As of Python version
3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

For Example-
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

Accessing Dictionary
Employee = {“Name”: “John”, “Age”: 29}
Print(“Name:” Employee[“Name”])
Print(“Age:” Employee [“Age”])

Output:
Name: John

Age: 29

5. Functions

Function definition

Python Functions is a block of statements that return the specific task.


The idea is to put some commonly or repeatedly done tasks together and make a function so
that instead of writing the same code again and again for different inputs, we can do the
function calls to reuse code contained in it over and over again. 

Function Syntax & example

28
def function name(parameters):

"""docstring"""

Statement (s)

example

def my_function():
  print("Hello from a function")

my_function()

6. Uses & Scope

Scope of Python

Science

 Bioinformatics

System Administration

 -Unix

29
 -Web logic
 -Web sphere

Web Application Development

 -CGI

Testing scripts

7. Modules

A Python module is a file containing Python definitions and statements. A module can
define functions, classes, and variables. A module can also include runnable code. Grouping
related code into a module makes the code easier to understand and use. It also makes the
code logically organized.

Example: We use modules to break down large programs into small manageable and
organized files. Furthermore, modules provide reusability of code.

30
We can define our most used functions in a module and import it, instead of copying their
definitions into different programs.

Let us create a module. Type the following and save it as example.py.

# Python Module example

defadd(a, b):
"""This program adds two
numbers and return the result"""

result = a + b
return result

Here, we have defined a function add () inside a module named example. The function takes
in two numbers and returns their sum.
How to import modules in Python?

We can import the definitions inside a module to another module or the interactive interpreter
in Python.

We use the import keyword to do this. To import our previously defined module example,


we type the following in the Python prompt.

>>>import example

This does not import the names of the functions defined in example directly in the current
symbol table. It only imports the module name example there.
Using the module name we can access the function using the dot . operator. For example:

31
>>>example.add(4,5.5)
9.5

Python has tons of standard modules. You can check out the full list of Python standard
modules and their use cases. These files are in the Lib directory inside the location where you
installed Python.

Python import statement

We can import a module using the import statement and access the definitions inside it using
the dot operator as described above. Here is an example.
# import statement example
# to import standard module math

import math
print("The value of pi is", math.pi)
Run Code

When you run the program, the output will be:

The value of pi is 3.141592653589793

32
1.2 Scripting Language
1.3 Object Oriented
Programming
1.4 History of python
1.5 Behind the Scene of Python
1.Introduction
1.1Python
1.2 Scripting Language
1.3 Object Oriented
Programming
1.4 History of python
33
1.5 Behind the Scene of Python
1.Introduction
1.1Python
1.2 Scripting Language
1.3 Object Oriented
Programming
1.4 History of python
1.5 Behind the Scene of Python
v 1.Introduc
1.1Python
1.2 Scripting Language
1.3 Object Oriented
Programming
1.4 History of python
1.5 Behind the Scene of Python
v 1.
34
35
8. Python Exception Handling

We have explored basic python till now from Set 1 to 4 (Set 1 | Set 2 | Set 3 | Set 4). 
In this article, we will discuss how to handle exceptions in Python using try. except, and
finally statement with the help of proper examples. 
Error in Python can be of two types i.e. Syntax errors and Exceptions . Errors are the
problems in a program due to which the program will stop the execution. On the other
hand, exceptions are raised when some internal events occur which changes the normal
flow of the program. 
Difference between Syntax Error and Exceptions
Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It
leads to the termination of the program.

Example: 
 Python3

# initialize the amount variable

amount =10000

# check that You are eligible to

#  purchase DsaSelf Paced or not

if(amount > 2999)

print("You are eligible to purchase DsaSelf Paced")

Output:

36
Try and Except Statement – Catching Exceptions
Try and except statements are used to catch and handle exceptions in Python. Statements
that can raise exceptions are kept inside the try clause and the statements that handle the
exception are written inside except clause.

Example: Let us try to access the array element whose index is out of bound and handle the
corresponding exception.

 Python3

# Python program to handle simple runtime error

#Python 3

a =[1, 2, 3]

try:

    print("Second element = %d"%(a[1]))

    # Throws error since there are only 3 elements in array

    print("Fourth element = %d"%(a[3]))

except:

    print("An error occurred")

Output
Second element = 2

An error occurred

37
In the above example, the statements that can cause the error are placed inside the
try statement (second print statement in our case). The second print statement tries to
access the fourth element of the list which is not there and this throws an exception.
This exception is then caught by the except statement.

Catching Specific Exception


A try statement can have more than one except clause, to specify handlers for
different exceptions. Please note that at most one handler will be executed. For
example, we can add Index Error in the above code. The general syntax for adding
specific exceptions are – 

try:

# statement(s)

except IndexError:

# statement(s)

except ValueError:

# statement(s)

Example: Catching specific exception in Python

 Python3

# Program to handle multiple errors with one

# except statement

# Python 3

deffun(a):

    ifa < 4:

38
 

        # throws ZeroDivisionError for a = 3

        b =a/(a-3)

    # throws NameError if a >= 4

    print("Value of b = ", b)

     

try:

    fun(3)

    fun(5)

# note that braces () are necessary here for

# multiple exceptions

exceptZeroDivisionError:

    print("ZeroDivisionError Occurred and Handled")

exceptNameError:

    print("NameError Occurred and Handled")

Output
ZeroDivisionError Occurred and Handled

If you comment on the line fun(3), the output will be 

NameError Occurred and Handled

39
The output above is so because as soon as python tries to access the value of b, NameError
occurs. 

Try with Else Clause


In python, you can also use the else clause on the try-except block which must be present
after all the except clauses. The code enters the else block only if the try clause does not
raise an exception.

Example: Try with else clause

 Python3

# Program to depict else clause with try-except

# Python 3

# Function which returns a/b

defAbyB(a , b):

    try:

        c =((a+b) /(a-b))

    exceptZeroDivisionError:

        print("a/b result in 0")

    else:

        print(c)

40
# Driver program to test above function

AbyB(2.0, 3.0)

AbyB(3.0, 3.0)

Output:
-5.0

a/b result in 0

41
Finally Keyword in Python
Python provides a keyword finally , which is always executed after the try and except
blocks. The final block always executes after normal termination of try block or after try
block terminates due to some exception.
Syntax:
try:

# Some Code....

except:

# optional block

# Handling of exception (if required)

else:

# execute if no exception

finally:

# Some code .....(always executed)

Example:

 Python3

# Python program to demonstrate finally

42
 

# No exception Exception raised in try block

try:

    k =5//0  # raises divide by zero exception.

    print(k)

# handles zerodivision exception

exceptZeroDivisionError:

    print("Can't divide by zero")

finally:

    # this block is always executed

    # regardless of exception generation.

    print('This is always executed')

Output:
Can't divide by zero

This is always executed

43
Raising Exception

The raise statement allows the programmer to force a specific exception to occur. The sole
argument in raise indicates the exception to be raised. This must be either an exception
instance or an exception class (a class that derives from Exception).

 Python3

# Program to depict Raising Exception

try:

    raiseNameError("Hi there")  # Raise Error

exceptNameError:

    print("An exception")

    raise  # To determine whether the exception was raised or not

The output of the above code will simply line printed as “An exception” but a Runtime
error will also occur in the last due to the raise statement in the last line. So, the output on
your command line will look like 

Traceback (most recent call last):

File "/home/d6ec14ca595b97bff8d8034bbf212a9f.py", line 5, in <module>

raise NameError("Hi there") # Raise Error

44
NameError: Hi there

45

You might also like