A Summer Training Report On "Python Language"
A Summer Training Report On "Python Language"
“PYTHON LANGUAGE”
TABLE OF CONTENTS
Introduction about the Industry
CHAPTER 1 Introduction
Python is relatively simple, so it's easy to learn since it requires a unique syntax that focuses on
readability. Developers can read and translate Python code much easier than other languages. In
turn, this reduces the cost of program maintenance and development because it allows teams to
work collaboratively without significant language and experience barriers.
Additionally, Python supports the use of modules and packages, which means that programs can
be designed in a modular style and code, can be reused across a variety of projects. Once you've
developed a module or package you need, it can be scaled for use in other projects, and it's easy
to import or export these modules.
History of Python - Python was developed by Guido van Rossum in the late eighties and early
nineties at the National Research Institute for Mathematics and Computer Science in the
Netherlands. Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, Smalltalk, and UNIX shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the GNU General
Public License (GPL).Python is now maintained by a core development team at the institute,
although Guido van Rossum still holds a vital role in directing its progress.
Python's name is derived from the British comedy group Monty Python, whom Python
creator Guido van Rossum enjoyed while developing the language. Monty Python references
appear frequently in Python code and culture.
Versions in Python –There were many versions of pythons since its release in 1994.The
following python versions are major and notable minor releases.
Python 1.0 - January 1994
Python 1.5 - December 31, 1997
Python 1.6 - September 5, 2000
Python 2.0 - October 16, 2000
Python 2.1 - April 17, 2001
Python 2.2 - December 21, 2001
Python 2.3 - July 29, 2003
Python 2.4 - November 30, 2004
Python 2.5 - September 19, 2006
Python 2.6 - October 1, 2008
Python 2.7 - July 3, 2010
Python 3.0 - December 3, 2008
Python 3.1 - June 27, 2009
Python 3.2 - February 20, 2011
Python 3.3 - September 29, 2012
Python 3.4 - March 16, 2014
Python 3.5 - September 13, 2015
Python 3.6 - December 3, 2016
Python 3.7.2 - June 27, 2018
Python 3.7.3 - March 25, 2019
Why Python? - The language’s core philosophy is summarized in the document ,which
includes aphorism such as-
Beautiful is better than ugly
Simple is better than complex
Complex is better than complicated
Readability counts
Explicit is better than implicit
Python Features -
Python's features include −
Easy-to-learn-Python has few keywords, simple structure, and a clearly defined syntax.
This allows the student to pick up the language quickly.
Easy-to-read− Python code is more clearly defined and visible to the eyes.
Easy-to-maintain− Python's source code is fairly easy-to-maintain.
A broad standard library− Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode− Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
Portable− Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
Extendable− You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
Databases− Python provides interfaces to all major commercial databases.
GUI Programming− Python supports GUI applications that can be created and ported to
many system calls, libraries and windows systems, such as Windows MFC, Macintosh,
and the X Window system of Unix.
Scalable− Python provides a better structure and support for large programs than shell
scripting.
Python 2 Python 3
It is more stable and transparent version of the It is the future of Python designed to address
python programming language. the design flaws in the previous version.
The print syntax is treated as a statement The print is explicitly treated as a function and
rather than function which requires to be replaced by the print () function in Python 3
wrapped in parenthesis. which requires an extra pair of parenthesis.
ASCII string type is used by default to store Unicode is the implicit type by default.
strings.
It simply returns an integer to the nearest It makes integer division more intuitive by
whole number when dividing two integers. using true division for integers and floats.
Xrange function reconstructs the sequence Xrange is replaced by range () function in
every time. Python 3.
Getting Python -
The most up-to-date and current source code, binaries, documentation, news, etc., is available
on the official website of Python https://www.python.org/
You can download Python documentation from https://www.python.org/doc/. The
documentation is available in HTML, PDF, and PostScript formats.
Installing Python -
Python distribution is available for a wide variety of platforms. You need to download only the
binary code applicable for your platform and install Python.
If the binary code for your platform is not available, you need a C compiler to compile the
source code manually. Compiling the source code offers more flexibility in terms of choice of
features that you require in your installation.
1. Interactive Mode Programming -Type the following text at the Python prompt and press
the Enter –
2. Script Mode Programming-Let us write a simple Python program in a script. Python files
have extension.py. Type the following source code in a test.py file –
Data Structure - Data structures are fundamental concepts of computer science which helps
is writing efficient programs in any language. Python is a high-level, interpreted, interactive and
object-oriented scripting language using which we can study the fundamentals of data structure
in a simpler way as compared to other programming languages
Lines and Indentation – Python provides no braces to indicate blocks of code for class and
function definitions or flow control. Blocks of code are denoted by line indentation, which is
rigidly enforced.
Comments in Python - A hash sign (#) that is not inside a string literal begins a comment. All
characters after the # and up to the end of the physical line are part of the comment and the
Python interpreter ignores them.
1) Single Line Comment - In case user wants to specify a single line comment, then comment
must start with ?#? -
Example –
2) Multi Line Comment - Multi lined comment can be given inside triple quotes.
Example –
Strings - Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows for either pairs of single or double quotes. The plus (+) sign is
the string concatenation operator and the asterisk (*) is the repetition operator.
Lists - Lists are the most versatile of Python's compound data types. A list contains items separated
by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C.
Ordered collection of data.
Supports similar slicing and indexing functionalities as in the case of String.
They are mutable.
For example –
Tuples - A tuple is another sequence data type that is similar to the list. A tuple consists of a number
of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
Immutable in Nature.
No type restriction
For example –
.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and size can
be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
Dictionary - Python's dictionaries are kind of hash table type. They work like associative.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square
braces ([]).
Lists are sequences but the dictionaries are mappings.
They are mapping between a unique key and a value pair.
For example −
Data Type Conversion - Sometimes, you may need to perform conversions between the built-
in types. To convert between types, you simply use the type name as a function.
There are several built-in functions to perform conversion from one data type to another. These
functions return a new object representing the converted value.
int (a, base)- This function converts any data type to integer. ‘Base’ specifies the base in
which string is if data type is string.
float ()- This function is used to convert any data type to a floating point number.
list () -This function is used to convert any data type to a list type.
dict () -This function is used to convert a tuple of order (key,value) into a dictionary.
Types of Operator - The operator can be defined as a symbol which is responsible for a
particular operation between two operands. Operators are the pillars of a program on which the
logic is built in a particular programming language. Python language supports the following
types of operators -
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Comparison operator - Comparison operators are used to comparing the value of the two
operands and returns boolean true or false accordingly. The comparison operators are described
in the following table
assignment operators - The assignment operators are used to assign the value of the right
expression to the left operand. The assignment operators are described in the following table.
Bitwise operator - The bitwise operators perform bit by bit operation on the values of the two
operands.
Logical Operators - The logical operators are used primarily in the expression evaluation to
make a decision. Python supports the following logical operators.
Membership Operators - Python membership operators are used to check the membership of
value inside a data structure. If the value is present in the data structure, then the resulting value
is true otherwise it returns false.
Loops in Python
Python For Loops – 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
language, and works more like an iterator method as found in other object-orientated
programming languages. With the for loop we can execute a set of statements, once for each item
in a list, tuple, set etc.
The break Statement -With the break statement we can stop the loop before it has looped
through all the items.
The continue Statement - With the continue statement we can stop the current iteration of
the loop, and continue with the next:
The range () Function -To loop through a set of code a specified number of times, we can
use the range () function. The range () function returns a sequence of numbers, starting from 0
by default, and increments by 1 (by default), and ends at a specified number.
Else in For Loop – The else keyword in a for loop specifies a block of code to be executed
when the loop is finished.Nested Loops - A nested loop is a loop inside a loop. The "inner
loop" will be executed one time for each iteration of the "outer loop".
While Loop – A while loop statement in Python programming language repeatedly executes
a target statement as long as a given condition is true.
Syntax -
The syntax of a while loop in Python programming language is −
while expression:
statement(s)
Arrays in Python
Array is a container which can hold a fix number of items and these items should be of the same
type. Most of the data structures make use of arrays to implement their algorithms. Following
are the important terms to understand the concept of Array.
As per the above illustration, following are the important points to be considered.
Index starts with 0.
Array length is 10 which means it can store 10 elements.
Each element can be accessed via its index. For example, we can fetch an element at
index 6 as 9.
Array is created in Python by importing array module to the python program. Then the array is
declared as shown in below.
2D Array - Two dimensional array is an array within an array. It is an array of arrays. In this
type of array the position of an data element is referred by two indices instead of one. So it
represents a table with rows and columns of data. In the below example of a two dimensional
array, observer that each array element itself is also an array.
Consider the example of recording temperatures 4 times a day, every day. Some times the
recording instrument may be faulty and we fail to record data. Such data for 4 days can be
presented as a two dimensional array as below.
Day 1 - 11 12 5 2
Day 2 - 15 6 10
Day 3 - 10 8 12 5
Day 4 - 12 15 8 6
print(T[0])
print(T[1][2])
Function
A function is a block of organized, reusable code that is used to perform a single, related action.
Defining a Function -
You can define functions to provide the required functionality. These are simple rules to define
a function in Python-
Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation string
of the function.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an expression
to the caller. A return statement with no arguments is the same as return None.
Syntax-
Recursion allows a function to call itself. Fixed steps of code get executed again and again for
new values. We also have to set criteria for deciding when the recursive call ends.
Recursive Function in Python - A recursive function has to terminate to be used in a program.
A recursive function terminates, if with every recursive call the solution of the problem is
downsized and moves towards a base case. A base case is a case, where the problem can be
solved without further recursion. A recursion can lead to an infinite loop, if the base case is not
met in the calls.
Now we come to implement the factorial in Python. It's as easy and elegant as the mathematical
definition.
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
Exception handling in python
An exception can be defined as an abnormal condition in a program resulting in the disruption in
the flow of the program.
Whenever an exception occurs, the program halts the execution, and thus the further code is
not executed. Therefore, an exception is the error which python script is unable to tackle with.
Python provides us with the way to handle the Exception so that the other part of the code can
be executed without any disruption. However, if we do not handle the exception, the
interpreter doesn't execute all the code that exists after the that.
Common Exceptions -
A list of common exceptions that can be thrown from a normal python program is given
below.
except Exception1:
#block of code
except Exception2:
#block of code
#other code
Example -
try:
a = int(input("Enter a:"))
b=int(input("Enter b:"))
c=a/b;
print("a/b=%d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")
File Handling
File handling is an important part of any web application. Python has several functions for
creating, reading, updating, and deleting files. The key function for working with files in
Python is the open () function.
"r"- Read - Default value. Opens a file for reading, error if the file does not exist
"a"- Append - Opens a file for appending, creates the file if it does not exist
"w"- Write - Opens a file for writing, creates the file if it does not exist
"x"- Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
Syntax -
f = open("demofile.txt")
Example -
f= open ("demofile.txt","r")
print(f.read())
Object Oriented Programming
Class − A user-defined prototype for an object that defines a set of attributes that characterize
any object of the class. The attributes are data members (class variables and instance variables)
and methods, accessed via dot notation.
Object − A unique instance of a data structure that's defined by its class. An object comprises
both data members (class variables and instance variables) and methods.
class Employee:
empCount = 0
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
def displayEmployee(self):