0% found this document useful (0 votes)
7 views

Srijan Report of Python

Uploaded by

Srijan Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Srijan Report of Python

Uploaded by

Srijan Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

PYTHON FOR DATA SCIENCE

A
Practical Training Report
on
PYTHON LANGUAGE
Submitted in partial fulfillment for the award of degree of
BACHELOR OF TECHNOLOGY
In
Computer Science & Engineering

Coordinator: Submitted By:


Mr. Hemant Mittal Srijan Kumar
21EGJCS148

Submitted to:
Mr. Pradeep Jha
Head of Dept.
Department of Computer Science & Engineering
GLOBAL INSTITUTE OF TECHNOLOGY
JAIPUR (RAJASTHAN)-302022
SESSION: 2022-23

Session 2022-23 i
PYTHON FOR DATA SCIENCE

Certificate

Session 2022-23 ii
PYTHON FOR DATA SCIENCE

Acknowledgement

I take this opportunity to express my deep sense of gratitude to my coordinator Mr.


Hemant Mittal, Assistant Professor Department of Computer Science and Engineering,
Global Institute of Technology, Jaipur, for his valuable guidance and cooperation
throughout the Practical Training work. He provided constant encouragement and
unceasing enthusiasm at every stage of the Practical Training work.

We are grateful to our respected Dr. I. C. Sharma, Principal GIT for guiding us during
Practical Training period

We express our indebtedness to Mr. Pradeep Jha, Head of Department of Computer


Science and Engineering, Global Institute of Technology, Jaipur for providing me ample
support during my Practical Training period.

Without their support and timely guidance, the completion of our Practical Training
would have seemed a farfetched dream. In this respect we find ourselves lucky to have
mentors of such a great potential.

Place: GIT, Jaipur

SRIJAN KUMAR

21EGJCS148

B.Tech. III Semester, II Year, CSE

Session 2022-23 iii


PYTHON FOR DATA SCIENCE

Abstract

Python is a modern, easy-to-learn, object-oriented programming language. It has a


powerful set of built-in data types and easy-to-use control constructs. Since Python is an
interpreted language, it is most easily reviewed by simply looking at and describing
interactive sessions. It is used in vast number of applications due to the various standard
libraries that come along with it and its capacity to integrate with other languages and use
their features. Python can be used for scripting, web scraping, and creating data sets. It’s
popular in the scientific community for scientific computing; there are libraries that make
it easy to share academic code projects in Python. Python is a web programming
language, so it interfaces with the internet. It knows how to receive and send web requests
and talk to databases. This paper describes the main features of Python programming,
loops and control statements in python then discusses applications of Python
programming

Session 2022-23 iv
PYTHON FOR DATA SCIENCE

Table Of Contents

Certificate ..................................................................................................................................................... ii

Acknowledgement .................................................................................................................................... iii

Abstract ........................................................................................................................................................ iv

Table of Content......................................................................................................................................... v

List of Figures .............................................................................................................. viii

List of Tables ................................................................................................................. ix

Chapter 1. Introduction ............................................................................................ 1


1.1 Python ................................................................................................... 1
1.2 Scripting Language................................................................................ 1
1.3 Object Oriented Programming Language ............................................... 2
1.4 History .................................................................................................. 2
1.5 Behind the Scenes of Python ................................................................. 4
1.6 Characteristics of Python ....................................................................... 5
Chapter 2. Downloading and Installation of Python ................................................ 6
2.1 Downloading Python ........................................................................... 6
2.2 Installing Python .................................................................................. 8
2.3 Setup the PATH Variable ................................................................... 10
2.4 Running Python IDE .......................................................................... 11
2.5 Python Code Execution ...................................................................... 12
Chapter 3. Downloading and Installation of Python .............................................. 13
3.1 Data Types ......................................................................................... 13
3.2 Variables............................................................................................ 14
3.3 Strings ............................................................................................... 14
3.3.1 Creating a String ............................................ 15
3.4 Python Operators ............................................................................... 15
3.4.1 Arithmetic Operators ..................................... 16
3.4.2 Comparison Operators ................................... 16
Chapter 4. Basic Data Structure in Python ............................................................ 18
4.1 List .................................................................................................... 18

Session 2022-23 v
PYTHON FOR DATA SCIENCE

4.2 Tuples ................................................................................................ 18


4.3 Dictionary .......................................................................................... 18
4.4 Sets .................................................................................................... 19
Chapter 5. Tuples and Lists ..................................................................................... 20
5.1 Tuples ................................................................................................ 20
5.1.1 Accessing Values in Tuples ........................... 20
5.1.2 Basic Tuple Operations .................................. 20
5.1.3 Built-in Tuple Functions ............................... 21
5.2 Lists ................................................................................................... 22
5.2.1 Accessing Values in Lists .............................. 22
5.2.2 Basic Lists Operations ................................... 23
5.2.3 Built-in List Functions and methods .............. 24
Chapter 6. Loops and Conditional Statements ....................................................... 26
6.1 Loops ................................................................................................. 26
6.1.1 Loops Definition............................................ 26
6.1.2 Loops Examples ............................................ 27
6.2 Conditional Statement ........................................................................ 28
6.2.1 Conditional Statements Definition ................. 28
6.2.2 Conditional Statements Examples .................. 30
Chapter 7. Uses and Scope of Python ..................................................................... 31
7.1 Scope of Python ................................................................................. 31
7.2 What can we do with Python? ............................................................ 31
7.3 Who uses Python today? .................................................................... 32
7.4 Why do people use Python? ............................................................... 32
Chapter 8. Functions ............................................................................................... 33
8.1 Function Syntax ................................................................................. 33
8.2 Function Examples ............................................................................ 33
Chapter 9. File Handling.......................................................................................... 35
9.1 Working of open() function ................................................................ 35
9.2 Working of read() mode ..................................................................... 36
9.3 Creating a file using write() mode ...................................................... 36
9.4 Working of append() mode ................................................................ 37

Session 2022-23 vi
PYTHON FOR DATA SCIENCE

9.5 Using write along with with() function ............................................... 38


9.6 split() using file handling ................................................................... 38
Chapter 10. Classes and Objects.......................................................................... 39
10.1 Class ................................................................................................. 39
10.1.1 Class Definition Syntax ............................... 39
10.1.2 Object Definition Syntax ............................. 39
10.1.3 Some Points on Python Class....................... 39
10.1.4 Defining a Class .......................................... 40
10.2 Class Objects .................................................................................... 40
10.2.1 Defining a Object ........................................ 41
10.3 The Self ............................................................................................ 43
10.4 The __init__ method ......................................................................... 44
10.5 Class and Inheritance Variables......................................................... 44

Chapter 11. Conclusion ........................................................................................ 48

REFERENCES ............................................................................................................ 49

Session 2022-23 vii


PYTHON FOR DATA SCIENCE

List of Figures

Fig 1.1 Guido Van Rossum.............................................................................................. 3

Fig 1.2 Python Logo ........................................................................................................ 4

Fig 2.1 Python Website ................................................................................................... 6

Fig 2.2 Python Version .................................................................................................... 6

Fig 2.3 Download Button ................................................................................................ 7

Fig 2.4 File Selection for Windows ................................................................................. 7

Fig 2.5 Setup Permission ................................................................................................. 8

Fig 2.6 Python Installation ............................................................................................... 8

Fig 2.7 Adding to PATH ................................................................................................ 9

Fig 2.8 Setup Complete ................................................................................................... 9

Fig 2.9 System Properties .............................................................................................. 10

Fig 2.10 Adding PATH to environment Variables ........................................................ 11

Fig 2.11 IDLE Selection ................................................................................................ 11

Fig 2.12 Python IDLE Shell .......................................................................................... 12

Fig 2.13 Code Execution Process................................................................................... 12

Fig 6.1 Loop Concept ................................................................................................... 26

Fig 6.2 Conditional Statements Concept ........................................................................ 29

Fig 8.1 Function Example ............................................................................................. 34

Fig 10.1 Example of Object Parts .................................................................................. 41

Session 2022-23 viii


PYTHON FOR DATA SCIENCE

Fig 10.2 Example of Objects ......................................................................................... 41

List of Tables

Table.3.1 Python Operators ........................................................................................... 15

Table.3.2 Arithmetic Operators ..................................................................................... 16

Table.3.3 Comparison Operators ................................................................................... 16

Table.5.1 Basic Tuple Operations .................................................................................. 21

Table.5.2 Built-in Tuple Functions ................................................................................ 21

Table.5.3 Basic List Operations ..................................................................................... 23

Table.5.4 Built-in List Functions ................................................................................... 24

Table.5.5 Built-in List Methods ..................................................................................... 24

Table.6.1 Types of Loop Statements .............................................................................. 27

Table.6.2 Types of Conditional Statements .................................................................... 29

Session 2022-23 ix
PYTHON FOR DATA SCIENCE

Chapter - 1

Introduction

1.1 Python
Python is a widely used high-level, general-purpose, interpreted, dynamic programming
language. Its design philosophy emphasizes code readability, and its syntax allows
programmers to express concepts in fewer lines of code than would be possible in
languages such as C++ or Java. The language provides constructs intended to enable clear
programs on both a small and large scale.

Python supports multiple programming paradigms, including object-oriented, imperative


and functional programming or procedural styles. It features a dynamic type system and
automatic memory management and has a large and comprehensive standard library.
Python interpreters are available for installation on many operating systems, allowing
Python code execution on a wide variety of systems.

1.2 Scripting Language

A scripting or script language is a programming language that supports scripts, programs


written for a special run-time environment that automate the execution of tasks that could
alternatively be executed one-by-one by a human operator.

Scripting languages are often interpreted (rather than compiled). Primitives are usually
the elementary tasks or API calls, and the language allows them to be combined into more
complex programs. Environments that can be automated through scripting include
software applications, web pages within a web browser, the shells of operating systems
(OS), embedded systems, as well as numerous games.

Session 2022-23 Page |1


PYTHON FOR DATA SCIENCE

A scripting language can be viewed as a domain-specific language for a particular


environment; in the case of scripting an application, this is also known as an extension
language. Scripting languages are also sometimes referred to as very high-level
programming languages, as they operate at a high level of abstraction, or as control
languages.

1.3 Object Oriented Programming Language

Object-oriented programming (OOP) is a programming paradigm based on the concept of


"objects", which may contain data, in the form of fields, often known as attributes; and
code, in the form of procedures, often known as methods. A distinguishing feature of
objects is that an object's procedures can access and often modify the data fields of the
object with which they are associated (objects have a notion of "this" or "self").

In OO programming, computer programs are designed by making them out of objects that
interact with one another. There is significant diversity in object oriented programming,
but most popular languages are class-based, meaning that objects are instances of classes,
which typically also determines their type.

1.4 History

Python was conceived in the late 1980s, and its implementation was started in December
1989 by Guido van Rossum at CWI in the Netherlands as a successor to the ABC
language (itself inspired by SETL) capable of exception handling and interfacing with the
Amoeba operating system. Van Rossum is Python's principal author, and his continuing
central role in deciding the direction of Python is reflected in the title given to him by the
Python community, benevolent dictator for life (BDFL).

Session 2022-23 Page |2


PYTHON FOR DATA SCIENCE

Fig. 1.1 Guido Van Rossum

“Python is an experiment in how much freedom programmers need. Too


much freedom and nobody can read another's code; too little and
expressiveness is endangered.”

- Guido van Rossum

1.5 Behind the Scenes of Python

About the origin of Python, Van Rossum wrote in 1996:

Over six years ago, in December 1989, I was looking for a "hobby" programming project
that would keep me occupied during the week around Christmas. My office ... would be
closed, but I had a home Computer, and not much else on my hands. I decided to write an
interpreter for the new scripting language I had been thinking about lately: a descendant
of ABC that would appeal to Unix/C hackers. I chose Python as a working title for the
project, being in a slightly irreverent mood (and a big fan of Monty Python's Flying
Circus).

Session 2022-23 Page |3


PYTHON FOR DATA SCIENCE

Fig. 1.2 Python Logo

Session 2022-23 Page |4


PYTHON FOR DATA SCIENCE

1.6 Characteristics of Python

 Easy to use.

 Free and Open Source.

 Clean, easy to read syntax.

 High Level.

 Dynamically Typed.

 Extensible.

 Portable.

 Third party utilities (e.g. Numeric, NumPy, SciPy)

 Interactive Programming Language.

Session 2022-23 Page |5


PYTHON FOR DATA SCIENCE

Chapter – 2

Downloading and Installation Of Python

2.1 Downloading Python

If you don’t already have a copy of Python installed on your computer, you will need to
open up your Internet browser and go to the Python download page
(http://www.python.org/download/).

Fig. 2.1 Python Website

Now that you are on the download page, select which of the software builds you would
like to download. For the purposes of this article we will use the most up to date version
available (Python 3.4.1).

Fig. 2.2 Python Version

Session 2022-23 Page |6


PYTHON FOR DATA SCIENCE

Once you have clicked on that, you will be taken to a page with a description of all the
new updates and features of 3.4.1, however, you can always read that while the download
is in process. Scroll to the bottom of the page till you find the “Download” section and
click on the link that says “download page.”

Fig. 2.3 Download Button

Now you will scroll all the way to the bottom of the page and find the “Windows x86
MSI installer.” If you want to download the 86-64 bit MSI, feel free to do so. We believe
that even if you have a 64-bit operating system installed on your computer, the 86-bit
MSI is preferable. We say this because it will still run well and sometimes, with the 64-
bit architectures, some of the compiled binaries and Python libraries don’t work well.

Fig. 2.4 File Selection for Windows

Session 2022-23 Page |7


PYTHON FOR DATA SCIENCE

2.2 Installing Python

Once you have downloaded the Python MSI, simply navigate to the download location on
your computer, double clicking the file and pressing Run when the dialog box pops up.

Fig. 2.5 Setup Permission

If you are the only person who uses your computer, simply leave the “Install for all users”
option selected. If you have multiple accounts on your PC and don’t want to install it
across all accounts, select the “Install just for me” option then press “Next.”

Fig. 2.6 Python Installation

Session 2022-23 Page |8


PYTHON FOR DATA SCIENCE

If you want to change the install location, feel free to do so; however, it is best to leave it
as is and simply select next, Otherwise...

Scroll down in the window and find the “Add Python.exe to Path” and click on the small
red “x.” Choose the “Will be installed on local hard drive” option then press “Next.”

Fig. 2.7 Adding to PATH

Now that you have completed the installation process, click on “Finish.

Fig. 2.8 Setup Complete

Session 2022-23 Page |9


PYTHON FOR DATA SCIENCE

2.3 Setup the PATH Variable

Begin by opening the start menu and typing in “environment” and select the option called
“Edit the system environment variables.”

When the “System Properties” window appears, click on “Environment Variables…”

Once you have the “Environment Variables” window open, direct your focus to the
bottom half. You will notice that it controls all the “System Variables” rather than just
this associated with your user. Click on “New…” to create a new variable for Python.

Fig. 2.9 System Properties

Simply enter a name for your Path and the code shown below. For the purposes of this
example we have installed Python 2.7.3, so we will call the path: “Pythonpath.” The
string that you will need to enter is: “C:\Python27\;C:\Python27\Scripts;”

Session 2022-23 P a g e | 10
PYTHON FOR DATA SCIENCE

Fig. 2.10 Adding PATH to Environment Variables

2.4 Running the Python IDE

Now that we have successfully completed the installation process and added our
“Environment Variable,” you are ready to create your first basic Python script. Let’s
begin by opening Python’s GUI by pressing “Start” and typing “Python” and selecting the
“IDLE (Python GUI).”

Fig. 2.11 IDLE Selection

Session 2022-23 P a g e | 11
PYTHON FOR DATA SCIENCE

Once the GUI is open, we will begin by using the simplest directive possible. This is the
“print” directive which simply prints whatever you tell it to, into a new line. Start by
typing a print directive like the one shown in the image below or copy and paste this text
then press

“Enter”: print (“Congratulations on executing your first print directive!”)

Fig. 2.12 Python IDLE Shell

2.5 Python Code Execution

Python’s traditional runtime execution model: source code you type is translated to byte
code, which is then run by the Python Virtual Machine. Your code is automatically
compiled, but then it is interpreted. Source code extension is .py. Byte code extension is
.pyc (compiled python code)

Fig. 2..13 Code Execution Process

Session 2022-23 P a g e | 12
PYTHON FOR DATA SCIENCE

Chapter – 3

Data Types and Operators

3.1 Data Types

Data types determine whether an object can do something, or whether it just would not
make sense. Other programming languages often determine whether an operation makes
sense for an object by making sure the object can never be stored somewhere where the
operation will be performed on the object (this type system is called static typing). Python
does not do that. Instead it stores the type of an object with the object, and checks when
the operation is performed whether that operation makes sense for that object.

Python has many native data types. Here are the important ones:

Booleans are either True or False.

Numbers can be integers (1 and 2), floats (1.1 and 1.2), fractions (1/2 and 2/3), or even
complex numbers.

Strings are sequences of Unicode characters, e.g. an HTML document.

Bytes and byte arrays, e.g. a JPEG image file.

Lists are ordered sequences of values.

Tuples are ordered, immutable sequences of values.

Sets are unordered bags of values.

Session 2022-23 P a g e | 13
PYTHON FOR DATA SCIENCE

3.2 Variables

Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.

Based on the data type of a variable, the interpreter allocates memory and decides what
can be stored in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals or characters in these variables.

Ex: counter = 100 # An integer assignment

miles = 1000.0 # A floating point

name = "John" # A string

3.3 Strings

In programming terms, we usually call text a string. When you think of a string as a
collection of letters, the term makes sense.

All the letters, numbers, and symbols in this book could be a string.

For that matter, your name could be a string, and so could your address.

 EXAMPLE:-

>>>”HELLO”

>>>”45678”

>>>”HEY Chad”

>>>”Python Language 101”

Session 2022-23 P a g e | 14
PYTHON FOR DATA SCIENCE

3.3.1 Creating a String

In Python, we create a string by putting quotes around text. For example, we could take
our otherwise useless.

• "hello"+"world" "helloworld" # concatenation

• "hello"*3 "hellohellohello" # repetition

• "hello"[0] "h" # indexing

• "hello"[-1] "o" # (from end)

• "hello"[1:4] "ell" # slicing

• len("hello") 5 # size

• "hello" < "jello" 1 # comparison

• "e" in "hello" 1 # search

3.4 Python Operators

TYPE NAME OPERATORS

Arithmetic Operator +,-,*,/,%,//,**

Comparison Operator <,>,==,!=,<=,>=

Table 3.1 Python Operators

Session 2022-23 P a g e | 15
PYTHON FOR DATA SCIENCE

3.4.1 Arithmetic Operator

Table 3.2 Arithmetic Operators

3.4.1 Comparison Operator

> Greater that - True if left operand is greater than the x > y
right

< Less that - True if left operand is less than the right x<y

Session 2022-23 P a g e | 16
PYTHON FOR DATA SCIENCE

== Equal to - True if both operands are equal x == y

!= Not equal to - True if operands are not equal x != y

>= Greater than or equal to - True if left operand is x >= y


greater than or equal to the right

<= Less than or equal to - True if left operand is less x <= y


than or equal to the right

Table 3.3 Comparison Operators

Session 2022-23 P a g e | 17
PYTHON FOR DATA SCIENCE

Chapter – 4

Basic Data Structure in Python

4.1 List

- Ordered collection of data.

- Supports Slicing and indexing same as strings.

- Mutable.

- E.g. : my_list = ['one', 'two','three',4,5]

4.2 Tuples

- Immutable in nature.

- No type restriction.

- Indexing and slicing, everything's same like that in strings and lists.

- E.g. : my_tuple = ("a", "b", “c")

4.3 Dictionaries

- Lists are sequences but the dictionaries are mappings.

- They are mappings between a unique key and a value pair.

- These mappings may not retain order.

- my_dictionary = {"key name": value}

Session 2022-23 P a g e | 18
PYTHON FOR DATA SCIENCE

4.4 Sets

- A set contains exclusive(unique) and unordered elements .

- We can construct a set by using a set() function.

- myset = {"a", "b", "c"}.

Session 2022-23 P a g e | 19
PYTHON FOR DATA SCIENCE

Chapter – 5

Tuples and Lists

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

5.1.1 Accessing Values in Tuple

To access values in tuple, use the square brackets for slicing along with the index or
indices to obtain 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 above code is executed, it produces the following result − tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]

5.1.2 Basic Tuple Operations

Tuples respond to the + and * operators much like strings; they mean concatenation and

repetition here too, except that the result is a new tuple, not a string. In fact, tuples

respond to all of the general sequence operations we used on strings in the prior chapter –

Session 2022-23 P a g e | 20
PYTHON FOR DATA SCIENCE

Table 5.1 Basic Tuple Operations

5.1.3 Built-in Tuple Functions


Python includes the following tuple functions –

Session 2022-23 P a g e | 21
PYTHON FOR DATA SCIENCE

Table 5.2 Built-in Tuple Functions

5.2 Lists

The list is a most versatile datatype available in Python which can be written as a list of
commaseparated values (items) between square brackets. Important thing about a list is
that items in a list need not be of the same type.

Creating a list is as simple as putting different comma-separated values between square


brackets. For example − list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];

Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so
on.

5.2.1 Accessing Values in Lists

To access values in lists, use the square brackets for slicing along with the index or
indices to obtain value available at that index.

For example –

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

list2 = [1, 2, 3, 4, 5, 6, 7 ];

print "list1[0]: ", list1[0] print "list2[1:5]: ", list2[1:5]

Output: list1[0]: physics list2[1:5]: [2, 3, 4, 5]

Update: list = ['physics', 'chemistry', 1997, 2000];

print "Value available at index 2 : "

print list[2]= 2001;

print "New value available at index 2 : "

print list[2]

Session 2022-23 P a g e | 22
PYTHON FOR DATA SCIENCE

Output: Value available at index 2 : 1997

New value available at index 2 : 2001

Delete: list1 = ['physics', 'chemistry', 1997, 2000];

print list1 del list1[2];

print "After deleting value at index 2 : "

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

Output: After deleting value at index 2 : ['physics', 'chemistry', 2000]

5.2.2 Basic List Operations

Table 5.3 Basic List Operations

Session 2022-23 P a g e | 23
PYTHON FOR DATA SCIENCE

5.2.3 Built-in List Function & Methods

Table 5.4 Built-in List Functions

Python includes following list methods

Session 2022-23 P a g e | 24
PYTHON FOR DATA SCIENCE

Table 5.5 Built-in Tuple Methods

Session 2022-23 P a g e | 25
PYTHON FOR DATA SCIENCE

Chapter – 6

Loops and Conditional Statements

6.1 Loops

6.1.1 Loops Definition

Programming languages provide various control structures that allow for more
complicated execution paths

. A loop statement allows us to execute a statement or group of statements multiple


times. The following diagram illustrates a loop statement –

Fig. 6.1 Loop Concept

Session 2022-23 P a g e | 26
PYTHON FOR DATA SCIENCE

Python programming language provides following types of loops to handle


looping requirements.

. Table 6.1 Types of Loops

6.1.2 Loops Example

For Loop:

>>> for mynum in [1, 2, 3, 4, 5]:

print ("Hello", mynum )

Hello 1

Hello 2

Hello 3

Hello 4

Hello 5

Session 2022-23 P a g e | 27
PYTHON FOR DATA SCIENCE

While Loop:

>>> count = 0

>>while(count< 4):

print 'The count is:', count

count = count + 1

The count is: 0

The count is: 1

The count is: 2

The count is: 3

6.2 Conditional Statements

6.2.1 Conditional Statement Definition

Decision making is anticipation of conditions occurring while execution of the program


and specifying actions taken according to the conditions.

Decision structures evaluate multiple expressions which produce TRUE or FALSE as


outcome. You need to determine which action to take and which statements to execute if
outcome is TRUE or FALSE otherwise.

Session 2022-23 P a g e | 28
PYTHON FOR DATA SCIENCE

Fig. 6.2 Conditional Statements Concept

Python programming language provides following types of decision making statements.


Click the following links to check their detail.

Table 6.2 Types of Conditional Statements

Session 2022-23 P a g e | 29
PYTHON FOR DATA SCIENCE

6.2.1 Conditional Statement Examples

If Statement:

a=33

b=200

If b>a:

print(“b”)

If...Else Statement:

a=200

b=33

if b>a:

print(“b is greater than a”)

else:

print(“a is greater than b”)

Session 2022-23 P a g e | 30
PYTHON FOR DATA SCIENCE

Chapter – 7

Uses and Scope of Python

7.1 Scope Of Python

 Science

- Bioinformatics

 System Administration

- Unix

- Web Logic

- Web Sphere

 Web Application Development

-CGI

 Testing Scripts

7.2 What can we do with Python?

 Web development

 Software development

 Scientific and Numeric Applications

 Game Development

 AI and ML

 Desktop GUI

Session 2022-23 P a g e | 31
PYTHON FOR DATA SCIENCE

 Operating Systems

7.3 Who uses Python today?

• Python is being applied in real revenue-generating products by real companies.

• Google makes extensive use of Python in its web search system, and employs Python’s
creator.

• Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for hardware
testing.

• ESRI uses Python as an end-user customization tool for its popular GIS mapping
products.

7.4 Why do people use Python?

• The YouTube video sharing service is largely written in Python.

• Python is object-oriented o Structure supports such concepts as polymorphism,


operation overloading, and multiple inheritance.

• Indentation o Indentation is one of the greatest future in Python.

• It's free (open source) o Downloading and installing Python is free and easy o Source
code is easily accessible

• It's powerful o Dynamic typing o Built-in types and tools o Library utilities

o Third party utilities (e.g. Numeric, NumPy, SciPy) o Automatic memory


management

• It's portable o Python runs virtually every major platform used today o As long as you
have a compatible Python interpreter installed, Python programs will run in exactly the
same manner, irrespective of platform.

Session 2022-23 P a g e | 32
PYTHON FOR DATA SCIENCE

Chapter – 8

Functions

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

8.1 Function Syntax

def functionname( parameters ):


"function_docstring"
function_suite
return [expression]

8.1 Function Example

1.def printme( str ):


"This prints a passed string into this function"
print str
return

2.# Function definition is here


def printme( str ):
"This prints a passed string into this function"

Session 2022-23 P a g e | 33
PYTHON FOR DATA SCIENCE

print str
return;

# Now you can call printme function


printme("I'm first call to user defined function!")
printme("Again second call to the same function")

Fig. 8.1 Function Example

Session 2022-23 P a g e | 34
PYTHON FOR DATA SCIENCE

Chapter – 9

File Handling

Python too supports file handling and allows users to handle files i.e., to read and write
files, along with many other file handling options, to operate on files. The concept of
file handling has stretched over various other languages, but the implementation is
either complicated or lengthy, but like other concepts of Python, this concept here is
also easy and short. Python treats files differently as text or binary and this is important.
Each line of code includes a sequence of characters and they form a text file. Each line
of a file is terminated with a special character, called the EOL or End of Line characters
like comma {,} or newline character. It ends the current line and tells the interpreter a
new one has begun. Let’s start with the reading and writing files.

9.1 Working of open() function

Before performing any operation on the file like reading or writing, first, we have to
open that file. For this, we should use Python’s inbuilt function open() but at the time of
opening, we have to specify the mode, which represents the purpose of the opening file.

f = open(filename, mode)

Where the following mode is supported:

1. r: open an existing file for a read operation.


2. w: open an existing file for a write operation. If the file already contains
some data then it will be overridden.
3. a: open an existing file for append operation. It won’t override existing data.
4. r+: To read and write data into the file. The previous data in the file will be
overridden.
5. w+: To write and read data. It will override existing data.
6. a+: To append and read data from the file. It won’t override existing data.

Session 2022-23 P a g e | 35
PYTHON FOR DATA SCIENCE

Take a look at the below example:


# a file named "geek", will be opened with the reading mode.
file = open('geek.txt', 'r')
# This will print every line one by one in the file
for each in file:
print (each)

The open command will open the file in the read mode and the for loop will print each
line present in the file.

9.2 Working of read() mode

There is more than one way to read a file in Python. If you need to extract a string that
contains all characters in the file then we can use file.read(). The full code would work
like this:

# Python code to illustrate read() mode


file = open("file.txt", "r")
print (file.read())

Another way to read a file is to call a certain number of characters like in the following
code the interpreter will read the first five characters of stored data and return it as a
string:

# Python code to illustrate read() mode character wise


file = open("file.txt", "r")
print (file.read(5))

9.3 Creating a file using write() mode

Let’s see how to create a file and how to write mode works, so in order to
manipulate the file, write the following in your Python environment:

Session 2022-23 P a g e | 36
PYTHON FOR DATA SCIENCE

# Python code to create a file


file = open('geek.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()

The close() command terminates all the resources in use and frees the
system of this particular program.

9.4 Working of append() mode

Let us see how the append mode works:

# Python code to illustrate append() mode


file = open('geek.txt','a')
file.write("This will add this line")
file.close()

There are also various other commands in file handling that is used to handle various tasks
like:

rstrip(): This function strips each line of a file off spaces from the right-hand side.

lstrip(): This function strips each line of a file off spaces from the left-hand side.

It is designed to provide much cleaner syntax and exception handling when you are
working with code. That explains why it’s good practice to use them with a statement
where applicable. This is helpful because using this method any files opened will be closed
automatically after one is done, so auto-cleanup.

Example:

# Python code to illustrate with()


with open("file.txt") as file:

Session 2022-23 P a g e | 37
PYTHON FOR DATA SCIENCE

data = file.read()
# do something with data

9.5 Using write along with the with() function

We can also use the write function along with the with() function:

# Python code to illustrate with() alongwith write()


with open("file.txt", "w") as f:
f.write("Hello World!!!")

9.6 split() using file handling

We can also split lines using file handling in Python. This splits the variable when space is
encountered. You can also split using any characters as we wish. Here is the code:

# Python code to illustrate split() function


with open("file.text", "r") as file:
data = file.readlines()
for line in data:
word = line.split()
print (word)

Session 2022-23 P a g e | 38
PYTHON FOR DATA SCIENCE

Chapter – 10

Classes and Objects

10.1 Class

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.

To understand the need for creating a class in Python let’s consider an example, let’s say
you wanted to track the number of dogs that may have different attributes like breed, age. If
a list is used, the first element could be the dog’s breed while the second element could
represent its age. Let’s suppose there are 100 different dogs, 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.
10.1.1 Class Definition Syntax:

class ClassName:
# Statement

10.1.2 Object Definition Syntax:


obj = ClassName()
print(obj.atrr)
Class creates a user-defined data structure, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class. A class is
like a blueprint for an object.

10.1.3 Some points on Python class:


 Classes are created by keyword class.
 Attributes are the variables that belong to a class.

Session 2022-23 P a g e | 39
PYTHON FOR DATA SCIENCE

 Attributes are always public and can be accessed using the dot (.) operator. Eg.:
Myclass.Myattribute
10.1.4 Defining a class

# Python3 program to

# demonstrate defining

# a class

class Dog:

pass

In the above example, the class keyword indicates that you are creating a class followed by
the name of the class (Dog in this case).

10.2 Class Objects

An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of


the class with actual values. It’s not an idea anymore, it’s an actual dog, like a dog of breed
pug who’s seven years old. You can have many dogs to create many different instances, but
without the class as a guide, you would be lost, not knowing what information is required.
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.

Session 2022-23 P a g e | 40
PYTHON FOR DATA SCIENCE

Fig. 10.1 Example of Object Parts

10.2.1 Declaring Objects

When an object of a class is created, the class is said to be instantiated. All the instances
share the attributes and the behavior of the class. But the values of those attributes, i.e. the
state are unique for each object. A single class may have any number of instances.

Example:

Fig. 10.2 Example Of Objects

Declaring an object

# Python3 program to

Session 2022-23 P a g e | 41
PYTHON FOR DATA SCIENCE

# demonstrate instantiating

# a class

class Dog:

# A simple class

# attribute

attr1 = "mammal"

attr2 = "dog"

# A sample method

def fun(self):

print("I'm a", self.attr1)

print("I'm a", self.attr2)

# Driver code

# Object instantiation

Rodger = Dog()

Session 2022-23 P a g e | 42
PYTHON FOR DATA SCIENCE

# Accessing class attributes

# and method through objects

print(Rodger.attr1)

Rodger.fun()

Output:
mammal

I'm a mammal

I'm a dog

In the above example, an object is created which is basically a dog named


Rodger. This class only has two class attributes that tell us that Rodger is a
dog and a mammal.

10.3 The Self

 Class methods must have an extra first parameter in the method definition. We do not
give a value for this parameter when we call the method, Python provides it.
 If we have a method that takes no arguments, then we still have to have one argument.
 This is similar to this pointer in C++ and this reference in Java.
When we call a method of this object as myobject.method(arg1, arg2), this is automatically
converted by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self
is about.

Session 2022-23 P a g e | 43
PYTHON FOR DATA SCIENCE

10.4 The __init__ method

The __init__ method is similar to constructors in C++ and Java. Constructors are used to
initializing the object’s state. Like methods, a constructor also contains a collection of
statements(i.e. instructions) that are executed at the time of Object creation. It runs as soon
as an object of a class is instantiated. The method is useful to do any initialization you want
to do with your object.

# A Sample class with init method


class Person:

# init method or constructor


def __init__(self, name):
self.name = name

# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)

p = Person('Nikhil')
p.say_hi()

Output:
Hello, my name is Nikhil

10.5 Class and Instance variables

Instance variables are for data, unique to each instance and class variables are for
attributes and methods shared by all instances of the class. Instance variables are variables
whose value is assigned inside a constructor or method with self whereas class variables
are variables whose value is assigned in the class.

Session 2022-23 P a g e | 44
PYTHON FOR DATA SCIENCE

Defining instance variables using a constructor.

# Python3 program to show that the variables with a value


# assigned in the class declaration, are class variables and
# variables inside methods and constructors are instance
# variables.

# Class for Dog

class Dog:

# Class Variable
animal = 'dog'

# The init method or constructor


def __init__(self, breed, color):

# Instance Variable
self.breed = breed
self.color = color

# Objects of Dog class


Rodger = Dog("Pug", "brown")
Buzo = Dog("Bulldog", "black")

print('Rodger details:')
print('Rodger is a', Rodger.animal)
print('Breed: ', Rodger.breed)
print('Color: ', Rodger.color)

Session 2022-23 P a g e | 45
PYTHON FOR DATA SCIENCE

print('\nBuzo details:')
print('Buzo is a', Buzo.animal)
print('Breed: ', Buzo.breed)
print('Color: ', Buzo.color)

# Class variables can be accessed using class


# name also
print("\nAccessing class variable using class name")
print(Dog.animal)

Output:
Rodger details:

Rodger is a dog

Breed: Pug

Color: brown

Buzo details:

Buzo is a dog

Breed: Bulldog

Color: black

Accessing class variable using class name

dog

Defining instance variables using the normal method.

# Python3 program to show that we can create


# instance variables inside methods

Session 2022-23 P a g e | 46
PYTHON FOR DATA SCIENCE

# Class for Dog

class Dog:

# Class Variable
animal = 'dog'

# The init method or constructor


def __init__(self, breed):

# Instance Variable
self.breed = breed

# Adds an instance variable


def setColor(self, color):
self.color = color

# Retrieves instance variable


def getColor(self):
return self.color

# Driver Code
Rodger = Dog("pug")
Rodger.setColor("brown")
print(Rodger.getColor())

Output:
brown

Chapter – 11

Session 2022-23 P a g e | 47
PYTHON FOR DATA SCIENCE

Conclusion

I believe the trial has shown conclusively that it is both possible and desirable to use Python
as the principal teaching language:

o It is Free (as in both cost and source code).

o It is trivial to install on a Windows PC allowing students to take their interest


further. For many the hurdle of installing a Pascal or C compiler on a Windows
machine is either too expensive or too complicated;

o It is a flexible tool that allows both the teaching of traditional procedural


programming and modern OOP; It can be used to teach a large number of
transferable skills;

o It is a real-world programming language that can be and is used in academia and


the commercial world;

o It appears to be quicker to learn and, in combination with its many libraries, this
offers the possibility of more rapid student development allowing the course to be
made more challenging and varied;

and most importantly, its clean syntax offers increased understanding and enjoyment for
student

Session 2022-23 P a g e | 48
PYTHON FOR DATA SCIENCE

References

1. www.python.org
2. www.geeksforgeeks.org
3. www.scribd.com
4. “GETTING STARTED WITH PYTHON” By Sumita Arora
5. www.slideshare.net

Session 2022-23 P a g e | 49

You might also like