0% found this document useful (0 votes)
84 views20 pages

A Summer Training Report On "Python Language"

Uploaded by

Nitesh Yadav
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)
84 views20 pages

A Summer Training Report On "Python Language"

Uploaded by

Nitesh Yadav
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/ 20

A Summer Training Report On

“PYTHON LANGUAGE”

Submitted to: Submitted by:


Mr. Vivek Srivastava Nitesh Yadav
Department of Computer Science & Engg. B.Tech.(CSE-4th year)
Roll No:1**********
Session: 2019– 2020

Department of Computer Science & Engineering


United College of Engineering and Research , Allahabad
Approved By AICTE, New Delhi & Govt. of U.P.,
Affiliated to AKTU, LUCKNOW

Introduction about the Industry


Udemy is the world's largest online learning platform. It is aimed at professional
adults and students.Udemy has more than 30 million students and 50,000
instructors teaching courses in over 60 languages. There have been over 245
million course enrollments. Students and instructors come from 190+ countries and
2/3 of students are located outside of the U.S. Udemy also has over 4,000
enterprise customers and 80% of Fortune 100 companies use Udemy for employee
upskilling (Udemy for Business). Students take courses largely as a means of
improving job-related skills. Some courses generate credit toward technical
certification. Udemy has made a special effort to attract corporate trainers seeking
to create coursework for employees of their company.Udemy serves as a platform
that allows instructors to build online courses on topics of their choosing. Using
Udemy's course development tools they can upload video, PowerPoint,
presentations, PDFs, audio, zip files and live classes to create courses. Instructors
can also engage and interact with users via online discussion boards. Courses are
offered across a breadth of categories, including business and entrepreneurship,
academics, the arts, health and fitness, language, music, and technology. Most
classes are in practical subjects such as Excel software or using an iPhone camera.
Udemy also offers Udemy for Business, enabling businesses access to a targeted
suite of over 3,000 training courses on topics from digital marketing tactics to
office productivity, design, management, programming, and more. With Udemy
for Business, organizations can also create custom learning portals for corporate
training. Udemy offers paid and free courses, depending on the instructor.

TABLE OF CONTENTS
Introduction about the Industry

CHAPTER 1 Introduction

CHAPTER 2 Data Structure in Python

CHAPTER 3 Operators in Python

CHAPTER 4 Loops in Python

CHAPTER 5 Arrays in Python

CHAPTER 6 Function & Recursion

CHAPTER 7 Exception handling in python

CHAPTER 8 File Handling

CHAPTER 9 Object Oriented Programming


INTRODUCTION
What is Python? - Python is a general-purpose interpreted, interactive, object-oriented, and
high-level programming language. It was created by Guido van Rossum during 1985- 1990.
Like Perl, Python source code is also available under the GNU General Public License (GPL).
Python was conceived in the late 1980s as a successor to the ABC language.

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.

How is Python Used? - Python is a general-purpose programming language, which is


another way to say that it can be used for nearly everything. Most importantly, it is an interpreted
language, which means that the written code is not actually translated to a computer-readable
format at runtime. Whereas, most programming languages do this conversion before the program
is even run. This type of language is also referred to as a "scripting language" because it was
initially meant to be used for trivial projects.

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.

Differences between Python 2 and Python 3 -

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.

First Python Program -

Let us execute programs in different modes of programming.

1. Interactive Mode Programming -Type the following text at the Python prompt and press
the Enter –

>> print "Hello, Python!

This produces the following result –


Hello, Python!

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 –

Print "Hello, Python!"

This produces the following result –


Hello, Python!
Data Structures in Python

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.

Python supports two types of comments:

1) Single Line Comment - In case user wants to specify a single line comment, then comment
must start with ?#? -

Example –

#This is single line comment.

2) Multi Line Comment - Multi lined comment can be given inside triple quotes.

Example –

''’This Is Multi line comment'''

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 –

list1 = ['physics', 'chemistry', 1997, 2000]


list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]

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 –

tup1 = ('physics', 'chemistry', 1997, 2000);


tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

.
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 −

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

print "dict['Name']: ", dict['Name']


print "dict['Age']: ", dict['Age']

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.

 ord () -This function is used to convert a character to integer.

 hex () -This function is to convert integer to hexadecimal string.

 oct () -This function is to convert integer to octal string.

 tuple () -This function is used to convert to a tuple.

 set () - This function returns the type after converting to set.

 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.

 str () -Used to convert integer into a string.

 complex (real, imag) - This function converts real numbers to complex(real,imag)


number.
Operators in Python

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

Arithmetic operators - Arithmetic operators are used to perform arithmetic operations


between two operands. It includes +(addition), - (subtraction), *(multiplication), /(divide),
%(reminder), //(floor division), and exponent (**).

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.

 Element − Each item stored in an array is called an element.


 Index− Each location of an element in an array has a numerical index, which is used to
identify the element.
Array Representation - Arrays can be declared in various ways in different languages. Below
is an illustration.

 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.

from array import *

arrayName = array(typecode, [Initializers])


Adding Array Elements - You can use the append ( ) method to add an element to an
array.

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

The above data can be represented as a two dimensional array as below.

T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]

Accessing Values in a Two Dimensional Array -


The data elements in two dimensional arrays can be accessed using two indices. One index
referring to the main or parent array and another index referring to the position of the data
element in the inner array. If we mention only one index then the entire inner array is printed for
that index position. The example below illustrates how it works.

from array import *

T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [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-

def functionname ( parameters ):


"function"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the same
order that they were defined.
Recursion

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.

1. ZeroDivisionError: Occurs when a number is divided by zero.


2. NameError: It occurs when a name is not found. It may be local or global.
3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.
5. EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.

Problem without handling exceptions –


Example -
a= int(input("Enter a:"))
b=int(input("Enter b:"))
c=a/b;
print("a/b=%d"%c)
print("Hi I am other part of the program")

ZeroDivisionError: division by zero -


Syntax -
try:
#block of code

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.

The open () function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

"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

"t"- Text - Default value. Text mode

"b"- Binary - Binary mode (e.g. images)

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.

Example - Following is the example of a simple Python class −

class Employee:

'Common base class for all employees'

empCount = 0

def __init__(self, name, salary):

self.name = name

self.salary = salary

Employee.empCount += 1

def displayCount(self):

print "Total Employee %d" % Employee.empCount

def displayEmployee(self):

print "Name : ", self.name, ", Salary: ", self.salary

You might also like