Professional Documents
Culture Documents
ON
PHYTHON
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)
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
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.
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.
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.
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 ..
8
Installing Python
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
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.
Numbers can be integers (1 and 2), floats (1.1 and 1.2), fractions (1/2 and 2/3), or even
complex numbers.
Python Operator
Arithmetic Operator
15
/ Divide left operand by the right one (always results into float) x/y
Comparison Operator
> 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
>= Greater than or equal to - True if left operand is greater than or x >= y
<= Less than or equal to - True if left operand is less than or x <= y
Logical Operator
Bitwise Operator
| Bitwise OR x|y
16
^ Bitwise XOR x^y
Assignment Operator
side operand
+= Add AND: Add right-side operand with left side operand a+=b
*= Multiply AND: Multiply right operand with left operand and a*=b
/= Divide AND: Divide left operand with right operand and a/=b
%= Modulus AND: Takes Modulus using left and right operands 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.
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.
Output
19
x is NOT present in given list
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.
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
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)
more statements.
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 –
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–
list2[1:5]: [2, 3, 4, 5]
24
Built in list Functions
3 max (list) Returns item from the list with max value
4 min (list) Returns item from the list with min value.
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
For example–
len(1, 2, 3) 3 Length
26
1 cmp (tuple1, tuple2) Compares elements of both
tuples.
4 min (tuple) Returns item from the tuple with min value.
27
Dictionary
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
28
def function name(parameters):
"""docstring"""
Statement (s)
example
def my_function():
print("Hello from a function")
my_function()
Scope of Python
Science
Bioinformatics
System Administration
-Unix
29
-Web logic
-Web sphere
-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.
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.
>>>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.
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
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
amount =10000
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 3
a =[1, 2, 3]
try:
except:
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.
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
Python3
# except statement
# Python 3
deffun(a):
ifa < 4:
38
b =a/(a-3)
print("Value of b = ", b)
try:
fun(3)
fun(5)
# multiple exceptions
exceptZeroDivisionError:
exceptNameError:
Output
ZeroDivisionError Occurred and Handled
39
The output above is so because as soon as python tries to access the value of b, NameError
occurs.
Python3
# Python 3
defAbyB(a , b):
try:
exceptZeroDivisionError:
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
else:
# execute if no exception
finally:
Example:
Python3
42
try:
print(k)
exceptZeroDivisionError:
finally:
Output:
Can't divide by zero
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
try:
exceptNameError:
print("An exception")
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
44
NameError: Hi there
45