0% found this document useful (0 votes)
95 views44 pages

Chinmay Takkar 089 CSE-B

The document summarizes a training report for a Python certificate training program from beginner to expert level that was completed over 3 months. The training was conducted through an online specialization offered by Uplatz Training on Udemy and covered topics such as basic programming, variables, expressions, statements, operators, collections, flow control, functions, file handling and libraries. The training aimed to teach Python programming through a project-based learning approach.

Uploaded by

Savio Savage
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)
95 views44 pages

Chinmay Takkar 089 CSE-B

The document summarizes a training report for a Python certificate training program from beginner to expert level that was completed over 3 months. The training was conducted through an online specialization offered by Uplatz Training on Udemy and covered topics such as basic programming, variables, expressions, statements, operators, collections, flow control, functions, file handling and libraries. The training aimed to teach Python programming through a project-based learning approach.

Uploaded by

Savio Savage
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/ 44

Python Certificate Training ( Beginner To Expert )

Summer Training Report submitted in partial fulfilment of the


requirement for the degree of

B. Tech

In

Computer Science &Engineering

Training Coordinator BY-

MS. RICHA SHARMA Chinmay Takkar

Bhagwan Parshuram Institute of Technology

PSP-4, Sector-17, Rohini, Delhi - 89

May 2020 - August 2020


DECLARATION

This is to certify that the Report entitled “Python Certificate Training


( Beginner To Expert )” which is submitted by me in partial fulfilment of the
requirement for the award of degree B. Tech in Computer Engineering to
BPIT, GGSIP University, Dwarka, Delhi comprises only my original work and
due acknowledgment has been made in the text to all other material used.

Date: Name of Student

Chinmay Takkar

ii
ACKNOWLEDGEMENT

It is my pleasure to be indebted to various people, who directly or indirectly


contributed to the development of this work and who influenced my thinking,
behaviour, and acts during the course of study.

I am thankful to MS. RICHA SHARMA for providing me constant inspiration with


her presence and also guidance for my future endeavours, during the report drafting
process.

I also extend my gratitude to Dr. Deepali Vermani and Prof. Payal Pahwa who
provided their valuable inputs and precious time in accomplishing our projects even
during the Pandemic without fail

Lastly, I would like to thank the almighty and my parents for their moral support and
my batchmates with whom I shared my day-to-day experience and received lots of
suggestions that improved my quality of work.

iii
COMPANY CERTIFICATE

iv
Training Coordinator Certificate

This is to certify that the Report entitled “Python Certificate Training


( Beginner To Expert )” which is submitted by Chinmay Takkar in partial
fulfilment of the requirement for the award of degree B.Tech in Computer
Engineering to BPIT, GGSIP University, Dwarka, Delhi is a record of the
candidate own work and the matter embodied in this report is adhered to the
given format.

Date: Coordinator

v
ABSTRACT

I have completed my training in python programming by completing a specialization


offered by Uplatz Training On Udemy . During this course, I learned a lot of things
related to basic programming, to begin with, my journey ahead.

Python is an interpreted, high-level, and general-purpose programming language.


Created by Guido van Rossum and first released in 1991, Python's design philosophy
emphasizes code readability with its notable use of significant whitespace. Its
language constructs and object-oriented approach aim to help programmers write
clear, logical code for small and large-scale projects.

Python is an open-source language with a very supportive and active community.


Python is designed to be a highly extensible language. This feature support it to be an
open-source language. Python works on the principle of “there is no obvious way to do
a task” rather than “there is more than one way to solve a particular problem”. A large
number of Python implementations and extensions have been developed since its
inception.

Training covers 3 months of learning by the project-based method which means learn
by doing.

vi

TABLE OF CONTENT

Declaration …………………………………………………………………………ii

Acknowledgement………………………………………………………………….iii

Company Certificate………………………………………………………………..iv

Training Coordinator Certificate……………………………………………………v

Abstract …………………………………………………………………………….vi
Chapter 1: Introduction ……………………………………………………………..1

Chapter 2: Python for Everybody Specialization……………………………………4

Chapter 3: Variable, Expression, and Statement ……………………………………6

Chapter 4: Operator …………………………………………………………………9

Chapter 5: Collection in Python …………………………………………………….13

Chapter 6: Flow Control ……………………………………………………………18

Chapter 7: Function …………………………………………………………………21

Chapter 8: File Handling ……………………………………………………………23

Chapter 9: Libraries …………………………………………………………………29

Bibliography ……………………………………………………………………….35

TABLE OF FIGURES

Python keywords ………………………………………………………………..7

Python operator precedence……………………………………………………..12

Mode of file opening ……………………………………………………………24

File methods …………………………………………………………………….28


CHAPTER 1

INTRODUCTION

1.1 PYTHON

Python is a high-level, interpreted, interactive, and object-oriented scripting language.


Python is designed to be highly readable it uses English keywords frequently whereas
other languages use punctuation, and it has fewer syntactical construction than other
languages.

• Python is interpreted. Python is processed at run time by the interpreter. You do


not need to compile your program before executing it. This is similar to PERL
and PHP.
• Python is interactive. You can sit at a Python prompt and interact with the
interpreter directly to write your programs.
• Python is Object-Oriented. Python supports an object-oriented style or technique
of programming that encapsulate code within objects.
• Python is a beginner language. Python is a great language for a beginner-level
programmer and supports the development of a wide range of applications
from simple text processing to www browser to games.

1.2 HISTORY OF PYTHON

Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde
& Informatica (CWI) in the Netherlands as a successor to the ABC language (itself
inspired by SETL), capable of exception handling and interfacing with the Amoeba
operating system. Its implementation began in December 1989. Van Rossum
shouldered sole responsibility for the project, as the lead developer, until 12 July
2018, when he announced his "permanent vacation" from his responsibilities as
Python's Benevolent Dictator For Life, a title the Python community bestowed upon
him to reflect his long-term commitment as the project's chief decision-maker. He now

1
shares his leadership as a member of a five-person steering council. In January 2019,
active Python core developers elected Brett Cannon, Nick Coghlan, Barry Warsaw,
Carol Willing, and Van Rossum to a five-member "Steering Council" to lead the
project. Guido van Rossum has since then withdrawn his nomination for the 2020
Steering council.

Python 2.0 was released on 16 October 2000 with many major new features, including
a cycle-detecting garbage collector and support for Unicode.

Python 3.0 was released on 3 December 2008. It was a major revision of the language
that is not completely backward-compatible.[45] Many of its major features were
backported to Python 2.6.x[46] and 2.7.x version series. Releases of Python 3 include
the 2to3 utility, which automates (at least partially) the translation of Python 2 code to
Python 3.
1.3 Python Syntax compared to other programming languages

Python was designed for readability and has some similarities to the English language
with influence from mathematics.

Python uses new lines to complete a command, as opposed to other programming


languages that often use semicolons or parentheses.

Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions, and classes. Other programming languages often use curly-brackets
for this purpose.

1.4 FEATURES OF PYTHON

There are many features in Python, some of which are discussed below –

• Easy to code: Python is a high-level programming language. Python is very easy


to learn the language as compared to other languages like C, C#, Javascript,
Java, etc. It is very easy to code in python language and anybody can learn
python basics in a few hours or days. It is also a developer-friendly language.

• Free and Open Source: Python language is freely available at the official
websiteSince it is open-source, this means that source code is also available to
the public. So you can download it, use it as well as share it.

2
• Object-Oriented Language: One of the key features of python is Object Oriented
programming. Python supports object-oriented language and concepts of
classes, objects encapsulation, etc.

• GUI Programming Support: Graphical User interfaces can be made using a


module such as PyQt5, PyQt4, wxPython, or Tk in python.PyQt5 is the most
popular option for creating graphical apps with Python.

• High-Level Language: Python is a high-level language. When we write


programs in python, we do not need to remember the system architecture, nor
do we need to manage the memory.

• Extensible feature: Python is an Extensible language. We can write some Python


code into C or C++ language and also we can compile that code in C/C++
language.

• Python is a Portable language: Python language is also a portable language. For


example, if we have python code for windows and if we want to run this code
on other platforms such as Linux, Unix, and Mac then we do not need to
change it, we can run this code on any platform.

• Python is an Integrated language: Python is also an Integrated language because


we can easily integrated python with other languages like c, c++, etc.

• Interpreted Language: Python is an Interpreted Language because Python code


is executed line by line at a time. like other languages C, C++, Java, etc. there
is no need to compile python code this makes it easier to debug our code. The
source code of python is converted into an immediate form called bytecode.

• Large Standard LibraryPython has a large standard library which provides a rich
set of module and functions so you do not have to write your code for every
single thing. There are many libraries present in python for such as regular
expressions, unit-testing, web browsers, etc.

• Dynamically Typed Language: Python is a dynamically-typed language. That


means the type (for example- int, double, long, etc.) for a variable is decided at
run time not in advance because of this feature we don’t need to specify the
type of variable.

CHAPTER 2

PYTHON FOR EVERYBODY SPECIALIZATION


Python for everybody is a well-known course for starting programming as it includes a
lot of assignments and concepts are explained very thoroughly. It is an approximately
8 months long course series but done with dedication it can be done in 2-5 months. I
have completed it in 3 months starting from June 2020 to August 2020.

This Specialization builds on the success of the Python for Everybody course and will
introduce fundamental programming concepts including data structures, networked
application program interfaces, and databases, using the Python programming
language. In the Capstone Project, you’ll use the technologies learned throughout the
Specialization to design and create your applications for data retrieval, processing, and
visualization.

This specialization includes a total of 5 courses:


1. Programming for Everybody (Getting Started with Python)
This course teaches everyone the basics of programming computers using Python.
It covers the basics of how one constructs a program from a series of simple
instructions in Python. The course has no pre-requisites and avoids all but the
simplest mathematics. Anyone with moderate computer experience should be able
to master the materials in this course

2. Python Data structures


This course introduces the core data structures of the Python programming language.
In this, we move past the basics of procedural programming and explore how we can
use the Python built-in data structures such as lists, dictionaries, and tuples to
perform increasingly complex data analysis.

3. Using python for accessing web data


This course shows how one can treat the Internet as a source of data. We will
scrape, parse, and read web data as well as access data using web APIs. We will
work with HTML, XML, and JSON data formats in Python. To succeed in this
course, one should be familiar with the material covered in previous courses in
this specialization. These topics include variables and expressions, conditional

execution (loops, branching, and try/except), functions, Python data structures


(strings, lists, dictionaries, and tuples), and manipulating files.
4. Using a database with python
This course introduces students to the basics of the Structured Query Language
(SQL) as well as basic database design for storing data as part of a multi-step data
gathering, analysis, and processing effort. The course will use SQLite3 as its
database. We will also build web crawlers and multi-step data gathering and
visualization processes. We will use the D3.js library to do basic data visualization.
To succeed in this course, one should be familiar with the material covered in the
first three courses in this specialization.
5. Capstone: Retrieving, Processing, and Visualizing Data with Python

In the capstone, students will build a series of applications to retrieve, process, and
visualize data using Python. The projects will involve all the elements of the
specialization. In the first part of the capstone, students will do some visualizations
to become familiar with the technologies in use and then will pursue their project
to visualize some other data that they have or can find.

CHAPTER 3

VARIABLE, EXPRESSION, AND STATEMENT

3.1 VALUES AND TYPES

There are mainly 3 types of values present in python:

1. integer:

Similar to mathematics Integer is a number without any floating-point or we


can say an integer is a whole number.

Example: 2,3,4,1etc.

2. string:

Any character or series of characters in between single (‘) or double (“) quotes
is considered as a String.

Example:” Ankit”,’ gaur’,”3” etc.

3. float:

Any number with a decimal point is considered to be a Float.

Example:2.35,5.67 etc.

To know the type of a variable we can use type function

>>> type('Hello, World!')


<class 'str'>

>>> type(17)
<class 'int'>

>>> type(3.2)
<class 'float'>
3.2 VARIABLES AND STATEMENT

A variable is a name that refers to a value.An assignment statement creates new


variables and gives them values:

>>> message = 'And now for something completely different'

6
>>> n = 17
>>> pi = 3.1415926535897931

Type of varable gives what type of value is saved in it

>>> type(message)
<class 'str'>
>>> type(n)
<class 'int'>
>>> type(pi)
<class 'float'>

A statement is a unit of code that the Python interpreter can execute.

3.3 VARIABLE NAMING RULES

• Must begin with a letter (a - z, A - B) or underscore (_)


• Other characters can be letters, numbers or _
• Case Sensitive
• Can be any (reasonable) length
• There are some reserved words that you cannot use as a variable name because
Python uses them for other things.
Python keywords
and del from None True
as elif global nonlocal try
assert else if not while
break except import or with
class False in pass yield
continue finally is raise async
def for lambda return await

3.4 TYPE CASTING

There may be times when you want to specify a type on to a variable. This can be done
with casting. therefore done using constructor functions:
7

• int() - constructs an integer number from an integer literal, a float literal (by
rounding down to the previous whole number), or a string literal (providing the
string represents a whole number)
• float() - constructs a float number from an integer literal, a float literal or a string
literal (providing the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including strings,
integer literals, and float literals
8

CHAPTER 4

OPERATOR

4.1 ARTHMATIC OPERATOR

• + Addition = Adds values on either side of the operator.


Example => a + b = 30
• -Subtraction= Subtracts right hand operand from left hand operand.
Example => a – b = 10
• Multiplication = Multiplies values on either side of the operator
Example => a * b = 200
• / Division = Divides left-hand operand by right-hand operand
Example => b / a = 2
• % Modulus= Divides left-hand operand by right-hand operand and returns the
remainder
Example => b % a = 0
• ** Exponent = Performs exponential (power) calculation on operators
Example => a**b =10 to the power 20
• // Floor Division = The division of operands where the result is the quotient in
which the digits after the decimal point are removed. But if one of the
operands is negative, the result is floored, i.e., rounded away from zero
(towards negative infinity):
Example => 9//2 = 4 and 9.0//2.0 = 4.0, 11//3 = 4, 11.0//3 = -4.0

4.2 ASSIGNMENT OPERATOR

• = Assigns: values from right side operands to left side operand


Example => c = a + b assigns value of a + b into c
• += Add AND Assign:It adds right operand to the left operand and assign the
result to left operand
Example => c += a is equivalent to c = c + a

• -= Subtract AND Assign: It subtracts the right operand from the left operand and
assigns the result to the left operand
Example => c -= a is equivalent to c = c - a
• *= Multiply AND Assign: It multiplies the right operand with the left operand
and assigns the result to the left operand
Example => c *= a is equivalent to c = c * a
• /= Divide AND Assign: It divides the left operand with the right operand and
assign the result to the left operand
Example =>c /= a is equivalent to c = c / ac /= a is equivalent to c = c / a • %=
Modulus AND Assign: It takes modulus using two operands and assign the result
to the left operand
Example =>c %= a is equivalent to c = c % a
• **= Exponent AND Assign:Performs exponential (power) calculation on
operators and assign value to the left operand
Example =>c **= a is equivalent to c = c ** a
• //= Floor Division AND Assign:It performs floor division on operators and
assign value to the left operand
Example =>c //= a is equivalent to c = c // a

4.3 IDENTITY OPERATOR


• is Evaluates to true if the variables on either side of the operator point to the
same object and false otherwise.
Example=>x is y, here is results in 1 if id(x) equals id(y).
• is not Evaluates to false if the variables on either side of the operator point to
the same object and true otherwise.
Example=>x is not y, here is not results in 1 if id(x) is not equal to id(y)

4.4 COMPARISON OPERATOR


• & Binary AND Operator copies a bit to the result if it exists in both operands
(a & b) (means 0000 1100)
• | Binary OR It copies a bit if it exists in either operand.

10

(a | b) = 61 (means 0011 1101)


• ^ Binary XOR It copies the bit if it is set in one operand but not both.
(a ^ b) = 49 (means 0011 0001)

• ~ Binary One's Complement


It is unary and has the effect of 'flipping' bits. (~a ) = -61 (means 1100
0011 in 2's complement form due to a signed binary number.
• << Binary Left Shift The left operands value is moved left by the number of
bits specified by the right operand.
a << 2 = 240 (means 1111 0000)
• >> Binary Right ShiftThe left operand's value is moved right by the number of
bits specified by the right operand.
a >> 2 = 15 (means 0000 1111)

4.5 LOGICAL OPERATOR


• and Logical AND :
If both the operands are true then the condition becomes true.
(a and b) is true.
• or Logical OR:
If any of the two operands are non-zero then the condition becomes
true.
(a or b) is true.
• not Logical NOT:
Used to reverse the logical state of its operand.
Not(a and b) is false.

4.6 Membership Operators


• in Evaluates to true if it finds a variable in the specified sequence and false
otherwise.

11

x in y herein results in a 1 if x is a member of sequence y.


• not in Evaluates to true if it does not finds a variable in the specified sequence
and false otherwise.
Python operator precedence
sign description
** Exponentiation (raise to the power)
~,+,- Complement, unary plus, and minus
*,/,%,// Multiply, divide, modulo, and floor division
+,- Addition and subtraction
>>,<< Right and left bitwise shift
& Bitwise 'AND'
^.| Bitwise exclusive `OR' and regular `OR'
<,>,<=,>= Comparison operators
<,>, ==, != Equality operators
= ,%=, /=, //=, -=, +=, *=, Assignment operators
**=
Is, is not Identity operators
In, not in Membership operators
not ,or ,and Logical operators

12

CHAPTER 5
COLLECTION IN PYTHON
5.1 LIST
The list is the most versatile data type available in Python which can be written as a
list of comma-separated values (items) between square brackets. An important thing
about a list is that items in a list need not be of the same type.
Creating a list is as simple as putting different comma-
separated values between square brackets. For example −
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
Basic List Operations Lists respond to the + and * operators much like strings; they
mean concatenation and repetition here too, except that the result is a new list, not a
string.
5.1.1Built-in List Functions & Methods:
SN Function with Description
1 cmp(list1, list2)
Compares elements of both lists.
2 len(list)
Gives the total length of the list.
3 max(list)
Returns item from the list with max value.
4 min(list)
Returns item from the list with min value.
5 list(seq)
Converts a tuple into a list.

SN Methods with Description


1 list.append(obj)
Appends object obj to list
2 list.count(obj)

13

Returns count of how many times obj occurs in the list


3 list. extend(seq)
Appends the contents of seq to list
4 list.index(obj)
Returns the lowest index in the list that obj appears
5 list.insert(index, obj)
Inserts object obj into list at offset index
6 list.pop(obj=list[-1])
Removes and returns last object or obj from list
7 list.remove(obj)
Removes object obj from list
8 list.reverse()
Reverses objects of list in place
9 list.sort([func])
Sorts objects of the list, use compare function if given 13
5.2 TUPLES
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like
lists. The differences between tuples and lists are, the tuples cannot be changed unlike
lists and tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-
separated values. Optionally we can put these comma-
separated values between parentheses also. For example −
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses
containing nothing − tup1 = ();
To write a tuple containing a single value you have to include
a comma, even though there is only one value −
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so
on.

14

Accessing Values in Tuples: To access values in the tuple, use the square brackets for
slicing along with the index or indices to obtain the value available at that index. For
example –
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0]
print "tup2[1:5]: ", tup2[1:5]
When the code is executed, it produces the following result −
tup1[0]: physics tup2[1:5]: [2, 3, 4, 5]
Updating Tuples: Tuples are immutable which means you
cannot update or change the values of the tuple elements. We
can take portions of existing tuples to create new tuples as
the following example demonstrates −
tup1 = (12, 34.56); tup2 = ('abc', 'xyz'); tup3 = tup1 +
tup2; print tup3 When the above code is executed,
it produces the following result − (12, 34.56,
'abc', 'xyz')
Delete Tuple Elements Removing individual tuple elements is not possible. There is,
of course, nothing wrong with putting together another tuple with the undesired
elements discarded.
To explicitly remove an entire tuple, just use the del statement. For example: tup =
('physics', 'chemistry', 1997, 2000); print tup del tup; print "After deleting tup : " print
tup
3.2.1 Basic Tuples Operations:
SN Function with Description
1 cmp(tuple1, tuple2): Compares elements of both tuples.
2 len(tuple): Gives the total length of the tuple.
3 max(tuple): Returns item from the tuple with max value.
4 min(tuple): Returns item from the tuple with min value.
5 tuple(seq): Converts a list into tuple.
5.3 DICTIONARY
Each key is separated from its value by a colon (:), the items are separated by commas,
and the whole thing is enclosed in curly braces. An empty dictionary without any
items is written with just two curly braces, like this: {}.

15

Keys are unique within a dictionary while values may not be. The values of a
dictionary can be of any type, but the keys must be of an immutable data type such as
strings, numbers, or tuples.
Accessing Values in Dictionary:
To access dictionary elements, you can use the familiar
square brackets along with the key to obtain its value.
Following is a simple example −
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
Result –
dict['Name']: Zara dict['Age']: 7
Updating Dictionary We can update a dictionary by adding a new entry or a key-value
pair, modifying an existing entry, or deleting an existing entry as shown below in the
simple example
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry dict['School'] = "DPS School"; # Add new
entry print "dict['Age']: ",
dict['Age'] print "dict['School']: ", dict['School']
Result −
dict['Age']: 8 dict['School']: DPS School
Delete Dictionary Elements We can either remove individual dictionary elements or
clear the entire contents of a dictionary. You can also delete entire dictionary in a
single operation.
To explicitly remove an entire dictionary, just use the del statement. Following is a
simple example –
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
5.3.1 Built-in Dictionary Functions & Methods
SN Function with Description

16

1 cmp(dict1, dict2)
Compares elements of both dict.
2 len(dict)
Gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.
3 str(dict)
Produces a printable string representation of a dictionary
4 type(variable)
Returns the type of the passed variable. If the passed variable is a
dictionary, then it would return a dictionary type.

SN Methods with Description


1 dict.clear():Removes all elements of dictionary dict
2 dict. Copy(): Returns a shallow copy of dictionary dict
3 dict.fromkeys(): Create a new dictionary with keys from seq and
values set to value.
4 dict.get(key, default=None):For key key, returns value or default if
key not in dictionary
5 dict.has_key(key):Returns true if key in dictionary dict, false
otherwise
6 dict.items():Returns a list of dict's (key, value) tuple pairs
7 dict.keys():Returns list of dictionary dict's keys
8 dict.setdefault(key, default=None):Similar to get(), but will set
dict[key]=default if key is not already indict
9 dict.update(dict2):Adds dictionary dict2's key-values pairs to dict

17
CHAPTER 6

FLOW CONTROL

6.1 DECISION MAKING (IF .. ELSE..)

Decision making is required when we want to execute a code only if a certain


condition is satisfied.

6.1.1 IF STATEMENT

Syntax:
If test expression:
Statement()

Here, the program evaluates the test expression and will execute statement(s) only if
the test expression is True.
If the test expression is False, the statement(s) is not executed.
In Python, the body of the if the statement is indicated by the indentation. The body
starts with an indentation and the first unindented line marks the end. Python
interprets non-zero values as True. None and 0 are interpreted as False.

6.1.2 IF... ELSE STATEMENT

Syntax :

if test expression:

statement 1

else:

statement 2

The if … else statement evaluates test expression and will execute the body of if only
when the test condition is True. If the condition is False, the body else is executed.
Indentation is used to separate the blocks.

18
6.1.3 IF…ELIF…ELSE STATEMENT

Syntax:

If test expression:

Body of if

Elif test expression :

Body of elif

Else:

Body of else

The elif is short for else if. It allows us to check for multiple expressions. If the

condition for if is False, it checks the condition of the next elif block and so on. If all

the conditions are False, the body of else is executed.

Only one block among the several if...elif...else blocks is executed according to the
condition.

The if block can have only one else block. But it can have multiple elif blocks.

6.2 ITERATION

6.2.1 FOR LOOP

The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects. Iterating over a sequence is called traversal.

Syntax :

for val in sequence:

Body of for

Here, Val is the variable that takes the value of the item inside the sequence on each
iteration.

19
Loop continues until we reach the last item in the sequence. The body of for loop is
separated from the rest of the code using indentation.

The range() function

We can generate a sequence of numbers using the range() function. range(10) will
generate numbers from 0 to 9 (10 numbers). We can also define the start, stop, and
step size as range(start, stop,step_size). step_size defaults to 1 if not provided.

6.2.2 WHILE LOOP

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

Syntax :

while test_expression:

Body of while

In the while loop, the test expression is checked first. The body of the loop is entered
only if the test_expression evaluates to True. After one iteration, the test expression is
checked again. This process continues until the test_expression evaluates to False.

In Python, the body of the while loop is determined through indentation. The

body starts with indentation and the first unindented line marks the end. Python

interprets any non-zero value as True. None and 0 are interpreted as False.

20
CHAPTER 7

FUNCTIONS

A function is a block of organized, reusable code that is used to perform a single,


related action. Functions provide better modularity for your application and a high
degree of code reusing. Python gives you many built-in functions like print(), etc. but
you can also create your functions. These functions are called user-defined functions.
7.1 Defining a Function
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 optional - the documentation string of
the
function or doc-string.
• 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 a
return None.
Syntax:
def function name( parameters ):
"function doc-string"
Function suite
return [expression]

7.2Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be
included in the function, and structures the blocks of code. Once the basic structure of
a function is finalized, you can execute it by calling it from another function or
directly from the Python prompt.

21
7.3 Scope of Variables
All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access
a particular identifier. There are two basic scopes of variables in Python − 1. Global
variables
2. Local variables
Global vs. Local variables
Variables that are defined inside a function body have a local scope, and those
defined outside have a global scope.
This means that local variables can be accessed only inside the function in which they
are declared, whereas global variables can be accessed throughout the program body
by all functions. When you call a function, the variables declared inside it are
brought into scope.

22
2
CHAPTER 8

FILE HANDLING

We can use python for reading and writing files of different types like txt or binary
etc.

8.1 Files

Files are named locations on disk to store related information. They are used to
permanently store data in non-volatile memory (e.g. hard disk).

Since Random Access Memory (RAM) is volatile (which loses its data when the
computer is turned off), we use files for future use of the data by permanently storing
them.

When we want to read from or write to a file, we need to open it first. When we are
done, it needs to be closed so that the resources that are tied with the file are freed.

Hence, in Python, a file operation takes place in the following order:

1. Open a file

2. Read or write (perform the operation)

3. Close the file

8.2 Opening Files in Python

Python has a built-in open() function to open a file. This function returns a file object,
also called a handle, as it is used to read or modify the file accordingly.ng full path We
can specify the mode while opening a file. In mode, we specify whether we want to
read r, write w or append a to the file. We can also specify if we want to open the file
in text mode or binary mode.
The default is reading in text mode. In this mode, we get strings when reading from
the file.

On the other hand, the binary mode returns bytes and this is the mode to be used when
dealing with non-text files like images or executable files.

23
Mode Description
r Opens a file for reading. (default)
w Opens a file for writing. Creates a new file if it does not exist or
truncates the file if it exists
x Opens a file for exclusive creation. If the file already exists, the
operation fails.
a Opens a file for appending at the end of the file without
truncating it. Creates a new file if it does not exist.
t Opens in text mode. (default)
b Opens in binary mode
+ Opens a file for updating (reading and writing)

Unlike other languages, the character does not imply the number 97 until it is encoded using
ASCII (or other equivalent encodings).
Moreover, the default encoding is platform dependent. In windows, it is cp1252 but utf
8 in Linux. So, we must not also rely on the default encoding or else our code will
behave differently in different platforms. Hence, when working with files in text
mode, it is highly recommended to specify the encoding type.

8.3 Closing Files in Python

When we are done with performing operations on the file, we need to properly close
the file. Closing a file will free up the resources that were tied with the file. It is done
using the close() method available in Python. Python has a garbage collector to clean
up unreferenced objects but we must not rely on it to close the file.

f = open("test.txt", encoding = 'utf-8') # perform file operations


24
f.close()

This method is not entirely safe. If an exception occurs when we are performing some operation
with the file, the code exits without closing the file.

A safer way is to use a try...finally block.


try:
f=open(“test.txt”) #perform file operation
finally:
f.close()
This way, we are guaranteeing that the file is properly closed even if an exception is
raised that causes program flow to stop.

The best way to close a file is by using the statement. This ensures that the file is
closed when the block inside the with statement is exited.

8.4 Writing to Files in Python


To write into a file in Python, we need to open it in write w, append a, or exclusive
creation x mode.
We need to be careful with the w mode, as it will overwrite into the file if it already
exists. Due to this, all the previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using the write()
method. This method returns the number of characters written to the file.

with open("test.txt",'w',encoding = 'utf-8') as f:


f.write("my first file\n")
f.write("This file\n\n")
f.write("contains three lines\n")

This program will create a new file named test.txt in the current directory if it does
not exist. If it does exist, it is overwritten.
We must include the newline characters ourselves to distinguish the different lines.

8.5 Reading Files in Python


25
To read a file in Python, we must open the file in reading r mode. There are various
methods available for this purpose. We can use the read(size) method to read in the
size number of data. If the size parameter is not specified, it reads and returns up to
the end of the file.
We can read the text.txt file we wrote in the above section in the following way:

>>> f = open("test.txt",'r',encoding = 'utf-8')


>>> f.read(4) # read the first 4 data
'This'

>>> f.read(4) # read the next 4 data


' is '

>>> f.read() # read in the rest till end of file


'my first file\nThis file\ncontains three lines\n'

>>> f.read() # further reading returns empty sting


''

We can see that the read() method returns a newline as '\n'. Once the end of the file is
reached, we get an empty string on further reading. We can change our current file
cursor (position) using the seek() method. Similarly, the tell() method returns our
current position (in the number of bytes).

>>> f.tell() # get the current file position


56

>>> f.seek(0) # bring file cursor to initial position


0

>>> print(f.read()) # read the entire file


This is my first file
This file
contains three lines

We can read a file line-by-line using a for loop. This is both efficient and fast.

>>> for line in f:


... print(line, end = '')
...
This is my first file
26
This file contains three lines

In this program, the lines in the file itself include a newline character \n. So, we use
the end parameter of the print() function to avoid two newlines when printing.
Alternatively, we can use the readline() method to read individual lines of a file. This
method reads a file till the newline, including the newline character.

>>> f.readline()
'This is my first file\n'

>>> f.readline()
'This file\n'

>>> f.readline()
'contains three lines\n'

>>> f.readline()

Lastly, the readlines() method returns a list of remaining lines of the entire file. All
these reading methods return empty values when the end of the file (EOF) is reached.

>>> f.readlines()
['This is my first file\n', 'This file\n', 'contains three lines\n']

8.6 Python File Methods

There are various methods available with the file object. Some of them have been used
in the above examples.

Here is the complete list of methods in text mode with a brief description:

27
Method Description

close() Closes an opened file. It does not affect if the file is already closed.

Separates the underlying binary buffer from the TextIOBase and


detach()
returns it.

flush() Flushes the write buffer of the file stream.

isatty() Returns True if the file stream is interactive.

Reads at most n characters from the file. Reads till the end of file if
read(n)
it is negative or None.

readable() Returns True if the file stream can be read from.

Reads and returns one line from the file. Reads in at most n bytes if
readline(n=-1)
specified.

Reads and returns a list of lines from the file. Reads in at most n
readlines(n=-1)
bytes/characters if specified.

Changes the file position to offset bytes, about from (start, current,
seek(offset,from=SEEK_SET)
end).

Resizes the file stream to size bytes. If the size is not specified,
truncate(size=None)
resizes to the current location.

writable() Returns True if the file stream can be written to.

Writes the string s to the file and returns the number of characters
write(s)
written.

writelines(lines) Writes a list of lines to the file.


28
CHAPTER 9

LIBRARIES

9.1 Numpy

NumPy is a Python package. It stands for 'Numerical Python'. It is a library consisting


of multidimensional array objects and a collection of routines for processing of array.

Numeric, the ancestor of NumPy, was developed by Jim Hugunin. Another package
Numarray was also developed, having some additional functionalities. In 2005,
Travis Oliphant created the NumPy package by incorporating the features of
Numarray into the Numeric package. There are many contributors to this open-
source project.

9.1.1Operations using NumPy


Using NumPy, a developer can perform the
following operations − • Mathematical and logical
operations on arrays.
• Fourier transforms and routines for shape manipulation.
• Operations related to linear algebra. NumPy has in-built functions for linear
algebra and random number generation.
9.1.2 Why Use NumPy?
In Python, we have lists that serve the purpose of arrays, but they are slow to process.

NumPy aims to provide an array object that is up to 50x faster than traditional Python
lists.

The array object in NumPy is called ndarray, it provides a lot of supporting functions
that make working with ndarray very easy.

Arrays are very frequently used in data science, where speed and resources are very
important.
29
9.2 Pandas
Pandas is an open-source Python library providing high-performance data
manipulation and analysis tools using its powerful data structures. The name Pandas
is derived from the word Panel Data – an Econometrics from Multidimensional data.

In 2008, developer Wes McKinney started developing pandas when in need of high
performance, flexible tool for analysis of data.

Before Pandas, Python was majorly used for data munging and preparation. It had
very little contribution to data analysis. Pandas solved this problem. Using Pandas,
we can accomplish five typical steps in the processing and analysis of data,
regardless of the origin of data — load, prepare, manipulate, model, and analyze.

Python with Pandas is used in a wide range of fields including academic and
commercial domains including finance, economics, statistics, analytics, etc.

9.2.1 Key Features of Pandas

• Fast and efficient DataFrame object with the default and customized indexing. •

Tools for loading data into in-memory data objects from different file formats. •

Label-based slicing, indexing, and subsetting of large data sets. • Columns from a

data structure can be deleted or inserted.

• Group by data for aggregation and transformations.

• High-performance merging and joining of data.

• Time Series functionality.


30

9.3 Matplotlib

9.3.1 Introduction

Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform
library for making 2D plots from data in arrays. Matplotlib is written in Python and makes use of NumPy, the
numerical mathematics extension of Python. It provides an object-oriented API that helps in embedding plots
in applications using Python GUI toolkits such as PyQt, WxPythonotTkinter. It can be used in Python and
IPython shells, Jupyter notebook, and web application servers also.

Matplotlib has a procedural interface named the Pylab, which is designed to resemble MATLAB, a
proprietary programming language developed by MathWorks. Matplotlib along with NumPy can be
considered as the open-source equivalent of MATLAB.

Matplotlib was originally written by John D. Hunter in 2003. The current stable version is 2.2.0 released in
January 2018.
31

9.4 Seaborn
9.4.1 Introduction
In the world of Analytics, the best way to get insights is by visualizing the data. Data
can be visualized by representing it as plots that are easy to understand, explore, and
grasp. Such data helps in drawing the attention of key elements.

To analyze a set of data using Python, we make use of Matplotlib, a widely


implemented 2D plotting library. Likewise, Seaborn is a visualization library in
Python. It is built on top of Matplotlib.

9.4.2 Seaborn Vs Matplotlib


It is summarized that if Matplotlib “tries to make easy things easy and hard things
possible”, Seaborn tries to make a well-defined set of hard things easy too.”

Seaborn helps resolve the two major problems faced by Matplotlib; the problems are

• Default Matplotlib parameters

• Working with data frames

As Seaborn compliments and extends Matplotlib, the learning curve is quite gradual.
If you know Matplotlib, you are already halfway through Seaborn.

9.4.3 Important Features of Seaborn


Seaborn is built on top of Python’s core visualization library Matplotlib. It is meant to
serve as a compliment and not a replacement. However, Seaborn comes with some
very important features. Let us see a few of them here. The features help in −

• Built-in themes for styling matplotlib graphics

• Visualizing univariate and bivariate data

• Fitting in and visualizing linear regression models

• Plotting statistical time-series data

• Seaborn works well with NumPy and Pandas data structures


• It comes with built-in themes for styling Matplotlib graphics

32
9.5 Plotly
9.5.1 Introduction
Plotly is a Montreal-based technical computing company involved in the
development of data analytics and visualization tools such as Dash and Chart Studio.
It has also developed open-source graphing Application Programming Interface
(API) libraries for Python, R, MATLAB, Javascript, and other computer
programming languages.

Some of the important features of Plotly are as follows −

• It produces interactive graphs.

• The graphs are stored in JavaScript Object Notation (JSON) data format so that
they can be read using scripts of other programming languages such as R,
Julia, MATLAB, etc.

• Graphs can be exported in various raster as well as vector image formats

9.5.2 Plotly Vs Matplotlib

Developers describe Matplotlib as "A plotting library for the Python programming
language". It is a Python 2D plotting library which produces publication quality
figures in a variety of hardcopy formats and interactive environments across
platforms. It can be used in Python scripts, the Python and IPython shells, the Jupyter
notebook, web application servers, and four graphical user interface toolkits. On the
other hand, Plotly is detailed as "The Web's fastest-growing charting libraries".
Plotly.js is the only open-source JavaScript library for data visualization in the
sciences and engineering. Open-source interfaces to Plotly.js are available for Python,
R, MATLAB, and React.
33

9.6 Tkinter
9.6.1 Introduction
Tkinter is the standard GUI library for Python. Python when combined with Tkinter
provides a fast and easy way to create GUI applications. Tkinter provides a powerful
object-oriented interface to the Tk GUI toolkit.

Creating a GUI application using Tkinter is an easy task. All you need to do is
perform the following steps −

• Import the Tkinter module.

• Create the GUI application main window.

• Add one or more of the above-mentioned widgets to the GUI application.

• Enter the main event loop to take action against each event triggered by the
user.

9.6.2 Standard attributes


Let us take a look at how some of their common attributes. such as sizes, colors, and
fonts are specified.
• Dimensions

• Colors

• Fonts

• Anchors

• Relief styles
• Bitmaps

• Cursors

9.6.3 Geometry Management


All Tkinter widgets have access to specific geometry management methods, which
have the purpose of organizing widgets throughout the parent widget area. Tkinter
exposes the following geometry manager classes: pack, grid, and place.
The pack() Method − This geometry manager organizes widgets in blocks before
placing them in the parent widget.
The grid() Method − This geometry manager organizes widgets in a table-like
structure in the parent widget.
The place() Method − This geometry manager organizes widgets by placing them in a
specific position in the parent widget.

34
Bibliography

Links

• https://www.geeksforgeeks.org/
• https://en.wikipedia.org/wiki/Python_(programming_language)
• https://www.google.com

•https://www.tutorialspoint.com/tutorialslibrary.ht
• https://www.python.org/
35

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy