[go: up one dir, main page]

0% found this document useful (0 votes)
128 views62 pages

Shreya Sharma Report

This document provides an industrial training report submitted by Shreya Sharma for a training program in Python with Django at Techpile Technology Pvt. Ltd. in Lucknow. The report covers an introduction to Python programming language including its history, features, and applications. It discusses key Python concepts such as basic syntax, language components, collections, functions, modules, exceptions, classes, and the future scope of Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
128 views62 pages

Shreya Sharma Report

This document provides an industrial training report submitted by Shreya Sharma for a training program in Python with Django at Techpile Technology Pvt. Ltd. in Lucknow. The report covers an introduction to Python programming language including its history, features, and applications. It discusses key Python concepts such as basic syntax, language components, collections, functions, modules, exceptions, classes, and the future scope of Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 62

INDUSTRIAL TRAINING REPORT

On

PYTHON WITH DJANGO


At

TECHPILE TECHNOLOGY PVT. LTD., LUCKNOW

Submitted Towards Partial Fulfillment of

Three-Year Diploma in
Computer Science & Engineering
Under the supervision of
Mr. RAHUL SONI

SUBMITTED BY:

SHREYA SHARMA

Enrollment No- E2144083890003

GOVERNMENT GIRLS POLYTECHNIC MEJA PRAYAGRAJ

Session (2022-2023)

1
2
CONTENT

1. INTRODUCTION TO PYTHON…………………………………………………………………1-7
2. BASIC PYTHON SYNTAX……………………………………………………………………….8-13
3. LANGUAGE COMPONENTS…………………………………………………………………..14-19
4. COLLECTIONS…………………………………………………………………………………..20-24
5. FUNCTIONS……………………………………………………………………………………...25-29
6. MODULES……………………………………………………………………………………..…30-32
7. EXCEPTIONS…………………………………………………………………………………….33-34
8. CLASSES IN PYTHON………………………………………………………………………….35-40
9. FUTURE SCOPE………………………………………………………………………..…………41
10.CONCLUSION……………………………………………………………………….……………42

3
INTRODUCTION TO PYTHON

1.1 History of Python

 Python is a general purpose and high level programming language.

 HLL==>language convertor =>LLL (0, 1).

 Python was developed by GUIDO Van Rossum in 1989 while working at

national research institute at Netherland.


 But official date of birth of python is 27 Feb 1991.

 The name python was selected from a T.V show (the Monty python flying

circle) broad casted by BBC channel in 1969 to 1974.


 For Developing console Application

 For Developing standalone Application (installable).

 For Developing AI Application.

 For Developing IOT Application.

 Networking programming application Embedded System application etc

 FEATURE OF PYTHON
 Python is simple and easy to learn

 HLL

 Object oriented programming.

 Freeware open source.

 Embeddable

 Extensible

 Dynamically type

 example=>a=10

 a=10.5

 a='Ram'
4
 a=True

 a=False

 Interpreted language

 Extensive library.

 Plate form Independent.

1. Working of Python
 Python is a dynamic, interpreted (byte code-compiled) language. There are no

type declarations of variables, parameters, functions, or methods in source


code. This makes the code short and flexible, and you lose the compile-time
type checking of the source code.

 Flavors of python
 Cython (c python)

 jython (j python)

 Ironpython (c## python,.net)

 Rubypython (ruby python)

 Anacondapython (large data processing)

1.2 Introductions
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.
There are two major Python versions: Python 2 and Python 3. Both are quite different.

Python Programming Language


Python is a high-level, general-purpose and a very popular programming language. Python
programming language (latest Python 3) is being used in web development, Machine Learning
5
applications, along with all cutting edge technology in Software Industry. Python Programming
Language is very well suited for Beginners, also for experienced programmers with other
programming languages like C++ and Java.

This specially designed Python tutorial will help you learn Python Programming Language in
most efficient way, with the topics from basics to advance (like Web-scraping, Deep-Learning,
etc.) with examples.
Below are some facts about Python Programming Language:
1. Python is currently the most widely used multi-purpose, high-level programming
language.
2. Python allows programming in Object-Oriented and Procedural paradigms.
3. Python programs generally are smaller than other programming languages like Java.
Programmers have to type relatively less and indentation requirement of the language,
makes them readable all the time.
4. Python language is being used by almost all tech-giant companies like – Google, Amazon,
Face book Drop box, etc.
5. The biggest strength of Python is huge collection of standard library which can be used for
the following:
 Machine Learning
 Web frameworks like (used by YouTube, Drop box)
 Image processing (like Open CV Pillow)
 Web scraping (like Selenium)
 Test frameworks
 Multimedia
 Scientific computing
 Text processing and many more.

Python Language advantages and applications


6
Python is a high-level, interpreted, and general-purpose dynamic programming language. that
focuses on code readability. It generally has small programs when compared to Java and C. It
was founded in 1991 by developer Guido Van ROSSUM. Python ranks among the most
popular and fastest-growing languages in the world. Python is a powerful, flexible, and easy-to-
use language. In addition, the python community is very active. It is used in many
organizations as it supports multiple programming paradigms. It also performs automatic
memory management.
Advantages:
1. Presence of third-party modules
2. Open source and large active community base
3. Versatile, Easy to read, learn and write
4. User-friendly data structures
5. High-level language
6. Dynamically typed language (No need to mention data type based on the value assigned, it
takes data type)
7. Object-Oriented and Procedural Programming language
8. Portable and Interactive
9. Ideal for prototypes – provide more functionality with less coding
10.Interpreted Language
Applications:
1. GUI-based desktop applications
2. Graphic design, image processing applications, Games, and Scientific/ computational
Applications
3. Web frameworks and applications
4. Enterprise and Business applications
5. Database Access
6. Language Development
7. Prototyping
8. Software Development
9. Data Science and Machine Learning
10.Scripting
Organizations using Python:
1. Google (Components of Google spider and Search Engine)
2. Yahoo (Maps)
3. YouTube
4. Mozilla
5. Drop box
6. Microsoft
7. Cisco
7
10. Facebook
PYTHON KEYWORDS
Keywords in Python are reserved words that cannot be used as a variable name, function
name, or any other identifier.

List of all keywords in Python


And As assert Break

class Continue Def Del

Elif Else except False

finally For From Global

If Import In Is

lambd
a None Nonlocal Not

Or Pass Raise Return

True Try while With

yield

Example: Python Keywords List

Import keyword as k
Print(k.kwlist)

Output=>

['False','True','None','and','or','and','as','async','assert','await','break','class','continue','def','del','
elif','else','except','finally','for','from','globle','if','import','in','is','lambda','nonlocal','not','pass','r
aise','return','try','while','with','yield']

Total keywords [35]


8
Namespaces and Scope in Python

What is name space?


A namespace is a system that has a unique name for each and every object in Python. An object
might be a variable or a method. Python itself maintains a namespace in the form of a Python
dictionary. Let’s go through an example, a directory-file system structure in computers.
Needless to say, that one can have multiple directories having a file with the same name inside
every directory.
Real-time example, the role of a namespace is like a surname. One might not find a single
“Alice” in the class there might be multiple “Alice” but when you particularly ask for “Alice
Lee” or “Alice Clark” (with a surname), there will be only one (time being don’t think of both
first name and surname are same for multiple students).
On similar lines, the Python interpreter understands what exact method or variable one is trying
to point to in the code, depending upon the namespace. So, the division of the word itself gives
a little more information. Its Name (which means name, a unique identifier) + Space (which
talks something related scope).

Types of name space:

When Python interpreter runs solely without any user-defined modules, methods, classes, etc.
Some functions like print (), id () are always present, these are built-in namespaces. When a
user creates a module, a global namespace gets created; later the creation of local functions
creates the local namespace. The built-in namespace encompasses the global namespace and
the global namespace encompasses the local namespace.

9
The life time of a name space :
A lifetime of a namespace depends upon the scope of objects, if the scope of an object end, the
lifetime of that namespace comes to an end. Hence, it is not possible to access the inner namespace’s
objects from an outer namespace.

Example:
Python3

# var1 is in the global namespace


10
var1 = 5

def some_func():

# var2 is in the local namespace

var2 = 6

def some_inner_func():

# var3 is in the nested local

# namespace

var3 = 7

As shown in the following figure, the same object name can be present in multiple
namespaces as isolation between the same name is maintained by their namespace.

11
But in some cases, one might be interested in updating or processing global variables only, as
shown in the following example, one should mark it explicitly as global and the update or
process. Note that the line “count = count +1” references the global variable and therefore
uses the global variable, but compare this to the same line written “count = 1”. Then the line
“global count” is absolutely needed according to scope rules .

Python3

# Python program processing

Statement, Indentation and Comment in Python


12
Statements
Instructions written in the source code for execution are called statements. There are different
types of statements in the Python programming language like Assignment statements,
Conditional statements, Looping statements, etc. These all help the user to get the required
output. For example, n = 50 is an assignment statement.
Multi-Line Statements: Statements in Python can be extended to one or more lines using
parentheses (), braces {}, square brackets [], semi-colon (;), continuation character slash (\).
When the programmer needs to do long calculations and cannot fit his statements into one line,
one can make use of these characters.
Example:
Declared using Continuation Character (\):
s=1+2+3+\
4+5+6+\
7+8+9

Declared using parentheses () :


n = (1 * 2 * 3 + 7 + 8 + 9)

Declared using square brackets [] :


Footballer = ['MESSI',
'NEYMAR',
'SUAREZ']

Declared using braces {}:


x = {1 + 2 + 3 + 4 + 5 + 6 +
7 + 8 + 9}

Declared using semicolons (;) :


Flag = 2; ropes = 3; pole = 4

Indentation
13
A block is a combination of all these statements. Block can be regarded as the grouping of
statements for a specific purpose. Most of the programming languages like C, C++, and Java
use braces { } to define a block of code. One of the distinctive features of Python is its use of
indentation to highlight the blocks of code. Whitespace is used for indentation in Python. All
statements with the same distance to the right belong to the same block of code. If a block has
to be more deeply nested, it is simply indented further to the right.
One can understand it better by looking at the following lines of code:

Python3

# Python program showing

# indentation

site = 'gfg'

if site == 'gfg':

print ('Logging on to geeksforgeeks...')

else:

print (‘retypes the URL.')

print ('All set!')

Output
Logging on to geeks for geeks...

The lines print (‘Logging on to geeks for geeks...’) and print (‘retype the URL.’) is two
separate code blocks. The two blocks of code in our example if-statement are both indented

14
four spaces. The final print (‘All set!’) is not indented, and so it does not belong to the else-
block.

Python3

j=1

while(j<= 5):

print(j)

j=j+1

Output
1
2
3
4
5
To indicate a block of code in Python, you must indent each line of the block by the same
whitespace. The two lines of code in the while loop are both indented four spaces. It is required
for indicating what block of code a statement belongs to. For example, j=1 and while (j<=5): is
not indented, and so it is not within the while block. So, Python code structures by indentation.

Comments
Python developers often make use of the comment system as, without the use of it, things can
get real confusing, real fast. Comments are the useful information that the developers provide
to make the reader understand the source code.
Single line comments: Python single-line comment starts with a hashtag symbol with no white
spaces (#) and lasts till the end of the line. If the comment exceeds one line then put a hashtag
on the next line and continue the comment. Python’s single-line comments are proved useful
for supplying short explanations for variables, function declarations, and expressions. See the
following code snippet demonstrating single line comment:
Multi-line string as a comment: Python multi-line comment is a piece of text enclosed in a
delimiter (“””) on each end of the comment. Again there should be no white space between
delimiter (“””). They are useful when the comment text does not fit into one line; therefore
15
need to span across lines. Multi-line comments or paragraphs serve as documentation for others
reading your code. See the following code snippet demonstrating multi-line comment:

1.3 Installing Python

 Installation steps
Four Python 3.10 installers are available for download - two each for the 32-bit and 64-bit
versions of the interpreter. The web installer is a small initial download, and it will
automatically download the required components as necessary. The offline installer includes
the components necessary for a default installation and only requires an internet connection for
optional features. See for other ways to avoid downloading during installation.

After starting the installer, one of two options may be selected:

If you select “Install Now”:

 You will not need to be an administrator (unless a system update for the C Runtime Library is required
or you install the Python Launcher for Windows for all users)
16
 Python will be installed into your user directory
 The Python Launcher for Windows will be installed according to the option at the bottom of the first
page
 The standard library, test suite, launcher and pip will be installed
 If selected, the install directory will be added to your PATH
 Shortcuts will only be visible for the current user

Selecting “Customize installation” will allow you to select the features to install, the installation location and
other options or post-install actions. To install debugging symbols or binaries, you will need to use this option.

To perform an all-users installation, you should select “Customize installation”. In this case:

 You may be required to provide administrative credentials or approval


 Python will be installed into the Program Files directory
 The Python Launcher for Windows will be installed into the Windows directory
 Optional features may be selected during installation
 The standard library can be pre-compiled to byte code
 If selected, the install directory will be added to the system PATH
 Shortcuts are available for all users.
1.4 Idle Of Python

IDLE is Python’s Integrated Development and Learning Environment.

IDLE has the following features:

 coded in 100% pure Python, using the GUI toolkit


 cross-platform: works mostly the same on Windows, Unix, and MacOS
 Python shell window (interactive interpreter) with colorizing of code input, output, and error messages
 multi-window text editor with multiple undo, Python colorizing, smart indent, call tips, auto
completion, and other features
 search within any window, replace within editor windows, and search through multiple files (Grep)
 debugger with persistent breakpoints, stepping, and viewing of global and local namespaces
 configuration, browsers, and other dialogs
1.5 Python is Dynamically Typed
Python is a dynamically typed language. This means that the Python interpreter does
type checking only as code runs, and the type of a variable is allowed to change over its
lifetime..
Example=>a=10
a=10.5
a='Ram'
a=True
a=False
17
1.6 Python Reserved Words
 There is one more restriction on identifier names. The Python language reserves a small
set of keywords that designate special language functionality. No object can have the
same name as a reserved word.
 In python some word are reserve to represent some special meaning or function .such
type of words are known as reserved word or keyword
1. 7 Naming Conventions
 In Python programming, naming conventions are set of rules for choosing the valid name to be used
for variable, package, module, class and function in a python program.
 In this article, I am going to discuss Naming Conventions in Python with Examples. Please read our
previous article where we discussed Python Coding Instructions .At the end of this article, you will
understand the following pointers in detail.

1.8 Python Version History

Python Software Foundation (PSF) used to support two major versions, Python 2.x & Python 3.x.
PSF supported Python 2 because a large body of existing code could not be forward ported to
Python 3. So, they supported Python 2 until January 2020, but now they have stopped supporting it.

Python 3.0 was released on December 3rd, 2008. It was designed to rectify certain flaws in the
earlier version. This version is not completely backward-compatible with previous versions.
However, many of its major features have since been back-ported to the Python 2.6.x and 2.7.x
version series. Releases of Python 3 include utilities to facilitate the automation of Python 2 code
translation to Python 3.

The following table lists all the important versions of Python:

Version Release Date Important Features


Python 0.9.0 February 1991  Classes with inheritance exception handling
 Functions
 Modules

Python 1.0 January 1994  Functional programming tools (lambda, map, filter
and reduce).
 Support for complex numbers.

18
Version Release Date Important Features
 Functions with keyword arguments

Python 2.0 October 2000  List comprehension.


Python 2.7.0 - EOL - Jan July 2010  Cycle-detecting garbage collector.
2020
 Support for Unicode. Unification of data types and
classes

Python 3 December 2008  Backward incompatible.


Python 3.6 December 2016  print keyword changed to print() function
Python 3.6.5 March 2018  Unified Unicode types.
 Utilities for automatic conversion of Python 2.x
code

Python 3.7.0 May 2018  New C API for thread-local storage


 Built-in breakpoint()
 Data classes
 Context variables

Python 3.8 October 2019  Assignment Expression


 Positional-only parameters
 Parallel file system cache for compiled byte code
files

Python 3.9 - Current October 2020  Dictionary Merge & Update Operators
Version  New remove prefix() and remove suffix() string
methods
 Built in Generic Types

19
BASIC PYTHON SYNTAX

2.1 Basic syntax

 Syntax is one of the basic requirements that we must know to code in any language. In
Python, we use indentation to represent the block of the code. We have to follow some
rules about how to use the indentation. Not just indentation, we have to follow the rules on
how to choose the name for the variables..

Execute Python Syntax


As we learned in the previous page, Python syntax can be executed by writing directly in the Command Line:

>>> print ("Hello, World!")


Hello, World!

2.2 String values

 A string in Python is a sequence of characters. It is a derived data type. Strings are


immutable. This means that once defined, they cannot be changed. Many Python methods,
such as replace, join, or split modify strings.

2.3 String Methods

2.4 String Operators

String operators represent the various types of operations that we can employ on the string
type of the variables in the program. Moreover, python lets us apply numerous string operators
on the python string and these are explained well in this article. Table of content ..

20
2.5 Numeric Data Types

 In Python, numeric data type represents the data that has a numeric value. The numeric
value can be an integer, floating number, or even complex number. These values are defined
as int, float, and complex classes in Python. Integers – This data type is represented with the
help of int class. -

21
22
2.6 Comments
 Comments in Python are the lines in the code that are ignored by the interpreter during the
execution of the program. Comments enhance the readability of the code and help the
programmers to understand the code very carefully. There are three types of comments in
Python –
 Single line Comments
 Multiline Comments
 Doc string Comments
Example: Comments in Python

Python3

# Python program to demonstrate comments

# sample comment

name ="shreya"

print(name)

Output:
Shreya
In the above example, it can be seen that comments are ignored by the interpreter during the
execution of the program.
Comments are generally used for the following purposes:
 Code Readability
 Explanation of the code or Metadata of the project
 Prevent execution of code
 To include resources
Types of Comments in Python
There are three main kinds of comments in Python. They are:
Single-Line Comments
Python single-line comment starts with the hashtag symbol (#) with no white spaces and lasts till the
end of the line. See the following code snippet demonstrating single line comment:
Example:

23
 Python3

# Print “Geeks for Geeks !” to console

print("Geeks for Geeks")

Output
Geeks for Geeks
Multi-Line Comments
Python does not provide the option for multiline comments However, there are different ways
through which we can write multiline comments.

Using Multiple Hash tags (#)

We can multiple hash tags (#) to write multiline comments in Python. Each and every line will be
considered as a single-line comment.
Example: Multiline comments using multiple hashtags (#)
Python3

# Python program to demonstrate

# multiline comments

print("Multiline comments")

Output
Multiline comments

24
LANGUAGE COMPONENTS

3.1 Indentation
 Indentation refers to the spaces at the beginning of a code line. Where in other programming languages the
indentation in code is for readability only, the indentation in Python is very important. Python uses

indentation to indicate a block of code.

3.2 The if Statement


Python if statement is one of the most commonly used conditional statements in programming languages. It
decides whether certain statements need to be executed or not. It checks for a given condition, if the
condition is true, then the set of code present inside the ” if ” block will be
Executed otherwise not.

3.3 Operators

25
 Operator is a symbol to perform operation over the operands.
1. Arithmetic operator

+,-,\,/Normal division,%,*,** exponent operator || power operator//float division

a=10
b=3
Print (a+b) #13
Print (a-b) #7
Print (a*b) #30
Print (a/b) #3.3333333
Print (a%b) #1
2. Relational operator | comparision operator
<,>,<=,>=
x=20
y=10
Print (x>y) #True
Print (x>=y) #True
Print (x<y) #False
Print (x<=y) #False
3. Equality operator
= =,!=.
a=10
b=20
Print (a==b) #False
print (a! =b) #True
Print (b! =a) #True

26
4. Logical operator
And=>it return true if both argument are true.
Example=>
1. True and False #False
Or=>it return true if at least one argument is true.
Example=>
1. True or True #True
2. False or True #True
3. False or False #False
Not=>complement
Example=>
1. Not True #False
2. Not False #True
print (30>40 and 40<50) #True
Print (50<=50 and 30<=50) #True
Print (50>=50 and 30>50) #False
Print (50<=50 and 40>50) #False
Print (30>40 or 40<50) #True
5. Assignment operator=>Assignment operator is used to assign value to the variable.
=,+=,-=,/=,//=,*=,**=,%=
a=10
b=4
A+=30=>a=a+30
A+=b=>a=a+b (10+2)#12
a-=5 print (a) #5
A**=2=>a=a**2
Print #100
27
A**=b=>a=a**4=>10*10*10*10=>10000
a//=b=>a=a//b#3.0

6. Membership operator
Membership operator it used to check given object present in given collection or not(String,
List, Tuple, Dict, Range).
(a) In=>it return true if given object is present in given collection.
(b) Not in=>it returns true if given object is not present in given collection.
Example:
Print ("T" in "Techpile") #True
Print ("t" in "Techpile") #False
x="welcome to techpile"
y="pi"
Print(y in x) #True
Print(y not in x) #False
7. Turnary operator|| condition operator
Syntax=>first value if condition else second value
=>if first satatement is true the first value considered otherwise second value
considered.
a=20
b=10
x=30 if (a>b) else 50
Print(x)
Print ("a is big") if (a>b) else print ("b is small")
Output=a is big
28
2.3 THE WHILE LOOP
 Python is a dynamic, interpreted (bytecode-compiled) language. There are no
type declarations of variables, parameters, functions, or methods in source
code. This makes the code short and flexible, and you lose the compile-time
type checking of the source code.
2.4 BREAK AND CONTINUE

This model has the same phases as the waterfall model, but with fewer restrictions.
Generally the phases occur in the same order as in the waterfall model, but they may
be conducted in several cycles.
2.4. THE FOR LOOP
We want to execute a group of statement for every element present in given sequence (string,
list, tuple, set, dect, range).
Syntax=>
For variablename in collection:
Statement
Statement
Statement
Name="Techpile"
For x in name:
Print ("hello")

29
COLLECTIONS

4.1 Introduction

 The collection Module in Python provides different types of containers. A Container is


an object that is used to store different objects and provide a way to access the
contained objects and iterate over them. Some of the built-in containers
are Tuple, List, and Dictionary etc. In this article, we will discuss the different
containers provided by the collections module.
 Table of Content:
 Counters
 Ordered Dict
 Default Dict
 Chain Map
 Named Tuple
 DeQue
 User Dict
 User List
 User String

4.2 LISTS

 Lists are used to store multiple items in a single variable. Lists are one of 4
built-in data types in Python used to store collections of data, the other 3 are
Tuple, Set, and Dictionary, all with different qualities and usage.
 If we want to represent a group of values where duplicates are allowed and order is
required to preserve then we have to used list data type.
 1.list is denoted by [] bracket
 2. Here duplicates are allowed.
 3. Collection heterogeneous data types element.

30
 4.order is applicable
 5. Indexing and slicing concept is applicable.
 6. Mutable.
 example:
 syntax=>listName=[item1,item2,item3......item Name]
 example:
 list = [10,20,30,"Ram",20,True,40.5]
4.3 TUPLES
 Tuple is same as a list but tuple is immutable.
 Tuple is read only version of list.
1. Tuple is denoted by () brackets.
2. Duplicates are allowed
3. Order applicable.
4. Indexing and slicing concept are applicable.
5. Collection of heterogeneous data types element.
6. Immutable.
Syntax=>
Tuplename= (item, item2, item3........itemN)
t= ("Ram", 10, 10.7, True,"Ram")
Print (t [0]) #Ram
Print (t [1]) #10
t.append (40) #error

4.4 SETS
 If we want to represent a group of values as single entity where duplicates are not
allowed and order is not application then we have use set data type.
1. Set data type is denoted by {} bracket.
2. Order is not applicable.
31
3. Indexing and slicing concept is not applicable.
4. Heterogeneous elements are allowed.

5. Duplicates are not allowed.


6. Mutable.
Example=>
s= {item1, item2, item3.....itemN}
4.5 DECTIONARIES
 Dict data type is used to represent a group value in form of key-value pare.
Syntax=>
DictName= {key1:value1, key2:value2, key3:value3....keyN: valueN}
Example=>
d= {1:"Ram",2:"Reena",3:100,1:"Rohan"}
How to access value of dict data type
Dictname [key]
Exam:
Print (d [1]) #Rohan
Print (d [2]) #Reena
Print (d [3]) #100
1dictionary is denoted by {} bracket
2. Order is not applicable
3. Indexing and slicing is not applicable
4. Value can be heterogeneous but key cannot be heterogeneous.
5. Mutable.

32
FUNCTIONS

5.1 INTRODUCTION

 A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function
In Python a function is defined using the def keyword:

Example
Def my_function ():
print ("Hello from a function")

Calling a Function
To call a function, use the function name followed by parenthesis:

Example
Def my_function
Print ("Hello from a function")

my_function()

Arguments
Information can be passed into functions as arguments.

33
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the function is called,
we pass along a first name, which is used inside the function to print the full name:

Example
def my_function(fname):
print(fname +" Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Arguments are often shortened to args in Python documentations.

Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are passed
into a function.

From a function's perspective:

A parameter is the variable listed inside the parentheses in the function definition.

An argument is the value that is sent to the function when it is called.

Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if
your function expects 2 arguments, you have to call the function with 2 arguments, not more,
and not less.

Example

34
This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):


print(fname +" "+ lname)

my_function("Emil", "Refsnes")

If you try to call the function with 1 or 3 arguments, you will get an error:
Example

This function expects 2 arguments, but gets only 1:

Def my_function(fname,lname):
print(fname+ "" +lname)

my_function("Emil")

Arbitrary Arguments, *args


If you do not know how many arguments that will be passed into your function, add a * before
the parameter name in the function definition.

This way the function will receive a tuple of arguments, and can access the items accordingly:

Example
If the number of arguments is unknown, add a * before the parameter name:

Def my_function (*kids):


print("Theyoungestchildis" +kids[2])

my_function("Emil", "Tobias", "Linus")

Arbitrary Arguments are often shortened to *args in Python documentations.

Keyword Arguments
35
You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

Example
Def my_function(child3,child2,child1):
print("Theyoungestchildis" +child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

The phrase Keyword Arguments are often shortened to kwargs in Python documentations.

Default Parameter Value

The following example shows how to use a default parameter value.

If we call the function without argument, it uses the default value:

Example
def my_function(country= "Norway"):
print("Iamfrom" + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Passing a List as an Argument


You can send any data types of argument to a function (string, number, list, dictionary etc.),
and it will be treated as the same data type inside the function.E.g. if you send a List as an
argument, it will still be a List when it reaches the function:

Example
36
def my_function(food):
for x in food:
print(x)

fruits=["apple", "banana", "cherry"]

my_function(fruits)

Return Values
To let a function return a value, use the return statement:

Example
def my_function(x):
return 5 *x

print(my_function(3))
print(my_function(5))
print(my_function(3))
The pass Statement
Function definitions cannot be empty, but if you for some reason have a function definition
with no content, put in the pass statement to avoid getting an error.

Example
def myfunction():
pass

5.1 PARAMETERS OR ARGUMENTS IN PYTHON


 parameters are input to the function if any function contains parameter then add the
time calling function compulsary be have to provide value the parameter otherwise be
will get error:

37
Example: def sum(x, y):
Print ("sum is :",( x+y))
Sum () #error
Sum (10, 20) #sum is: 30
************Return Statement**************
Function can take input as parameter and execute business logic and return output to the caller
function.
def sum(x, y)
res=x+y
x=sum (20, 30)
Print(x) #None
Print(x) #None
 Returning multiple values from a function.
Exa. =>

def cal(x, y)
sum=x+y
Sum=x-y
m=x*y
div=x/y
fdiv=x//y
exp=x**y
Return sum, sum, m, div, fdiv, and exp
A, b, c, d, e, f=cal (20, 10)
Print ("sum:” a)
Print ("sub:” b)
Print ("m:” c)
38
Print ("div:” d)
Print ("fdiv:” e)
Print ("exp:” f)
x=sum (10, 20)
Print ("result is", x)
Print (sum (50, 60))
Def sum(x, y)
Res=x+y
x=sum (20, 30)
Print(x) #None
5.2 BUILT IN FUNCTIONS
 The Python built-in functions are defined as the functions whose functionality is pre-
defined in Python. The python interpreter has several functions that are always present
for use. These functions are known as Built-in Functions.

Python abs () Function


The python abs () function is used to return the absolute value of a number. It takes only one
argument, a number whose absolute value is to be returned. The argument can be an integer
and floating-point number. If the argument is a complex number, then, abs () returns its
magnitude.

Python abs () Function Example

number
# Integer
integer = -20
print ('Absolute value of -40 is:’ abs(integer))

# floating number
floating = -20.83
print('Absolute value of -40.83 is:’ abs(floating))

Output:
39
Absolute value of -20 is: 20
Absolute value of -20.83 is: 20.83

5.1 MAP
Map in Python is a function that works as an iterator to return a result after applying a
function to every item of an iterable (tuple, lists, etc.). It is used when you want to apply a
single transformation function to all the iterable elements. The iterable and function are passed
as arguments to the map in Python.
Workings of the Python Map() Function
 The map in Python takes a function and an iterable/iterables. It loops over each item of
an iterable and applies the transformation function to it. Then, it returns a map object that
stores the value of the transformed item. The input function can be any callable function,
including built-in functions, lambda functions, user-defined functions, classes, and
methods. Now, calculate the same multiplication as you did in the previous example, but
this time with both the for loop and the map functions separately, to understand how the
map () function works.

Example: Using For Loop

num = [3, 5, 7, 11, 13]

Mul = []

for n in num:

mul.append(n ** 2)

print (mul)

Output:

40
5.1 FILTER
The filter() method filters the given sequence with the help of a function that tests each
element in the sequence to be true or not.
Syntax:
Filter (function, sequence)
Parameters:
function: function that tests if each element of a
sequence true or not.
sequence: sequence which needs to be filtered, it can
be sets, lists, tuples, or containers of any iterators.
Returns:
returns an iterator that is already filtered.

# function that filters vowels

def fun(variable):

letters = ['a', 'e', 'i', 'o', 'u']

if (variable in letters):

return True

else:

return False

41
# sequence

sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r']

# using filter function

filtered = filter(fun, sequence)

print('The filtered letters are:')

for s in filtered:

print(s)

Output:
The filtered letters are:
e
e

5.1 INNER FUNCTION

A function which is defined inside another function is known as inner function or nested
function. Nested functions are able to access variables of the enclosing scope. Inner functions
are used so that they can be protected from everything happening outside the function. This
process is also known as Encapsulation. To know more about encapsulation
Example:
42
# Python program to illustrate

# nested functions

def outerFunction(text):

text = text

def innerFunction():

print(text)

innerFunction()

if __name__ == '__main__':

outerFunction('Shreya!')

Output:
Shreya

43
44
MODULES

6.1 MODULES

1. import modulename

2. import module1,module2,module3.....modulename
3 .import module as aliasname
4. import module1 as m1, module2 as m2,....moduleN as mn.
5. from module import member
6. from module import member1, member2, member3....memberN
7from module import member as aliasname
8. from module import member1,as m1,member2,as m2...member as mn
9. from module import *
6.2 STANDARD MODULE-SYS

 The sys module in Python provides various functions and variables that are used
to manipulate different parts of the Python runtime environment. It allows
operating on the interpreter as it provides access to the variables and functions that
interact strongly with the interpreter.
6.3 STANDARD MODULE-MATH

Python has a built-in module that you can use for mathematical tasks.

The math module has a set of methods and constants.

Math Methods
45
Method Description

math.acos() Returns the arc cosine of a number

math.acosh() Returns the inverse hyperbolic cosine of a number

math.asin() Returns the arc sine of a number

math.asinh() Returns the inverse hyperbolic sine of a number

math.atan() Returns the arc tangent of a number in radians

math.atan2() Returns the arc tangent of y/x in radians

math.atanh() Returns the inverse hyperbolic tangent of a number

math.ceil() Rounds a number up to the nearest integer

math.comb() Returns the number of ways to choose k items from n items without repetition and orde

math.copysign() Returns a float consisting of the value of the first parameter and the sign of the second

math.cos() Returns the cosine of a number

math.cosh() Returns the hyperbolic cosine of a number

math.degrees() Converts an angle from radians to degrees

math.dist() Returns the Euclidean distance between two points (p and q), where p and q are the co
point

math.erf() Returns the error function of a number

math.erfc() Returns the complementary error function of a number

math.exp() Returns E raised to the power of x

math.expm1() Returns Ex – 1

math.fabs() Returns the absolute value of a number

math.factorial() Returns the factorial of a number

math.floor() Rounds a number down to the nearest integer

math.fmod() Returns the remainder of x/y

math.frexp() Returns the mantissa and the exponent, of a specified number

46
6.4 STANDARD MODULTIME

 There is a popular time module available in Python which provides functions for
working with times, and for converting between representations. The
function time. time() returns the current system time in ticks since 00:00:00 hrs
January 1, 1970(epoch).
TO DEVELOP THIS PROJECT THE VARIOUS SOFTWARE RESOURCES ARE USED.

 Front End - HTML-CSS &Bootstrap


 Back End - SQLite
 Web Server - Apache Server
 Technology - Python technology
 Code-Behind Language -Python
 IDE - PyCharm

3.3 SUPPORT AND MAINTENANCE: -


One-year free support for rectifying system bugs including front end and beck end
will be provided. During warranty period Software Engineers will be responsible for
removing bugs and improving it. After one year support can be extended @ 20% of
the total product deployment cost.

EXCEPTIONS

47
7.1 RUNTIME ERRORS
Some examples of Python runtime errors:
 division by zero.
 performing an operation on incompatible types.
 using an identifier which has not been defined.
 accessing a list element, dictionary value or objects attribute which doesn't exist.
 trying to access a file which doesn't exist.

CLASSES IN PYTHON

8.1 CLASSES IN PYTHON


 A Class is like an object constructor, or a "blueprint" for creating objects.
 A class is a user-defined blueprint or prototype from which objects are created.

Classes provide a means of bundling data and functionality together. Creating a new
class creates a new type of object, allowing new instances of that type to be made.
Each class instance can have attributes attached to it for maintaining its state. Class
instances can also have methods (defined by their class) for modifying their state.
 Syntax: Class Definition

Some points on Python class:


 Classes are created by keyword class.
 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the dot (.) operator. Eg.:
Myclass.Myattribute

8.2 PRINCIPLES OF OBJECT ORIENTATION


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.
48
Main Concepts of Object-Oriented Programming (OOPs)
 Class
 Objects
 Polymorphism
 Encapsulation
 Inheritance
 Data Abstraction

OOPs

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.
To understand the need for creating a class let’s consider an example, let’s say you wanted to
track the number of dogs that may have different attributes like breed, age then how would
you know which element is supposed to be which? What if you wanted to add other
properties to these dogs? This lacks organization and it’s the exact need for classes.
Some points on Python class:
 Classes are created by keyword class.
 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the dot (.) operator. Eg.:
Myclass.Myattribute
Class Definition Syntax:
class ClassName:
# Statement-1
.

49
.
.
# Statement-N

Example: Creating an empty Class in Python

Python

# Python3 program to

# demonstrate defining

# a class

class Dog:

pass

In the above example, we have created a class named dog using the class keyword.
Objects
The object is an entity that has a state and behavior associated with it. It may be any real-
world object like a mouse, keyboard, chair, table, pen, etc. Integers, strings, floating-point
numbers, even arrays, and dictionaries, are all objects. More specifically, any single integer or
any single string is an object. The number 12 is an object, the string “Hello, world” is an
object, a list is an object that can hold other objects, and so on. You’ve been using objects all
along and may not even realize it.
An object consists of:
 State: It is represented by the attributes of an object. It also reflects the properties of an
object.
 Behavior: It is represented by the methods of an object. It also reflects the response of an
object to other objects.
 Identity: It gives a unique name to an object and enables one object to interact with other
objects.

50
To understand the state, behavior, and identity let us take the example of the class dog
(explained above).

 The identity can be considered as the name of the dog.


 State or Attributes can be considered as the breed, age, or color of the dog.
 The behavior can be considered as to whether the dog is eating or sleeping.

Example: Creating an object

8.3 CREATING CLASSES

class Dog:

# class attribute

attr1 = "mammal"

# Instance attribute

def __init__(self, name):

self.name = name

def speak(self):

print("My name is {}".format(self.name))

51
# Driver code

# Object instantiation

Rodger = Dog("Rodger")

Tommy = Dog("Tommy")

# Accessing class methods

Rodger.speak()

Tommy.speak()

Output
My name is Rodger
My name is Tommy

8.4 METHOD IN PYTHON


A method in python is somewhat similar to a function, except it is associated with
object/classes. Methods in python are very similar to functions except for two major
differences.
 The method is implicitly used for an object for which it is called.
 The method is accessible to data that is contained within the class.
General Method Syntax
class ClassName:
def method_name():
…………..
# Method_body
………………
52
Let’s understand the method through one simple code −
class Pet(object):
def my_method(self):
print("I am shreya")
cat = Pet()
cat.my_method()
Output
I am shreya
In the above code, we first defined class “Pet”. Then we created the object “cat” from this
blueprint. Next, we call our custom method called my_method with the object(.i.e. cat).

8.5 CLASS VARIABLES


If the value of a variable is not varied from object to object, such types of variables are
called class variables or static variables. Class variables are shared by all instances of a class.
8.6 INHERITANCE

 Inheritance allows us to define a class that inherits all the methods and properties from
another class.

Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived class.

8.7 POLYMORPHISM
 The word polymorphism means having many forms. In programming, polymorphism

means the same function name (but different signatures) being used for different
types.

 Python3

53
# A simple Python function to demonstrate

# Polymorphism

def add(x, y, z = 0):

return x + y+z

# Driver code

print(add(2, 3))

print(add(2, 3, 4))

Output:
5
9

54
7.TESTING
Testing is the integral part of any System Development Life Cycle insufficient and
interested application tends to crash and result in loss of economic and manpower
investment besides user’s dissatisfaction and downfall of reputation.
Software is to be tested for the best quality assurance, an assurance that system
meets the specification and requirement for its intended use and performance.
System Testing is the most useful practical process of executing the program
with the implicit intention of finding errors that makes the program fail.

Types of Testing:

Black Box (Functional) Testing:

Testing against specification of system or component. Study it by examining its


inputs and related outputs. Key is to devise inputs that have a higher likelihood of
causing outputs that reveal the presence of defects. Use experience and knowledge of
domain to identify such test cases. Failing this a systematic approach may be
necessary. Equivalence partitioning is where the input to a program falls into a
number of classes,

55
e.g., positive numbers vs. negative numbers. Programs normally behave the same
way for each member of a class. Partitions exist for both input and output. Partitions
may be discrete or overlap. Invalid data (i.e., outside the normal partitions) is one or
more partitions that should be tested.
Internal System design is not considered in this type of testing. Tests are based on
requirements and functionality.
This type of test case design method focuses on the functional requirements of the
software, ignoring the control structure of the program. Black box testing attempts to
find errors in the following categories:

 Incorrect or missing functions.

 Interface errors.

 Errors in data structures or external database access.

 Performance errors.

 Initialization and termination errors.

White Box (Structural) Testing:

Testing based on knowledge of structure of component (e.g., by looking at source


code). Advantage is that structure of code can be used to find out how many test case
need to be performed. Knowledge of the algorithm (examination of the code) can be
used to identify the equivalence partitions. Path testing is where the tester aims to
exercise every independent execution path through the component. All conditional
statements tested for both true and false cases. If a unit has an control statements,
56
there will be up to
2npossiblepathsthroughit.Thisdemonstratesthatitismucheasiertotestsmall

57
program units than large ones. Flow graphs are a pictorial representation of the paths
of control through a program (ignoring assignments, procedure calls and I/O
statements). Use flow graph to design test cases that execute each path. Static tools
may be used to make this easier in programs that have a complex branching structure.
Tools support. Dynamic program analysers instrument a program with additional
code. Typically, this will count how many times each statement is executed. At end
print out report showing which statements have and have not been executed.
Problems with flow graph derived testing:
 Data complexity could not take into account.

 We cannot test all paths in combination.

 In really only possible at unit and module testing stages because beyond that

complexity is too high.


This testing is based on knowledge of the internal logic of an application’s code.
Also known as a Glass Box Testing. Internal software and code working should be
known for this type of testing. Tests are based on coverage of code statements,
branches, paths, conditions.

Unit Testing:
Unit testing concentrates on each unit of the software as implemented in the code.
This is done to check syntax and logical errors in programs. At this stage, the test
focuses on each module individually, assuring that it functions properly as a unit. In
our case, we used extensive white-box testing at the unit testing stage.

Incremental Integration Testing:


Bottom-up approach for testing i.e., continuous testing of an application as new
functionality is added; Application functionality and modules should be independent
enough to test separately done by programmers or by testers.
58
Integration Testing:
Testing of integration modules to verify combined functionality after integration

.Modules are typically code modules, individual applications, client and server and
distributed systems.

Functional Testing:

This type of testing ignores the internal parts and focus on the output is as per requirement or
not. Black box type testing geared to functionality requirements of an application.

System Testing:

Entire system is tested as per the requirements. Black box type test that is based on overall
requirement specifications covers all combined parts of a system.

End-to-End Testing:

Similar to system testing, involves testing of a complete application environment in a


situation that mimics real-world use, such as interacting with a database, using network
communications, or interacting with hardware, applications, or system if appropriate.

Regression Testing:

Testing the application as a whole for the modification in any module or


59
functionality. Difficult to cover all the system in regression testing so typically
automation tools are used for these testing types.

60
Acceptance Testing:

Normally this type of testing is done to verify if system meets the customer specified
requirements. User or customers do this testing to determine whether to accept application.

Performance Testing:

Term often used interchangeably with “stress” and “load” testing, To check whether system
meets performance requirements, used different performance and load tools to do this .

Alpha Testing:
In house virtual user environment can be created for this type of testing. Testing is done at
the end of development. Still minor design changes may be made as a result of such testing.

Beta Testing:

Testing typically done by end-users or others. This is final testing before releasing
application for commercial purpose.

61
9. FUTURE SCOPE
Following modification or upgrades can be done in system.

1. More than one company can be integrated through this software.

2. Web services can be used to know exact donation status of packets.

3. Client can check there donation delivery status online.

10. CONCLUSION:
At the last the Conclusion of project is to develop a web-application which the help
programmer to get help from the site, so that they can develop their project and
application Different Technologies and make a group of programmer.A Group is a
social unit of any size that shares common values, ideas and code and queries. The
portal doesn’t have to be expensive. It supports multiple programmer goals.
NGO is not only a web portal; it is a live product of board of technical education. In
future we will add more and more features on it.

62

You might also like