0% found this document useful (0 votes)
8 views183 pages

Python

The document provides an introduction to Python programming, covering its history, characteristics, language features, and applications. It discusses Python's syntax, data types, control statements, functions, and the use of comments, as well as the differences between Python and Java. Additionally, it outlines the concepts of tokens, keywords, identifiers, and literals in Python.

Uploaded by

Showkath Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views183 pages

Python

The document provides an introduction to Python programming, covering its history, characteristics, language features, and applications. It discusses Python's syntax, data types, control statements, functions, and the use of comments, as well as the differences between Python and Java. Additionally, it outlines the concepts of tokens, keywords, identifiers, and literals in Python.

Uploaded by

Showkath Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R

PG Department of CS
Arasu College of Arts & Science for Women, Karur

UNIT – 1 INTRODUCTION TO PYTHON


Introduction – Python overview – Getting started – Comments – Python identifiers – Reserved
keywords – Variables – Standard data types – Operators – Statements and Expressions – String
operations – Boolean expressions. Control Statements: The for loop – while statement – if-elif-else
statement – Input from keyboard. Functions: Introduction – Built-in functions – User defined
functions – Function Definition – Function Call - Type conversion – Type coercion – Python
recursive function.

Introduction:

• General-purpose Object-Oriented Programming language.


• High-level language
• Developed in late 1980 by Guido van Rossum at National Research Institute for
Mathematics and Computer Science in the Netherlands.
• It is derived from programming languages such as ABC, Modula 3, small talk, Algol-68.
• It is Open-Source Scripting language.
• It is Case-sensitive language (Difference between uppercase and lowercase letters).
• One of the official languages at Google.

It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.

History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at the National
Research Institute for Mathematics and Computer Science in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk,
and Unix shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public
License (GPL).
Python is now maintained by a core development team at the institute, although Guido van Rossum still
holds a vital role in directing its progress.
Characteristics of Python
Following are important characteristics of Python Programming −

• It supports functional and structured programming methods as well as OOP.


• It can be used as a scripting language or can be compiled to byte-code for building large
applications.
• It provides very high-level dynamic data types and supports dynamic type checking.
• It supports automatic garbage collection.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

(or)

• Interpreted: Python source code is compiled to byte code as a .pyc file, and this byte
code can be interpreted by the interpreter.
• Interactive
• Object Oriented Programming Language
• Easy & Simple
• Portable
• Scalable: Provides improved structure for supporting large programs.
• Integrated
• Expressive Language
LANGUAGE FEATURES
Interpreted
• There are no separate compilation and execution steps like C and C++.
• Directly run the program from the source code.
• Internally, Python converts the source code into an intermediate form called bytecodes
which is then translated into native language of specific computer to run it.
• No need to worry about linking and loading with libraries, etc.
Platform Independent
• Python programs can be developed and executed on multiple operating system platforms.
• Python can be used on Linux, Windows, Macintosh, Solaris and many more.
• Free and Open Source; Redistributable
High-level Language
• In Python, no need to take care about low-level details such as managing the memory used
by the program.
Simple
• Closer to English language;Easy to Learn
• More emphasis on the solution to the problem rather than the syntax
Embeddable
• Python can be used within C/C++ program to give scripting capabilities for the program’s
users.
Robust
• Exceptional handling features
• Memory management techniques in built
Rich Library Support
• The Python Standard Library is very vast.
• Known as the “batteries included” philosophy of Python ;It can help do various things
involving regular expressions, documentation generation, unit testing, threading, databases,
web browsers, CGI, email, XML, HTML, WAV files, cryptography, GUI and many more.
• Besides the standard library, there are various other high-quality libraries such as the Python
Imaging Library which is an amazingly simple image manipulation library.
Applications of Python
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

• Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This
allows the student to pick up the language quickly.
• Easy-to-read − Python code is more clearly defined and visible to the eyes.
• Easy-to-maintain − Python's source code is fairly easy-to-maintain.
• A broad standard library − Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
• Interactive Mode − Python has support for an interactive mode which allows interactive testing
and debugging of snippets of code.
• Portable − Python can run on a wide variety of hardware platforms and has the same interface on
all platforms.
• Extendable − You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
• Databases − Python provides interfaces to all major commercial databases.
• GUI Programming − Python supports GUI applications that can be created and ported to many
system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X
Window system of Unix.
• Scalable − Python provides a better structure and support for large programs than shell scripting.

Pros
1. Ease of use
2. Multi-paradigm Approach
Cons
1. Slow speed of execution compared to C,C++
2. Absence from mobile computing and browsers
3. For the C,C++ programmers switching to python can be irritating as the language requires
proper indentation of code. Certain variable names commonly used like sum are functions in
python. So C, C++ programmers have to look out for these.

Python vs JAVA
Python Java

Dynamically Typed
Statically Typed
• All variable names (along with their types)
• No need to declare anything. An
must be explicitly declared. Attempting to
assignment statement binds a
assign an object of the wrong type to a
name to an object, and the
variable name triggers a type exception.
object can be of any type.
• Type casting is required when using
• No type casting is required
container objects.
when using container objects

Concise Express much in limited words Verbose Contains more words

Compact Less Compact


Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Python Java

Uses Indentation for structuring code Uses braces for structuring code

Python Getting Started

Many PCs and Macs will have python already installed.

To check if we have python installed on a Windows PC, search in the start bar for Python or run
the following on the Command Line ([Link]):

C:\Users\Your Name>python --version

Python Interpreter:
Names of some Python interpreters are:
▪ PyCharm
▪ Python IDLE
▪ The Python Bundle
▪ pyGUI
▪ Sublime Text etc.
There are two modes to use the python interpreter:
i. Interactive Mode
ii. Script Mode

Interactive Mode: Without passing python script file to the interpreter, directlyexecute code to
Python (Command line).
Example:
>>>6+3

Output: 9
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Note:>>> is a command the python interpreter uses to indicate that it is ready. Theinteractive mode
is better when a programmer deals with small pieces of code.
To run a python file on command line:
exec(open(“C:\Python33\python programs\[Link]”).read( ))

Script Mode:In this mode source code is stored in a file with the .py extension and use the interpreter
to execute the contents of the file. To execute the script by the interpreter, you have to tell the
interpreter the name of the file.
Example:
if you have a file name [Link] , to run the script you have to follow the followingsteps:
Step-1: Open the text editor i.e. Notepad
Step-2: Write the python code and save the file with .py file extension. (Defaultdirectory is
C:\Python33/[Link])
Step-3: Open IDLE ( Python GUI) python shell
Step-4: Click on file menu and select the open option
Step-5: Select the existing python file
Step-6: Now a window of python file will be opened
Step-7: Click on Run menu and the option Run Module.
Step-8: Output will be displayed on python shell window.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Fig. : IDLE (Python GUI)

Fig: Python Shell


Python – Comments
Python comments are programmer-readable explanation or annotations in the Python source code.
They are added with the purpose of making the source code easier for humans to understand, and are
ignored by Python interpreter

• Comments can be used to explain Python code.


• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing code.
There are three types of comments available in Python
• Single line Comments
• Multiline Comments
• Docstring Comments

Example
Following is an example of a single line comment in Python:
# This is a single line comment in python
print ("Hello, World!")
This produces the following result −
Hello, World!
Multi-Line comment: Multiline comments can be written in more than one lines. Triple quoted ‘ ’ ’
or “ ” ”) multi-line comments may be used in python. It is also known as docstring.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Example:
‘’’ This program will calculate the average of 10 values.
First find the sum of 10 values
and divide the sum by number of values
‘’’
Docstring Comments
Python docstrings provide a convenient way to provide a help documentation with Python modules,
functions, classes, and methods. The docstring is then made available via the __doc__ attribute.

def add(a, b):


"""Function to add the value of a and b"""
return a+b
print(add.__doc__)

Function to add the value of a and b


Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Difference Between ‘Docstrings’ and ‘Multi-line Comments


Docstrings and Multi-line comments may look the same but they aren’t.
• Docstrings are written in the functions and classes to show how to use the program.
• Multi-line comments are used to show how a block of code works.

Python Character Set :

It is a set of valid characters that a language recognize.


• Letters: A-Z, a-z
• Digits : 0-9
• Special Symbols
• Whitespace

TOKENS
Token: Smallest individual unit in a program is known as [Link] are five types of token in
python:
• Keywords
• Identifiers
• Literals
• Operators
• Punctuators
Keywords
Keywords in Python are reserved words that can not be used as a variable name, function
name, or any other identifier.
Python contains thirty-five keywords in the most recent version, i.e., Python 3.8. Here we have
shown a complete list of Python keywords for the reader's reference.

False Await else import pass

None Break except in raise

True Class finally is return

and Continue for lambda try

as Def from nonlocal while

assert Del global not with

async Elif if or yield


Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

All the keywords are in lowercase except 03 keywords (True, False, None).

Code

# Python program to demonstrate the application of iskeyword()


# importing keyword library which has lists
import keyword
# displaying the complete list using "kwlist()."
print("The set of keywords in this version is: ")
print( [Link] )
Output:
The set of keywords in this version is :
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else',
'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise',
'return', 'try', 'while', 'with', 'yield']

True and False are those keywords that can be allocated to variables or parameters and are compared
directly.

Code
print( 4 == 4 )
print( 6 > 9 )
print( True or False )
print( 9 <= 28 )
print( 6 > 9 )
print( True and False )
Output:
True
False
True
True
False
False
The None Keyword
None is a Python keyword that means "nothing." None is known as nil, null, or undefined in
different computer languages.
If a function does not have a return clause, it will give None as the default output:

Code
print( None == 0 )
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

print( None == " " )


print( None == False )
A = None
B = None
print( A == B )
Output:
False
False
False
True
Identifier:
The name given by the user to the entities like variable name, class-name,function-
name etc.

Rules for identifiers:


• It can be a combination of letters in lowercase (a to z) or uppercase (A to Z) ordigits (0
to 9) or an underscore.
• It cannot start with a digit.
• Keywords cannot be used as an identifier.
• We cannot use special symbols like !, @, #, $, %, + etc. in identifier.
• _ (underscore) can be used in identifier.
• Commas or blank spaces are not allowed within an identifier.

Literal:
Literals are the constant value. Literals can be defined as a data that is given ina variable
or constant.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Literal

Numeric String Boolean Special Literal


Collections

int float complex

True False None

Numeric literals: Numeric Literals are immutable.


Eg.
5,6.7,6+9j
String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single as
well as double quotes for a String.

Eg:
"Aman" , '12345'
Escape sequence characters:

\\ Backslash

\’ Single quote

\” Double quote

\a ASCII Bell

\b Backspace

\f ASCII Formfeed
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

\n New line charater

\t Horizontal tab

Boolean literal: A Boolean literal can have any of the two values: True or False.
Special literals: Python contains one special literal [Link].
None is used to specify to that field that is not created. It is also used for end of lists inPython.
Literal Collections: Collections such as tuples, lists and Dictionary are used in Python.
Operators:
An operator performs the operation on operands. Basically there are twotypes of
operators in python according to number of operands:
• Unary Operator
• Binary Operator
Unary Operator: Performs the operation on one operand.
Example:
+ Unary plus
- Unary minus
~ Bitwise
complementnot
Logical
negation

Binary Operator: Performs operation on two operands.


Separator or punctuator : , ; , ( ), { }, [ ]
Basic terms of a Python Programs:

• Blocks and Indentation


• Statements
• Expressions
• Comments

Blocks and Indentation


• Python provides no braces to indicate blocks of code for class and function definition or
flow control.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

• Maximum line length should be maximum 79 characters.

• Blocks of code are denoted by line indentation, which is rigidly enforced.

• The number of spaces in the indentation is variable, but all statements within the block
must be indented the same amount.

for example –
if True:
print(“True”)
else:
print(“False”)

Statements
A line which has the instructions or expressions.

Expressions:
A legal combination of symbols and values that produce a result. Generally it produces a value.
Comments:
Comments are not executed. Comments explain a program and make a program
understandable and readable. All characters after the # and up to the end of the physical line are part of
the comment and the Python interpreter ignores them.

Mantissa and Exponent Form:

A real number in exponent form has two parts:

➢ Mantissa
➢ Exponent
Mantissa: It must be either an integer or a proper real constant.
Exponent: It must be an integer. Represented by a letter E or e followed by integer value.

Valid Exponent form Invalid Exponent form


123E05 2.3E (No digit specified for exponent)
1.23E07
0.24E3.2 (Exponent cannot have fractional part)
0.123E08
23,455E03 (No comma allowed)
123.0E08
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

123E+8

1230E04

-0.123E-3

163.E4

.34E-2

4.E3

Basic terms of a Python Programs:

• Blocks and Indentation


• Statements
• Expressions
• Comments

Blocks and Indentation

• Python provides no braces to indicate blocks of code for class and function definition
orflow control.

• Maximum line length should be maximum 79 characters.


• Blocks of code are denoted by line indentation, which is rigidly enforced.
• The number of spaces in the indentation is variable, but all statements within the
blockmust be indented the same amount.
Example
if True:
print(“True”)
else:
print(“False”)

Statements
A line which has the instructions or expressions.

Expressions
A legal combination of symbols and values that produce a result. Generally, it produces a value.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Comments
Comments are not executed. Comments explain a program and make a program
understandable and readable. All characters after the # and up to the end of the physical line are part
of the comment and the Python interpreter ignores them.

Multiple Statements on a Single Line

The semicolon (;) allows multiple statements on the single line given that neither statement
starts a new code block.
Example
x=5;
print(“Value =” x)
Variable/Label in Python

Definition: Named location that refers to a value and whose value can be used and processed
during program execution.
Variables in python do not have fixed locations. The location they refer to changes every timetheir
values change.
Creating a variable:

A variable is created the moment you first assign a value to

[Link]:

x=5

y = “hello”

Variables do not need to be declared with any particular type and can even change type after
they have been set. It is known as dynamic Typing.

x = 4 # x is of type int
x = "python" # x is now of type strprint(x)

Rules for Python variables:


• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscore (A-z, 0-
9,and _)
• Variable names are case-sensitive (age, Age and AGE are three different variables)
Python allows assign a single value to multiple variables.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Example x=y=z=5

You can also assign multiple values to multiple variables. For example −

x , y , z = 4, 5, “python”

4 is assigned to x, 5 is assigned to y and string “python” assigned to variable z respectively.


x=12
y=14
x,y=y,x
print(x,y)
Now the result will be14 12

Lvalue and Rvalue:


An expression has two values. Lvalue and Rvalue.

Lvalue: the LHS part of the expression

Rvalue: the RHS part of the expression

Python first evaluates the RHS expression and then assigns to [Link]:

p, q, r= 5, 10, 7

q, r, p = p+1, q+2, r-1

print (p,q,r)

Now the result will be:


6 6 12

Note: Expressions separated with commas are evaluated from left to right and assigned in sameorder.

If you want to know the type of variable, you can use type( ) function :

Syntax:
type (variable-name)

Example:

x=6

type(x)

The result will be:


Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

<class ‘int’>

• If you want to know the memory address or location of the object, you can use id( ) function.

Example:
>>>id(5)
1561184448
>>>b=5
>>>id(b)
1561184448

You can delete single or multiple variables by using del statement.

Example:del x
del y, z
• input ( prompt )
• raw_input ( prompt )
input (): This function first takes the input from the user and converts it into a string.
Python provides a built-in function called input which takes the input from the user.
Syntax:
inp = input('STATEMENT')
Example:
>>> name = input('What is your name?\n') # \n ---> newline ---> It causes a line break
>>> What is your name?
Ram
>>> print(name)
Ram

# ---> comment in python


Example 2:
name = input ('What is your name?\n') # \n ---> newline ---> It causes a line break
print(name)

Output:
What is your name?
Ram
Ram
Example
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

# Program to check input


# type in Python
num = input ("Enter number :")
print(num)
name1 = input("Enter name : ")
print(name1)
# Printing type of input value
print ("type of number", type(num))
print ("type of name", type(name1))

Output
Enter number :123
123
Enter name: This is my first program
This is my first program
type of number <class,’str’>
type of name <class,’str’>
raw_input(): This function works in older version (like Python 2.x). This function takes exactly what
is typed from the keyboard, converts it to string, and then returns it to the variable in which we want
to store it.

# Python program showing


# a use of raw_input()
g = raw_input("Enter your name : ")
print g

Enter your name : Vishnu priya

Vishnu Priya

Python | Output using print() function


Python print() function prints the message to the screen or any other standard output device.
name = "John"
age = 30
print("Name:", name)
print("Age:", age)

Name: John
Age: 30

Python print() Function Syntax


Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Syntax : print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)


Python print() Function with Examples

Python String Literals


String literals in Python’s print statement are primarily used to format or design how a specific
string appears when printed using the print() function.
• \n: This string literal is used to add a new blank line while printing a statement.
• “”: An empty quote (“”) is used to print an empty line

print("welcome \n to all.")

Output
welcome
to all.
Type Casting:
To convert one data type into another data type.

Casting in python is therefore done using constructor functions:

x = int(1) # x will be 1

y = int(2.8) # y will be 2

z = int("3") # z will be 3

float( ) - constructs a float number from an integer literal, a float literal or a string literal.

Example:

x = float(1) # x will be 1.0

y = float(2.8) # y will be 2.8

z = float("3") # z will be 3.0

w = float("4.2") # w will be 4.2

str( ) - constructs a string from a wide variety of data types, including strings, integerliterals and
float literals.

Example:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

x = str("s1") # x will be 's1'


y = str(2) # y will be '2'

z = str(3.0) # z will be '3.0'


OUTPUT using print( ) statement:
Syntax:
print(object, sep=<separator string >, end=<end-string>)

object: It can be one or multiple objects separated by comma.


sep: sep argument specifies the separator character or string. It separate the objects/items. Bydefault
sep argument adds space in between the items when printing.
end: It determines the end character that will be printed at the end of print line. By default it
has newline character( ‘\n’ ).
Example:
x=10

y=20

z=30
print(x,y,z, sep=’@’, end= ‘ ‘)
Output:

10@20@30
Data Types in Python

Python has Two data types –

1. Primitive Data Type (Numbers, String)


2. Collection Data Type (List, Tuple, Set, Dictionary)
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Data Types

Primitive Collection
Data Type Data Type

Number String

List Tuple Set Dictionary

int float complex

Primitive Data Types:

a. Numbers: Number data types store numeric values.


There are three numeric types in Python:

• int
• float
• complex

Example:
w=1 # int
y = 2.8 # float
z = 1j # complex
integer : There are two types of integers in python:

➢ int
➢ Boolean

➢ int: int or integer, is a whole number, positive or negative, without decimals.


Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Example:

x=1
y = 35656222554887711
z = -3255522
Boolean: It has two values: True and False. True has the value 1 and False has thevalue 0.
Example:

>>>bool(0)
False
>>>bool(1)
True
>>>bool(‘ ‘)
False
>>>bool(-34)
True
>>>bool(34)
True
Float : float or "floating point number" is a number, positive or negative, containing oneor more
decimals. Float can also be scientific numbers with an "e" to indicate the powerof 10.
Example:
x = 1.10
y = 1.0
z = -35.59
a = 35e3

b = 12E4
c = -87.7e100
Complex: Complex numbers are written with a "j" as the imaginary part.
Example:
>>>x = 3+5j
>>>y = 2+4j
>>>z=x+y
>>>print(z)5+9j
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

>>>z.real5.0

>>>z.imag9.0
Real and imaginary part of a number can be accessed through the attributes real and imag.
String: Sequence of characters represented in the quotation marks.

• Python allows for either pairs of single or double quotes. Example: 'hello' is the sameas
"hello" .
• Python does not have a character data type, a single character is simply a string with a
length of 1.
• The python string store Unicode characters.
• Each character in a string has its own index.
• String is immutable data type means it can never change its value in place

Collection Data Type:


• List
• Tuple
• Set
• Dictionary

MUTABLE & IMMUTABLE Data Type:


Mutable Data Type:
These are changeable. In the same memory address, new value can be stored.
Example: List, Set, Dictionary
Immutable Data Type:
These are unchangeable. In the same memory address new value cannot be [Link]:
integer, float, Boolean, string and tuple.

Python Operators
The operator is a symbol that performs a specific operation between two operands, according to
one definition.

Types of Python Operators


Python language supports the following types of operators.

• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

• Membership Operators
• Identity Operators

Python Arithmetic Operators


• Python arithmetic operators are used to perform mathematical operations on numerical values.
These operations are Addition, Subtraction, Multiplication, Division, Modulus, Exponents and
Floor Division.

Operator Name Example

+ Addition 10 + 20 = 30

- Subtraction 20 – 10 = 10

* Multiplication 10 * 20 = 200

/ Division 20 / 10 = 2

% Modulus 22 % 10 = 2

** Exponent 4**2 = 16

// Floor Division 9//2 = 4

Example
Following is an example which shows all the above operations:
a = 21
b = 10
# Addition
print ("a + b : ", a + b)
# Subtraction
print ("a - b : ", a - b)
# Multiplication
print ("a * b : ", a * b)
# Division
print ("a / b : ", a / b)
# Modulus
print ("a % b : ", a % b)
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

# Exponent
print ("a ** b : ", a ** b)

# Floor Division
print ("a // b : ", a // b)

This produce the following result −


a + b : 31
a - b : 11
a * b : 210
a / b : 2.1
a%b: 1
a ** b : 16679880978201
a // b : 2

Python Comparison Operators


Python comparison operators compare the values on either sides of them and decide the relation
among them. They are also called relational operators. These operators are equal, not equal, greater than,
less than, greater than or equal to and less than or equal to.

Operator Name Example

== Equal 4 == 5 is not true.

!= Not Equal 4 != 5 is true.

> Greater Than 4 > 5 is not true.

< Less Than 4 < 5 is true.

>= Greater than or Equal to 4 >= 5 is not true.

<= Less than or Equal to 4 <= 5 is true.

Example
Following is an example which shows all the above comparison operations:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

a=4
b=5
# Equal
print ("a == b : ", a == b)

# Not Equal
print ("a != b : ", a != b)
# Greater Than
print ("a > b : ", a > b)
# Less Than
print ("a < b : ", a < b)
# Greater Than or Equal to
print ("a >= b : ", a >= b)
# Less Than or Equal to
print ("a <= b : ", a <= b)

This produce the following result −


a == b : False
a != b : True
a > b : False
a < b : True
a >= b : False
a <= b : True
Python Assignment Operators
Python assignment operators are used to assign values to variables. These operators include simple
assignment operator, addition assign, subtraction assign, multiplication assign, division and assign
operators etc.

Operator Name Example

= Assignment Operator a = 10
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

+= Addition Assignment a += 5 (Same as a = a + 5)

-= Subtraction Assignment a -= 5 (Same as a = a - 5)

*= Multiplication Assignment a *= 5 (Same as a = a * 5)

/= Division Assignment a /= 5 (Same as a = a / 5)

%= Remainder Assignment a %= 5 (Same as a = a % 5)

**= Exponent Assignment a **= 2 (Same as a = a ** 2)

//= Floor Division Assignment a //= 3 (Same as a = a // 3)

Example
Following is an example which shows all the above assignment operations:

# Assignment Operator
a = 10
# Addition Assignment
a += 5
print ("a += 5 : ", a)
# Subtraction Assignment
a -= 5
print ("a -= 5 : ", a)
# Multiplication Assignment
a *= 5
print ("a *= 5 : ", a)
# Division Assignment
a /= 5
print ("a /= 5 : ",a)
# Remainder Assignment
a %= 3
print ("a %= 3 : ", a)
# Exponent Assignment
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

a **= 2
print ("a **= 2 : ", a)
# Floor Division Assignment
a //= 3
print ("a //= 3 : ", a)

This produce the following result −


a += 5 : 105
a -= 5 : 100
a *= 5 : 500
a /= 5 : 100.0
a %= 3 : 1.0
a **= 2 : 1.0
a //= 3 : 0.0
Python Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13;
Now in the binary format their values will be 0011 1100 and 0000 1101 respectively. Following table lists
out the bitwise operators supported by Python language with an example each in those, we use the above
two variables (a and b) as operands −
a = 0011 1100
b = 0000 1101
--------------------------
a&b = 12 (0000 1100)
a|b = 61 (0011 1101)
a^b = 49 (0011 0001)
~a = -61 (1100 0011)
a << 2 = 240 (1111 0000)
a>>2 = 15 (0000 1111)
There are following Bitwise operators supported by Python language

Operator Name Example


Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

& Binary AND Sets each bit to 1 if both bits are 1

| Binary OR Sets each bit to 1 if one of two bits is 1

^ Binary XOR Sets each bit to 1 if only one of two bits is 1

~ Binary Ones Complement Inverts all the bits

<< Binary Left Shift Shift left by pushing zeros in from the right and
let the leftmost bits fall off

>> Binary Right Shift Shift right by pushing copies of the leftmost bit
in from the left, and let the rightmost bits fall off

Example
Following is an example which shows all the above bitwise operations:
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
# Binary AND
c=a&b # 12 = 0000 1100
print ("a & b : ", c)
# Binary OR
c=a|b # 61 = 0011 1101
print ("a | b : ", c)
# Binary XOR
c=a^b # 49 = 0011 0001
print ("a ^ b : ", c)
# Binary Ones Complement
c = ~a; # -61 = 1100 0011
print ("~a : ", c)
# Binary Left Shift
c = a << 2; # 240 = 1111 0000
print ("a << 2 : ", c)
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

# Binary Right Shift


c = a >> 2; # 15 = 0000 1111
print ("a >> 2 : ", c)

This produce the following result −


a & b : 12
a | b : 61
a ^ b : 49
~a : -61
a >> 2 : 240
a >> 2 : 15
Python Logical Operators
There are following logical operators supported by Python language. Assume variable a holds 10
and variable b holds 20 then

Operator Description Example

and Logical If both the operands are true then condition becomes true. (a and b)
AND is true.

or Logical OR If any of the two operands are non-zero then condition becomes (a or b)
true. is true.

not Logical NOT Used to reverse the logical state of its operand. Not(a
and b) is
false.

Membership Operators

The membership of a value inside a Python data structure can be verified using Python
membership operators. The result is true if the value is in the data structure; otherwise, it returns false.

In If the first operand cannot be found in the second operand, it is evaluated to be true
(list, tuple, or dictionary).

not If the first operand is not present in the second operand, the evaluation is true (list,
in tuple, or dictionary).

Program Code:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Now we give code examples of Membership operators in Python. The code is given below -

x = ["Rose", "Lotus"]
print(' Is value Present?', "Rose" in x)
print(' Is value not Present?', "Riya" not in x)
Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output
is given below -
Is value Present? True
Is value not Present? True
Python Identity Operators
Identity operators compare the memory locations of two objects. There are two Identity operators
explained below −

Operator Description

Is If the references on both sides point to the same object, it is determined to be true.

is not If the references on both sides do not point at the same object, it is determined to be
true.

Program Code:

Now we give code examples of Identity operators in Python. The code is given below -

a = ["Rose", "Lotus"]
b = ["Rose", "Lotus"]
c=a
print(a is c)
print(a is not c)
print(a is b)
print(a is not b)
print(a == b)
print(a != b)
Output:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Now we compile the above code in python, and after successful compilation, we run it. Then the output
is given below -
True
False
False
True
True
False

Python Operators Precedence Example


The following table lists all operators from highest precedence to lowest.

Operator Description

** Exponentiation (raise to the power)

~+- Complement, unary plus and minus (method names for the last two are
+@ and -@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

>> << Right and left bitwise shift

& Bitwise 'AND'td>

^| 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

Operator precedence affects how an expression is evaluated.


For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than
+, so it first multiplies 3*2 and then adds into 7.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at
the bottom.
a = 20
b = 10
c = 15
d=5
e=0
e = (a + b) * c / d #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ", e
e = ((a + b) * c) / d # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ", e
e = (a + b) * (c / d); # (30) * (15/5)
print "Value of (a + b) * (c / d) is ", e
e = a + (b * c) / d; # 20 + (150/5)
print "Value of a + (b * c) / d is ", e
When you execute the above program, it produces the following result −

Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50

OR
Operator Precedence and Associativity:
Operator Precedence: It describes the order in which operations are performed when anexpression
is evaluated. Operators with higher precedence perform the operation first.
Operator Associativity: whenever two or more operators have the same precedence, then
associativity defines the order of operations.

Operator Description Associativity Preced


ence
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

( ), { } Parentheses (grouping) Left to Right


f(args…) Function call Left to Right
x[index:index] Slicing Left to Right
x[index] Subscription Left to Right
** Exponent Right to Left
~x Bitwise not Left to Right
+x, -x Positive, negative Left to Right
*, /, % Product, division, remainder Left to Right
+, – Addition, subtraction Left to Right
<<, >> Shifts left/right Left to Right
& Bitwise AND Left to Right
^ Bitwise XOR Left to Right
| Bitwise OR Left to Right
<=, <, >, >= Comparisons Left to Right
=, %=, /=, += Assignment
is, is not Identity
in, not in Membership
Not Boolean NOT Left to Right
And Boolean AND Left to Right
Or Boolean OR Left to Right
Lambda Lambda expression Left to Right

FLOW CONTROL
• Decision Making and branching (Conditional Statement)
• Looping or Iteration
• Jumping statements

DECISION MAKING & BRANCHING


Decision making is about deciding the order of execution of statements based on certain
conditions. Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome
There are three types of conditions in python:

1. if statement
2. if-else statement
3. elif statement
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

if statement:

It is a simple if statement. When condition is true, then code which isassociated with if statement
will execute.
Example:
a=40

b=20
if a>b:
print(“a is greater than b”)

if-else statement:
When the condition is true, then code associated with if statement willexecute, otherwise code
associated with else statement will execute.
Example:
a=10 b=20
if a>b:
print(“a is greater”)
else:
print(“b is greater”)

elif statement:

It is short form of else-if statement. If the previous conditions were not true,then do this
condition". It is also known as nested if statement.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Example:
a=input(“Enter first number”)

b=input("Enter Second Number:")


if a>b:
print("a is greater")

elif a==b:
print("both numbers are equal")
else:
print("b is greater")

LOOPS in PYTHON
Loop
Execute a set of statements repeatedly until a particular condition is satisfied.
There are two types of loops in python:

1. while loop
2. for loop

While loop:
With the while loop we can execute a set of statements as long as a condition istrue. It requires to
define an indexing variable.
Example:
To print table of number 2
i=2
while i<=20:
print(i)
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

i+=2

For loop
The for loop iterate over a given sequence (it may be list, tuple or string).
Note: The for loop does not require an indexing variable to set beforehand, as the for commanditself allows
for this.
primes = [2, 3, 5, 7]
for x in primes:

print(x)
The range( ) function:

it generates a list of numbers, which is generally used to iterate over with for loop.
range( ) function uses three types of parameters, which are:

• start: Starting number of the sequence.


• stop: Generate numbers up to, but not including last number.
• step: Difference between each number in the sequence. Python use range( ) function
in three ways:

• range(stop)
• range(start, stop)
• [Link](start, stop, step)

Note:

• All parameters must be integers.


• All parameters can be positive or negative.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

range(stop): By default, It starts from 0 and increments by 1 and ends up to stop,but not
including stop value.
Example:

for x in range(4):
print(x)

Output:

0
1
2
3

range(start, stop): It starts from the start value and up to stop, but not including stop
value.
Example:

for x in range(2, 6):


print(x)

Output:

2
3
4
5
Range (start, stop, step): Third parameter specifies to increment or decrement the value byadding or
subtracting the value.
Example:

for x in range(3, 8, 2):

print(x)

Output:

3
5
7
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Explanation of output: 3 is starting value, 8 is stop value and 2 is step value. First print 3 and
increase it by 2, that is 5, again increase is by 2, that is 7. The output can’t exceed stop-1 valuethat
is 8 here. So, the output is 3, 5, 8.
Difference between range( ) and xrange( ):

S.
range( ) xrange( )
No.
returns the generator object that can be usedto
1 returns the list of numbers display numbers only by looping
The variable storing the range takes more
2 memory variable storing the range takes less memory

all the operations that can be applied on operations associated to list


3 the list can be used on it cannot beapplied on it

4 slow implementation faster implementation

JUMP STATEMENTS:
There are two jump statements in python:

1. break
2. continue
Break statement

With the break statement we can stop the loop even if it is true.

Example
in while loop in for loop
i=1 languages = ["java", "python", "c++"]
while i for x in languages:
< 6: if x ==
print( "python":
i) if i break
== 3: print(x)
break
i += 1
Output: Output:
1 java
2
3

Note: If the break statement appears in a nested loop, then it will terminate the very loop it is in
i.e. if the break statement is inside the inner loop then it will terminate the inner loop only and
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

the outer loop will continue as it is.


Continue statement: With the continue statement we can stop the current iteration, and
continue with the next iteration.
Example
in while loop in for loop
i=0 languages = ["java", "python", "c++"]for x in
while i < 6:i languages:
+= 1 if x == "python":
if i == 3: continue
continue print(x)
print(i)

Output: Output:
1 java c++
2
4
5
6

Loop else statement

The else statement of a python loop executes when the loop terminates normally. The else
statement of the loop will not execute when the break statement terminates the loop.
The else clause of a loop appears at the same indentation as that of the loop keyword while or for.
Syntax:
for loop while loop

for <variable> in <sequence>: while <test condition>:


statement-1 statement-1
statement-2 statement-2
. .
. .
else: else:
statement(s) statement(s)

Nested Loop:
A loop inside another loop is known as nested loop.
Syntax:
for <variable-name> in <sequence>:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

for <variable-name> in <sequence>:

statement(s)

statement(s)

Example:
for i in range(1,4):
for j in range(1,i):
print("*", end=" ")

print(" ")

Programs related to Conditional, looping and jumping statements

Write a program to check a number whether it is even or odd.

num=int(input("Enter the number: "))

if num%2==0:
print(num, " is even number")
else:
print(num, " is odd number")

Write a program in python to check a number whether it is prime or not.


num=int(input("Enter the number: "))
for i in range(2,num):

if num%i==0:
print(num, "is not prime number")

break;

else:
print(num,"is prime number")

Write a program to check a year whether it is leap year or not.


year=int(input("Enter the year: "))
if year%100==0 and year%400==0:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

print("It is a leap year")


elif year%4==0:
print("It is a leap year")
else:
print("It is not leap year")

Write a program in python to convert °C to °F and vice versa.


a=int(input("Press 1 for C to F \n Press 2 for F to C \n"))

if a==1:
c=float(input("Enter the temperature in degree celcius: "))
f= (9/5)*c+32
print(c, "Celcius = ",f," Fahrenheit")
elif a==2:
f=float(input("Enter the temperature in Fahrenheit: "))
c= (f-32)*5/9
print(f, "Fahrenheit = ",c," Celcius")
else:
print("You entered wrong choice")

Write a program to check a number whether it is palindrome or not.


num=int(input("Enter a number : "))

n=num
res=0
while num>0:
rem=num%10
res=rem+res*10

num=num//10
if res==n:
print("Number is Palindrome")

else:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

print("Number is not Palindrome")


A number is Armstrong number or not.
num=input("Enter a number : ")
length=len(num)
n=int(num)
num=n sum=0
while n>0:
rem=n%10
sum=sum+rem**length
n=n//10
if num==sum:
print(num, "is armstrong number")

else:

print(num, "is not armstrong number")

To check whether the number is perfect number or not


num=int(input("Enter a number : "))

sum=0
for i in range(1,num):
if(num%i==0):

sum=sum+i
if num==sum:
print(num, "is perfect number")

else:

print(num, "is not perfect number")

Write a program to print Fibonacci series.


n=int(input("How many numbers : "))
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

first=0
second=1
i=3
print(first, second, end=" ")
while i<=n:
third=first+second
print(third, end=" ")
first=second
second=third

i=i+1

To print a pattern using nested loops


for i in range(1,5):
for j in range(1,i+1):

print(j," ", end=" ")

print('\n')

1
1 2
1 2 3
1 2 3 4

FUNCTIONS INPYTHON
Definition:
Functions are the subprograms that perform specific task. Functions are the small modules.
Types of Functions
There are two types of functions in python:

1. Library Functions (Built in functions)


2. Functions defined in modules
3. User Defined Functions
Library Functions: These functions are already built in the python library.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Functions defined in modules: These functions defined in particular modules. When you want to
use these functions in program, you have to import the corresponding moduleof that function.
User Defined Functions: The functions those are defined by the user are called user defined functions.
Library Functions in Python
These functions are already built in the library of python.

For example: type( ), len( ), input( ) etc.


Functions defined in modules:
Functions of math module:
To work with the functions of math module, we must import math module in program.
import math
S. No. Function Descri Exam
ption ple
1 sqrt( ) Returns the square root of a number >>>[Link](49)
7.0
2 ceil( ) Returns the upper integer >>>[Link](81.3)
82
3 floor( ) Returns the lower integer >>>[Link](81.3)
81
4 pow( ) Calculate the power of a number >>>[Link](2,3)
8.0
5 fabs( ) Returns the absolute value of a number >>>[Link](-5.6)
5.6
6 exp( ) Returns the e raised to the power i.e. e3 >>>[Link](3)
20.085536923187668

Function in random module:

Random module has a function randint( ).


• randint( ) function generates the random integer values including start and end values.
Syntax: randint(start, end)
It has two parameters. Both parameters must have integer values.
Example:
import random
n=[Link](3,7)

The value of n will be 3 to 7.


USER DEFINED FUNCTIONS
The syntax to define a function is:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

def function-name ( parameters) :


#statement(s)

Where:
➢ Keyword def marks the start of function header.
➢ A function name to uniquely identify it. Function naming follows the same rules
ofwriting identifiers in Python.
➢ Parameters (arguments) through which we pass values to a function. They are optional.
➢ A colon (:) to mark the end of function header.
➢ One or more valid python statements that make up the function body. Statements
musthave same indentation level.

➢ An optional return statement to return a value from the function.


Example:
def display(name):
print("Hello " + name + " How are you?")

Function Parameters:
A functions has two types of parameters:
Formal Parameter: Formal parameters are written in the function prototype and function header of
the definition. Formal parameters are local variables which are assigned values from the arguments
when the function is called.
Actual Parameter: When a function is called, the values that are passed in the call are called actual
parameters. At the time of the call each actual parameter is assigned to the corresponding formal
parameter in the function definition.
Example :

def ADD(x, y): #Defining a function and x and y are formal parameters
z=x+y
print("Sum = ", z)
a=float(input("Enter first number: " ))
b=float(input("Enter second number: " ))
ADD(a,b) #Calling the function by passing actual parameters
In the above example, x and y are formal parameters. a and b are actual parameters.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Calling the function:


Once we have defined a function, we can call it from another function, program or even the
Python prompt. To call a function we simply type the function name with appropriate parameters.

Syntax:
function-name(parameter)
Example:
ADD(10,20)

OUTPUT:
Sum = 30.0

How function works?

… .. …

def functionName(parameter):… .. …
… .. …

functionName(parameter)
… .. …
… .. …

The return statement:

The return statement is used to exit a function and go back to the place from where it was called.
There are two types of functions according to return statement:

• Function returning some value (non-void function)


• Function not returning any value (void function)

Function returning some value (non-void function):

Syntax:
return expression/value

Example-1:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Function returning one value

def my_function(x):
return 5 * x
Example-2
Function returning multiple values:
def sum(a,b,c):
return a+5, b+4, c+7
S=sum(2,3,4) # S will store the returned values as a tuple print(S)

OUTPUT:
(7, 7, 11)

Example-3:
Storing the returned values separately:
def sum(a,b,c):
return a+5, b+4, c+7
s1, s2, s3=sum(2, 3, 4) # storing the values separately print(s1, s2, s3)

OUTPUT:
6 7 11

Function not returning any value (void function) : The function that performs someoperations
but does not return any value, called void function.
def message(): print("Hello")
m=message()
print(m)
OUTPUT
Hello None
Scope and Lifetime of variables:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Scope of a variable is the portion of a program where the variable is recognized. Parametersand
variables defined inside a function is not visible from outside. Hence, they have a local scope.
There are two types of scope for variables:

• Local Scope
• Global Scope

Local Scope: Variable used inside the function. It cannot be accessed outside the function. In this
scope, The lifetime of variables inside a function is as long as the function executes. They are
destroyed once we return from the function. Hence, a function does not remember thevalue of a
variable from its previous calls.
Global Scope: Variable can be accessed outside the function. In this scope, Lifetime of a variable is the
period throughout which the variable exits in the memory.
Example:
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
OUTPUT:
Value inside function: 10
Value outside function: 20
Here, we can see that the value of x is 20 initially. Even though the function my_func()changedthe
value of x to 10, it did not affect the value outside the function.

This is because the variable x inside the function is different (local to the function) from theone
outside. Although they have same names, they are two different variables with different scope.

On the other hand, variables outside of the function are visible from inside. They have a global scope.
We can read these values from inside the function but cannot change (write) them. In order to modify
the value of variables outside the function, they must be declared as global variables using the keyword
global.
RECURSION:
A function calls itself, is called recursion.
Python program to find the factorial of a number using recursion:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Program:
def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)
num=int(input("enter the number: "))
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num = = 0:
print("The factorial of 0 is 1")
else:
print("The factorial of ",num," is ", factorial(num))

OUTPUT:
enter the number: 5
The factorial of 5 is 120

Python program to print the Fibonacci series using recursion:


Program
def fibonacci(n):
if n<=1:
return n
else:
return(fibonacci(n-1)+fibonacci(n-2))
num=int(input("How many terms you want to display: "))
for i in range(num):
print(fibonacci(i)," ", end=" ")
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

OUTPUT:
How many terms you want to display: 8
0 1 1 2 3 5 8 13

Binary Search using recursion:

The given array or sequence must be sorted to perform binary search.

Program
def Binary_Search(sequence, item, LB, UB):
if LB>UB:
return -5 # return any negative value mid=int((LB+UB)/2)
if item==sequence[mid]:
return mid
elif item<sequence[mid]:
UB=mid-1
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

return Binary_Search(sequence, item, LB, UB)


else:
LB=mid+1
return Binary_Search(sequence, item, LB, UB)
L=eval(input("Enter the elements in sorted order: "))
n=len(L)
element=int(input("Enter the element that you want to search :"))
found=Binary_Search(L,element,0,n-1)
if found>=0:
print(element, "Found at the index : ",found)
else:
print("Element not present in the list")

Type coercion
Type coercion refers to the automatic conversion of one data type to another, usually performed
by the Python interpreter. This type of conversion occurs when mixing data types in operations or
assignments.

Python Type Conversion


In programming, type conversion is the process of converting data of one type to another. For
example: converting int data to str.
There are two types of type conversion in Python.
Implicit Conversion - Automatic type conversion
Explicit Conversion - Manual type conversion

Example 1: Converting integer to float


Let's see an example where Python promotes the conversion of the lower data type (integer) to
the higher data type (float) to avoid data loss.
integer_number = 123
float_number = 1.23
new_number = integer_number + float_number
# display new value and resulting data type
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

print("Value:",new_number)
print("Data Type:",type(new_number))
Output
Value: 124.23
Data Type: <class 'float'>
In the above example, we have created two variables: integer_number and float_number of int and
float type respectively.
Then we added these two variables and stored the result in new_number.

Explicit Type Conversion


In Explicit Type Conversion, users convert the data type of an object to required data type.
We use the built-in functions like int(), float(), str(), etc to perform explicit type conversion.
This type of conversion is also called typecasting because the user casts (changes) the data type of the
objects.
Example 2: Addition of string and integer Using Explicit Conversion
num_string = '12'
num_integer = 23
print("Data type of num_string before Type Casting:",type(num_string))
# explicit type conversion
num_string = int(num_string)
print("Data type of num_string after Type Casting:",type(num_string))
num_sum = num_integer + num_string
print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
Output
Data type of num_string before Type Casting: <class 'str'>
Data type of num_string after Type Casting: <class 'int'>
Sum: 35
Data type of num_sum: <class 'int'>
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

In the above example, we have created two variables: num_string and num_integer with str and int
type values respectively. Notice the code,
num_string = int(num_string)
Here, we have used int() to perform explicit type conversion of num_string to integer type.
After converting num_string to an integer value, Python is able to add these two variables.
Finally, we got the num_sum value i.e 35 and data type to be int.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

UNIT – II
STRINGS
Strings –Compound data type – len function – String slices – String traversal – Escape characters – String
formatting operator – String formatting functions. Tuples: Tuples – Creating tuples – Accessing values in
tuples – Tuple assignment – Tuples as return values – Basic tuple operations – Built-in tuple functions.
Lists: Values and accessing elements – Traversing a list – Deleting elements from list – Built-in list
operators & methods. Dictionaries: Creating dictionary – Accessing values in dictionary – Updating
dictionary – Deleting elements from dictionary – Operations in dictionary - Built-in dictionary methods.
Introduction
Sequence of characters enclosed in single, double or triple quotation marks.
Basics of String
• Strings are immutable in python. It means it is unchangeable. At the same memory address, the
new value cannot be stored.
• Each character has its index or can be accessed using its index.
• String in python has two-way index for each location. (0, 1, 2, ……. In the forward direction
and -1, -2, -3, in the backward direction.)
Example

0 1 2 3 4 5 6 7
d y n a m i c s
-8 -7 -6 -5 -4 -3 -2 -1

• The index of string in forward direction starts from 0 and in backward direction starts from -1.
• The size of string is total number of characters present in the string. (If there are n characters in
the string, then last index in forward direction would be n-1 and last index in backward direction
would be –n.)
• String are stored each character in contiguous location.
• The character assignment is not supported in string because strings are immutable. Example :
• str = “dynamics”
• str[2] = ‘y’ # it is invalid. Individual letter assignment not allowed in python
Traversing a String
Access the elements of string, one character at a time. str = “dynamics”
for ch in str :
print(ch, end= ‘ ‘)
Output
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Dynamics
String Operators
• Basic Operators (+, *)

• Membership Operators (in, not in)


• Comparison Operators (==, !=, <, <=, >, >=)
Basic Operators
There are two basic operators of strings:
• String concatenation Operator (+)
• String repetition Operator (*)
String concatenation Operator
The + operator creates a new string by joining the two operand strings.
Example:
>>>”Hello”+”Python” ‘HelloPython’
>>>’2’+’7’
’27’
>>>”Python”+”3.0”
‘Python3.0’
Note: You cannot concate numbers and strings as operands with + operator.
Example:
>>>7+’4’ # unsupported operand type(s) for +: 'int' and 'str' It is invalid and generates an error.
String repetition Operator
It is also known as String replication operator. It requires two types of operands- a string and an
integer number.
Example:
>>>”you” * 3 ‘youyouyou’
>>>3*”you” ‘youyouyou’
Note:You cannot have strings as n=both the operands with * operator. Example:
>>>”you” * “you” # can't multiply sequence by non-int of type 'str' It is invalid and generates an
error.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Membership Operators
• in – Returns True if a character or a substring exists in the given string; otherwise False
• not in - Returns True if a character or a substring does not exist in the given string; otherwise
False
Example
>>> "ken" in "Kendriya Vidyalaya" False
>>> "Ken" in "Kendriya Vidyalaya" True
>>>"ya V" in "Kendriya Vidyalaya" True
>>>"8765" not in "9876543" False

Comparison Operators
These operators compare two strings character by character according to their ASCII value.

Characters ASCII (Ordinal) Value

‘0’ to ‘9’ 48 to 57

‘A’ to ‘Z’ 65 to 90

‘a’ to ‘z’ 97 to 122

Example:
>>> 'abc'>'abcD' False
>>> 'ABC'<'abc' True
>>> 'abcd'>'aBcD' True
>>> 'aBcD'<='abCd' True

Finding the Ordinal or Unicode value of a character:

Function Description

ord(<character>) Returns ordinal value of a character

chr(<value>) Returns the corresponding character


Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Example
>>> ord('b') 98
>>> chr(65) 'A'
Write a program to display ASCII code of a character and vice versa.
var=True
while var:
choice=int(input("Press-1 to find the ordinal value \n Press-2 to find a character of a value\n")) if
choice==1:
ch=input("Enter a character : ") print(ord(ch))
elif choice==2:
val=int(input("Enter an integer value: ")) print(chr(val))
else:
print("You entered wrong choice")
print("Do you want to continue? Y/N") option=input()
if option=='y' or option=='Y': var=True
else:
var=False
Slice operator with Strings
The slice operator slices a string using a range of indices.
Syntax
string-name[start:end]
where start and end are integer indices. It returns a string from the index start to end-1.

0 1 2 3 4 5 6 7 8 9 10 11 12 13
d a t a s t r u c t u r e
-14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Example
>>> str="data structure"
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

>>> str[0:14]
'data structure'
>>> str[0:6]
'data s'
>>> str[2:7]
'ta st'
>>> str[-13:-6]
'ata str'
>>> str[-5:-11]
'' #returns empty string
>>> str[:14] # Missing index before colon is considered as 0. 'data structure'
>>> str[0:] # Missing index after colon is considered as 14. (length of string) 'data structure'
>>> str[7:] 'ructure'
>>> str[4:]+str[:4] ' structuredata'
>>> str[:4]+str[4:] #for any index str[:n]+str[n:] returns original string 'data structure'
>>> str[8:]+str[:8] 'ucturedata str'
>>> str[8:], str[:8]
('ucture', 'data str')
Slice operator with step index:
Slice operator with strings may have third index. Which is known as step. It is optional.
Syntax:
string-name[start:end:step]
Example:
>>> str="data structure"
>>> str[Link]
't tu'
>>> str[-11:-3:3]
'atc'
>>> str[: : -1] # reverses a string 'erutcurts atad'
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Interesting Fact: Index out of bounds causes error with strings but slicing a string outside the index does
not cause an error.
Example
>>>str[14]
IndexError: string index out of range
>>> str[14:20] # both indices are outside the bounds ' ' # returns empty string
>>> str[10:16]
'ture'
Reason: When you use an index, you are accessing a particular character of a string, thus the index
must be valid and out of bounds index causes an error as there is no character to return from the given
index.
But slicing always returns a substring or empty string, which is valid sequence.
Built-in functions of string: Example:
str=”data structure”
s1= “hello365” s2= “python” s3 = ‘4567’
s4 = ‘ ‘
s5= ‘comp34%@’

S. Function Description Example


No.

1 len( ) Returns the length of a string >>>print(len(str))


14

2 capitalize( ) Returns a string with its first >>> [Link]()


character capitalized.
'Data structure'

3 find(sub,start,end) Returns the lowest index in the string >>> [Link]("ruct",5,13) 7


where the substring sub is found within
>>> [Link]("ruct",8,13)
the slice range.
-1
Returns -1 if sub is not found.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

4 isalnum( ) Returns True if the characters in the >>>[Link]( ) True


string are alphabets or numbers. False
>>>[Link]( ) True
otherwise
>>>[Link]( ) True
>>>[Link]( ) False
>>>[Link]( ) False

5 isalpha( ) Returns True if all characters in the >>>[Link]( ) False


string are alphabetic. False otherwise.
>>>[Link]( ) True
>>>[Link]( ) False
>>>[Link]( ) False
>>>[Link]( ) False

6 isdigit( ) Returns True if all the characters in the >>>[Link]( ) False


string are digits. False otherwise.
>>>[Link]( ) False
>>>[Link]( ) True
>>>[Link]( ) False
>>>[Link]( ) False

7 islower( ) Returns True if all the characters in the >>> [Link]() True
string are lowercase. False otherwise.
>>> [Link]()

True
>>> [Link]() False
>>> [Link]() False
>>> [Link]() True

8 isupper( ) Returns True if all the characters in the >>> [Link]() False
string are uppercase. False otherwise.
>>> [Link]() False
>>> [Link]() False
>>> [Link]() False
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

>>> [Link]() False

9 isspace( ) Returns True if there are only >>> " ".isspace() True
whitespace characters in the string.
>>> "".isspace() False
False otherwise.

10 lower( ) Converts a string in lowercase >>> "HeLlo".lower()


characters.
'hello'

11 upper( ) Converts a string in uppercase >>> "hello".upper()


characters.
'HELLO'

12 lstrip( ) Returns a string after removing >>> str="data structure"


theleading characters. (Left side).
>>> [Link]('dat') ' structure'
if used without any argument, it
>>> [Link]('data') '
removes the leading whitespaces.
structure'
>>> [Link]('at') 'data
structure'
>>> [Link]('adt') ' structure'
>>> [Link]('tad') ' structure'

13 rstrip( ) Returns a string after removing >>> [Link]('eur') 'data


thetrailing characters. (Right side). struct'
if used without any argument, it >>> [Link]('rut') 'data
removes the trailing whitespaces. structure'
>>> [Link]('tucers') 'data '

14 split( ) breaks a string into words and creates a >>> str="Data Structure"
list out of it
>>> [Link]( ) ['Data',
'Structure']

Programs related to Strings


Write a program that takes a string with multiple words and then capitalize the first letter of each
word and forms a new string out of it.
Solution
s1=input("Enter a string : ") length=len(s1)
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

a=0 end=length
s2="" #empty string while a<length:
if a==0:
s2=s2+s1[0].upper() a+=1
elif (s1[a]==' 'and s1[a+1]!=''): s2=s2+s1[a] s2=s2+s1[a+1].upper() a+=2
else:
s2=s2+s1[a] a+=1
print("Original string : ", s1) print("Capitalized wrds string: ", s2)
Write a program that reads a string and checks whether it is a palindrome string or not.
str=input("Enter a string : ") n=len(str)
mid=n//2 rev=-1
for i in range(mid): if str[i]==str[rev]:
i=i+1 rev=rev-1
else:
print("String is not palindrome") break
else:
print("String is palindrome")

Write a program to convert lowercase alphabet into uppercase and vice versa.
choice=int(input("Press-1 to convert in lowercase\n Press-2 to convert in uppercase\n"))
str=input("Enter a string: ")
if choice==1: s1=[Link]() print(s1)
elif choice==2: s1=[Link]() print(s1)
else:
print("Invalid choice entered")

TUPLE IN PYTHON
INTRODUCTION:
Tuple is a collection of elements which is ordered and unchangeable (Immutable). Immutable
means you cannot change elements of a tuple in place.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

• Allows duplicate members.


• Consists the values of any type, separated by comma.
• Tuples are enclosed within parentheses ( ).
• Cannot remove the element from a tuple.

Creating Tuple
Syntax
tuple-name = ( ) # empty tuple
tuple-name = (value-1, value-2, , value-n)
Example
>>> T=(23, 7.8, 64.6, 'h', 'say')
>>> T
(23, 7.8, 64.6, 'h', 'say')
Creating a tuple with single element
>>> T=(3) #With a single element without comma, it is a value only, not a tuple
>>> T 3
>>> T= (3, ) # to construct a tuple, add a comma after the single element
>>> T (3,)
>>> T1=3, # It also creates a tuple with single element
>>> T1 (3,)
Creating a tuple using tuple( ) constructor:
It is also possible to use the tuple( ) constructor to create a tuple.
>>>T=tuple( ) # empty tuple
>>> T=tuple((45,3.9, 'k',22)) #note the double round-brackets
>>> T
(45, 3.9, 'k', 22)
>>> T2=tuple('hello') # for single round-bracket, the argument must be of sequence type
>>> T2
('h', 'e', 'l', 'l', 'o')
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

>>> T3=('hello','python')
>>> T3
('hello', 'python')
Nested Tuples
>>> T=(5,10,(4,8))

>>> T
(5, 10, (4, 8))
Creating a tuple by taking input from the user:
>>> T=tuple(input("enter the elements: "))
enter the elements: hello python
>>> T
('h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n')
>>> T1=tuple(input("enter the elements: ")) enter the elements: 45678
>>> T1
('4', '5', '6', '7', '8') # it treats elements as the characters though we entered digits
To overcome the above problem, we can use eval( ) method, which identifies the data type and evaluate
them automatically.
>>> T1=eval(input("enter the elements: "))
enter the elements: 56789
>>> T1
56789 # it is not a list, it is an integer value
>>> type(T1)
<class 'int'>
>>> T2=eval(input("enter the elements: "))
enter the elements: (1,2,3,4,5) # Parenthesis is optional
>>> T2
(1, 2, 3, 4, 5)
>>> T3=eval(input("enter the elements: "))
enter the elements: 6, 7, 3, 23, [45,11] # list as an element of tuple
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

>>> T3
(6, 7, 3, 23, [45, 11])
Accessing Tuples
Tuples are very much similar to lists. Like lists, tuple elements are also indexed. Forward
indexing as 0,1,2,3,4……… and backward indexing as -1,-2,-3,-4,………
• The values stored in a tuple can be accessed using the slice operator ([ ] and [:]) with indexes.
• tuple-name[start:end] will give you elements between indices start to end-1.
• The first item in the tuple has the index zero (0).
Example:

>>> alpha=('q','w','e','r','t','y')

Forward Index

0 1 2 3 4 5
q w e r t y
-6 -5 -4 -3 -2 -1

Backward Index

>>> alpha[5] 'y'


>>> alpha[-4] 'e'
>>> alpha[46]
IndexError: tuple index out of range
>>> alpha[2]='b' #can’t change value in tuple, the value will remain unchanged TypeError: 'tuple'
object does not support item assignment
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

8.3.1 Difference between List and Tuple:

S. No. List Tuple

1 Ordered and changeable (Mutable) Ordered but unchangeable (Immutable)

2 Lists are enclosed in brackets. [ ] Tuples are enclosed in parentheses. ( )

3 Element can be removed. Element can’t be removed.

Traversing a Tuple
Syntax:
for <variable> in tuple-name: statement
Example

Method-1
>>> alpha=('q','w','e','r','t','y')
>>> for i in alpha:
print(i)
Output
qwerty

Method-2
>>> for i in range(0, len(alpha)):
print(alpha[i])
Output
qwerty
Tuple Operations
• Joining operator +
• Repetition operator *
• Slice operator [ : ]
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

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


• Joining Operator: It joins two or more tuples.
Example
>>> T1 = (25,50,75)
>>> T2 = (5,10,15)
>>> T1+T2
(25, 50, 75, 5, 10, 15)
>>> T1 + (34)
TypeError : can only concatenate tuple (not "int") to tuple
>>> T1 + (34, )
(25, 50, 75, 34)
Repetition Operator: It replicates a tuple, specified number of times.
Example:
>>> T1*2
(25, 50, 75, 25, 50, 75)

>>> T2=(10,20,30,40)
>>> T2[2:4]*3
(30, 40, 30, 40, 30, 40)
Slice Operator
tuple-name[start:end] will give you elements between indices start to end-1.
>>>alpha=('q','w','e','r','t','y')
>>> alpha[1:-3] ('w', 'e')
>>> alpha[3:65] ('r', 't', 'y')
>>> alpha[-1:-5]
()
>>> alpha[-5:-1] ('w', 'e', 'r', 't')

List-name[start:end:step] will give you elements between indices start to end-1 with skipping
elements as per the value of step.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

>>> alpha[Link] ('w', 'r')


>>> alpha[ : : -1]
('y', 't', 'r', 'e', 'w', 'q') #reverses the tuple

Comparison Operators
• Compare two tuples
• Python internally compares individual elements of tuples in lexicographical order.
• It compares the each corresponding element must compare equal and two sequences must be of
the same type.
• For non-equal comparison as soon as it gets a result in terms of True/False, from
corresponding elements’ comparison. If Corresponding elements are equal, it goes to the next
element and so on, until it finds elements that differ.

Example
>>> T1 = (9, 16, 7)
>>> T2 = (9, 16, 7)
>>> T3 = ('9','16','7')
>>> T1 = = T2
True
>>> T1==T3
False
>>> T4 = (9.0, 16.0, 7.0)
>>> T1==T4
True
>>> T1<T2
False
>>> T1<=T2
True
Tuple Methods
Consider a tuple:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

subject=("Hindi","English","Maths","Physics")

S. Function Description Example


Name
No.

1 len( ) Find the length of a tuple. >>>subject=("Hindi","English","Maths",


"Physics”)
Syntax:
>>> len(subject) 4
len (tuple-name)

2 max( ) Returns the largest value >>> max(subject) 'Physics'


from a tuple.
Syntax:
max(tuple-name)

Error: If the tuple contains values of different data types, then it will give an error because
mixed data type comparison is not possible.
>>> subject = (15, "English", "Maths", "Physics", 48.2)
>>> max(subject)
TypeError: '>' not supported between instances of 'str' and 'int'

3 min( ) Returns the >>>subject=("Hindi","English","Maths",


smallest value from "Physics")
a tuple.
>>> min(subject) 'English'
Syntax:
min(tuple-name)

Error: If the tuple contains values of different data types, then it will give an error because
mixed data type comparison is not possible.

>>> subject = (15, "English", "Maths", "Physics", 48.2)


>>> min(subject)
TypeError: '>' not supported between instances of 'str' and 'int'
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

4 index( ) Returns the index of the >>>subject=("Hindi","English","Maths",


first element with the "Physics")
specified value.
Syntax:

tuple- [Link](element) >>> [Link]("Maths") 2

5 count( ) Return the number of times >>> [Link]("English") 1


the value appears.
Syntax:
tuple- [Link](element)

Tuple Packing and Unpacking:


Tuple Packing: Creating a tuple from set of values.
Example
>>> T=(45,78,22)
>>> T
(45, 78, 22)

Tuple Unpacking: Creating individual values from the elements of tuple.

Example
>>> a, b, c=T
>>> a 45
>>> b 78
>>> c 22
Note: Tuple unpacking requires that the number of variable on the left side must be equal to the length
of the tuple.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Delete a tuple
The del statement is used to delete elements and objects but as you know that tuples are
immutable, which also means that individual element of a tuple cannot be deleted.
Example
>> T=(2,4,6,8,10,12,14)
>>> del T[3]

TypeError: 'tuple' object doesn't support item deletion


But you can delete a complete tuple with del statement as:
Example
>>> T=(2,4,6,8,10,12,14)
>>> del T
>>> T
NameError: name 'T' is not defined

LIST IN PYTHON
Introduction
• List is a collection of elements which is ordered and changeable (mutable).
• Allows duplicate values.
• A list contains items separated by commas and enclosed within square brackets ([ ]).
• All items belonging to a list can be of different data type.
• The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list.

Difference between list and string

List String

Mutable Immutable

Element can be assigned at specified Element/character cannot be


Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Index assigned at specified index.

Example: Example:
>>>L=[7,4,8,9] >>>str= “python”
>>>L[2]=6 #valid >>>str[2]= ‘p’ #error

Creating a list
To create a list enclose the elements of the list within square brackets and separate the
elements by commas.
Syntax
list-name= [item-1, item-2, , item-n]
Example
mylist = ["apple", "banana", "cherry"] # a list with three items L = [ ] # an empty list
Creating a list using list( ) Constructor
• It is also possible to use the list( ) constructor to make a list.
mylist = list(("apple", "banana", "cherry")) #note the double round-brackets print(mylist)
L=list( ) # creating empty list
Nested Lists
>>> L=[23,'w',78.2, [2,4,7],[8,16]]
>>> L
[23, 'w', 78.2, [2, 4, 7], [8, 16]]
Creating a list by taking input from the user:
>>> List=list(input("enter the elements: "))
enter the elements: hello python
>>> List

['h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n']
>>> L1=list(input("enter the elements: "))
enter the elements: 678546
>>> L1
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

['6', '7', '8', '5', '4', '6'] # it treats elements as the characters though we entered digits
To overcome the above problem, we can use eval( ) method, which identifies the data type and
evaluate them automatically.
>>> L1=eval(input("enter the elements: "))
enter the elements: 654786
>>> L1
654786 # it is an integer, not a list
>>> L2=eval(input("enter the elements: "))
enter the elements: [6,7,8,5,4,3] # for list, you must enter the [ ] bracket
>>> L2
[6, 7, 8, 5, 4, 3]
Note: With eval( ) method, If you enter elements without square bracket[ ], it will be considered as a
tuple.
>>> L1=eval(input("enter the elements: "))
enter the elements: 7,65,89,6,3,4
>>> L1
(7, 65, 89, 6, 3, 4) #tuple
Accessing lists
• The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes.
• List-name[start:end] will give you elements between indices start to end-1.
• The first item in the list has the index zero (0).

Example
>>> number=[12,56,87,45,23,97,56,27]
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

0 1 2 3 4 5 6 7

12 56 87 45 23 97 56 27

-8 -7 -6 -5 -4 -3 -2 -1

>>> number[2] 87
>>> number[-1] 27
>>> number[-8] 12
>>> number[8]
IndexError
list index out of range
>>> number[5]=55 #Assigning a value at the specified index
>>> number
[12, 56, 87, 45, 23, 55, 56, 27]

Traversing a LIST
Traversing means accessing and processing each element.
Method-1
>>> day=list(input("Enter elements :"))
Enter elements : sunday
>>> for d in day:
print(d)

Output
sunday

Method-2
>>> day=list(input("Enter elements :"))
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Enter elements : wednesday


>>> for i in range(len(day)):
print(day[i])

Output
wednesday

List Operators
• Joining operator +
• Repetition operator *
• Slice operator [ : ]
• Comparison Operator <, <=, >, >=, ==, !=

Joining Operator
It joins two or more lists.
Example
>>> L1=['a',56,7.8]
>>> L2=['b','&',6]
>>> L3=[67,'f','p']
>>> L1+L2+L3
['a', 56, 7.8, 'b', '&', 6, 67, 'f', 'p']

Repetition Operator
It replicates a list specified number of times.
Example
>>> L1*3
['a', 56, 7.8, 'a', 56, 7.8, 'a', 56, 7.8]
>>> 3*L1
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

['a', 56, 7.8, 'a', 56, 7.8, 'a', 56, 7.8]

Slice Operator
List-name[start:end] will give you elements between indices start to end-1.

>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:-2] [87, 45, 23, 97]
>>> number[4:20] [23, 97, 56, 27]
>>> number[-1:-6] [ ]
>>> number[-6:-1]
[87, 45, 23, 97, 56]
>>> number[0:len(number)] [12, 56, 87, 45, 23, 97, 56, 27]
List-name[start:end:step] will give you elements between indices start to end-1 with skipping
elements as per the value of step.

>>> number[Link] [56, 45, 97]


>>> number[: : -1]
[27, 56, 97, 23, 45, 87, 56, 12] #reverses the list

List modification using slice operator


>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:4]=["hello","python"]
>>> number
[12, 56, 'hello', 'python', 23, 97, 56, 27]
>>> number[2:4]=["computer"]
>>> number
[12, 56, 'computer', 23, 97, 56, 27]
Note: The values being assigned must be a sequence (list, tuple or string)
Example:
>>> number=[12,56,87,45,23,97,56,27]
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

>>> number=[12,56,87,45,23,97,56,27]

>>> number[2:3]=78 # 78 is a number, not a sequence


TypeError
It can only assign an iterable
Comparison Operators
• Compares two lists
• Python internally compares individual elements of lists in lexicographical order.
• It compares each corresponding element must compare equal and two sequences must be of the
same type.
• For non-equal comparison as soon as it gets a result in terms of True/False, from
corresponding elements’ comparison. If Corresponding elements are equal, it goes to the next
element and so on, until it finds elements that differ.
Example
>>>L1, L2 = [7, 6, 9], [7, 6, 9]
>>>L3 = [7, [6, 9] ]

For Equal Comparison

Comparison Result Reason


>>>L1==L2 True Corresponding elements have same value and same
type
>>>L1==L3 False Corresponding values are not same

For Non-equal comparison:

Comparison Result Reason

>>> L1>L2 False All elements are equal

>>> L2>L3 TypeError: '>' not in L2, element at the index 1 is int
supported between type and in L3 element at the index
instances of 'int' and 1 is list type
'list'
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

>>>[3,4,7,8]<[5,1] True 3<5 is True

>>>[3,4,7,8]<[3,4,9,2] True First two elements are same so move


to next element and 7<9 is True

>>>[3,4,7,8]<[3,4,9,11] True 7<9 is True

>>>[3,4,7,8]<[3,4,7,5] False 8<5 is False

List Methods
Consider a list:
company=["IBM","HCL","Wipro"]

S. Function
Description Example
No. Name
1 append( ) To add element to the >>> [Link]("Google")
listat the end. >>> company
Syntax: ['IBM', 'HCL', 'Wipro', 'Google']
[Link]
(element)
Error:
>>>[Link]("infosys","microsoft") # takes exactly one element
TypeError: append() takes exactly one argument (2 given)

2 extend( ) Add a list, to the >>>company=["IBM","HCL","Wipro"]


end ofthe current list. >>> desktop=["dell","HP"]
Syntax: >>> [Link](desktop)
[Link](list) >>> company
['IBM', 'HCL', 'Wipro', 'dell', 'HP']
Error:
>>>[Link]("dell","HP") #takes only a list as argument
TypeError: extend() takes exactly one argument (2 given)

3. len( ) Find the length of the >>>company=["IBM","HCL","Wipro"]


list.
Syntax: >>> len(company)
len(list-name) 3
>>> L=[3,6,[5,4]]
>>> len(L)
3
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

4 index( ) Returns the index of >>> company = ["IBM", "HCL", "Wipro",


the first element with "HCL","Wipro"]
the specified value. >>> [Link]("Wipro")2
Syntax:
list-
[Link](element)
Error:
>>> [Link]("WIPRO") # Python is case-sensitive language
ValueError: 'WIPRO' is not in list

>>> [Link](2) # Write the element, not index

ValueError: 2 is not in list

5 insert( ) Adds an element at the >>>company=["IBM","HCL","Wipro


specified position. "]
>>> [Link](2,"Apple")
Syntax: >>> company
[Link](index, ['IBM', 'HCL', 'Apple', 'Wipro']
element)
>>> [Link](16,"Microsoft")
>>> company
['IBM', 'HCL', 'Apple',
'Wipro',
'Microsoft']

>>> [Link](-16,"TCS")
>>> company
['TCS', 'IBM', 'HCL', 'Apple',
'Wipro',
'Microsoft']

6 count( ) Return the number >>> company = ["IBM",


oftimes the "HCL",
value appears. "Wipro", "HCL","Wipro"]
Syntax: >>>
[Link](element) [Link]("HCL")
2
>>> [Link]("TCS")
0
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

7 remove( To remove an >>> company = ["IBM",


) elementfrom the "HCL",
list. "Wipro", "HCL","Wipro"]
Syntax: >>> [Link]("Wipro")
list- >>> company
[Link](element) ['IBM', 'HCL', 'HCL', 'Wipro']
Error:
>>> [Link]("Yahoo")
ValueError: [Link](x): x not
in list
8 clear( ) Removes all the >>> company=["IBM","HCL",
elementsfrom list. "Wipro"]
Syntax:
[Link]( ) >>> [Link]( )

>>>

compa

ny[ ]
9 pop( ) Removes the element at >>>company=["IBM","HCL",
the specified position "Wipro"]
and returns the deleted >>> [Link](1) 'HCL'
element. >>> company ['IBM', 'Wipro']
Syntax:
[Link](index) >>> [Link]( ) 'Wipro'

The index argument is


optional. If no index is
specified, pop( )
removes and returns the
last item in the list.
Error:
>>>L=[ ]
>>>[Link]( )
IndexError: pop from empty list

10 copy( ) Returns a copy of the list. >>>company=["IBM","HCL", "Wipro"]


>>> L=[Link]( )
Syntax: >>> L
[Link]( ) ['IBM', 'HCL', 'Wipro']
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

11 reverse( ) Reverses the order of the >>>company=["IBM","HCL", "Wipro"]


list. >>> [Link]()
Syntax: >>> company
[Link]( ) ['Wipro', 'HCL',
'IBM']
Takes no argument,
returns no list.

12. sort( ) Sorts the list. By default >>>company=["IBM","HCL", "Wipro"]


in ascending order. >>>[Link]( )
>>> company
Syntax: ['HCL', 'IBM', 'Wipro']
[Link]( )
To sort a list in descending order:

>>>company=["IBM","HCL", "Wipro"]
>>> [Link](reverse=True)
>>> company
['Wipro', 'IBM',
'HCL']

Deleting the elements from the list using del statement


Syntax
del list-name[index] # to remove element at specified index del list-name[start:end] # to
remove elements in list slice
Example
>>> L=[10,20,30,40,50]
>>> del L[2] # delete the element at the index 2
>>> L
[10, 20, 40, 50]
>>> L= [10,20,30,40,50]
>>> del L[1:3] # deletes elements of list from index 1 to 2.
>>> L
[10, 40, 50]
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

>>> del L # deletes all elements and the list object too.
>>> L
NameError: name 'L' is not defined

Difference between del, remove( ), pop( ), clear( ):

S. Del remove( ) pop( ) clear( )


No.

1 Statement Function Function Function

Deletes a single element or a Removes the Removes an


Removes all the
2 list slice or completelist. firstmatching individual item and elements from
item from returns it. list.
the list.
Removes all elementsand Removes all
3 deletes list object elements but list
too. object still exists.

Difference between append( ), extend( ) and insert( ) :

S. append( ) extend( ) insert


No. ()
Adds an element at the
1 Adds single element in the end Add a list in the end of
of the list. the another list specified
positi
on.(Anywhere in the list)

2 Takes one element as argument Takes one list Takes two arguments,
asargument position and element.

The length of the list


3 The length of the list The length of the list
willincrease by 1. will increase by the will increase by 1.
length of inserted list.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

ACCESSING ELEMENTS OF NESTED LISTS


Example
>>> L=["Python", "is", "a", ["modern", "programming"], "language", "that", "we", "use"]
>>> L[0][0] 'P'
>>> L[3][0][2]
'd'
>>> L[3:4][0]
['modern', 'programming']
>>> L[3:4][0][1]
'programming'
>>> L[3:4][0][1][3]
'g'
>>> L[0:9][0]
'Python'
>>> L[0:9][0][3]
'h'
>>> L[3:4][1]
IndexError: list index out of range

Programs related to lists in python


Write a program to find the minimum and maximum number in a list.
L=eval(input("Enter the elements: "))
n=len(L)
min=L[0] max=L[0]
for i in range(n): if min>L[i]:
min=L[i] if max<L[i]:
max=L[i]
print("The minimum number in the list is : ", min)
print("The maximum number in the list is : ", max)
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Program-2 Find the second largest number in a list.


L=eval(input("Enter the elements: "))
n=len(L) max=second=L[0] for i in range(n):
if max<L[i]>second: max=L[i] seond=max
print("The second largest number in the list is : ", second)

Program to search an element in a list. (Linear Search).


L=eval(input("Enter the elements: "))
n=len(L)
item=eval(input("Enter the element that you want to search : "))
for i in range(n):
if L[i]==item:
print("Element found at the position :", i+1) break
else:
print("Element not Found")

Output
Enter the elements: 56,78,98,23,11,77,44,23,65
Enter the element that you want to search : 23
Element found at the position : 4

DICTIONARY IN PYTHON
INTRODUCTION
• Dictionary is a collection of elements which is unordered, changeable and indexed.
• Dictionary has keys and values.
• Doesn’t have index for values. Keys work as indexes.
• Dictionary doesn’t have duplicate member means no duplicate key.
• Dictionaries are enclosed by curly braces { }
• The key-value pairs are separated by commas ( , )
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

• A dictionary key can be almost any Python type, but are usually numbers or strings.
• Values can be assigned and accessed using square brackets [ ].

CREATING A DICTIONARY
Syntax:
dictionary-name = {key1:value, key2:value, key3:value, keyn:value}
Example
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
>>> D = { } #Empty dictionary

>>> D
{}
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
{'Maths': 81, 'Chemistry': 78, 'Physics': 75, 'CS': 78} # there is no guarantee that # elements in
dictionary can be accessed as per specific order.

Note: Keys of a dictionary must be of immutable types, such as string, number, tuple.
Example
>>> D1={[2,3]:"hello"}
TypeError: unhashable type: 'list'

A. Creating a dictionary using dict( ) Constructor:


• use the dict( ) constructor with single parentheses:
>>> marks=dict(Physics=75,Chemistry=78,Maths=81,CS=78)
>>> marks
{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
• In the above case the keys are not enclosed in quotes and equal sign is used for assignment
rather than colon.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

B. dict ( ) constructor using parentheses and curly braces:

>>> marks=dict({"Physics":75,"Chemistry":78,"Maths":81, "CS":78})


>>> marks
{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}

C. dict( ) constructor using keys and values separately:


>>> marks=dict(zip(("Physics","Chemistry","Maths","CS"),(75,78,81,78)))
>>> marks
{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
In this case the keys and values are enclosed separately in parentheses and are given as argument to
the zip( ) function. zip( ) function clubs first key with first value and so on.

[Link]( ) constructor using key-value pairs separately: Example-a


>>> marks=dict([['Physics',75],['Chemistry',78],['Maths',81],['CS',78]])
# list as argument passed to dict( ) constructor contains list type elements.
>>> marks
{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}

Example-b
>>> marks=dict((['Physics',75],['Chemistry',78],['Maths',81],['CS',78]))
# tuple as argument passed to dict( ) constructor contains list type elements
>>> marks
{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}

Example-c
>>> marks=dict((('Physics',75),('Chemistry',78),('Maths',81),('CS',78)))
# tuple as argument to dict( ) constructor and contains tuple type elements
>>> marks
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

{'Physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}

ACCESSING ELEMENTS OF A DICTIONARY:


Syntax
dictionary-name[key]

Example
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> marks["Maths"]
81
>>> marks["English"] #Access a key that doesn’t exist causes an error
KeyError: 'English'
>>> [Link]( ) #To access all keys in one go dict_keys(['physics', 'Chemistry', 'Maths', 'CS'])
>>> [Link]( ) # To access all values in one go dict_values([75, 78, 81, 78])

Lookup
A dictionary operation that takes a key and finds the corresponding value, is called lookup.
TRAVERSING A DICTIONARY
Syntax
for <variable-name> in <dictionary-name>: statement
Example:
>>> for i in marks:
print(i, ": ", marks[i])
OUTPUT
physics : 75
Chemistry : 78
Maths : 81
CS : 78
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

CHANGE AND ADD THE VALUE IN A DICTIONARY


Syntax
dictionary-name[key]=value

Example
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}
>>> marks['CS']=84 #Changing a value
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}
>>> marks['English']=89 # Adding a value
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}
DELETE ELEMENTS FROM A DICTIONARY

There are two methods to delete elements from a dictionary:

(i) using del statement


(ii) using pop( ) method

1. Using del statement


Syntax
del dictionary-name[key]

Example
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}
>>> del marks['English']
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}

[Link] pop( ) method


It deletes the key-value pair and returns the value of deleted element.
Syntax
[Link]( )
Example
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}
>>> [Link]('Maths') 81
CHECK THE EXISTANCE OF A KEY IN A DICTIONARY
To check the existence of a key in dictionary, two operators are used:

(i) in : it returns True if the given key is present in the dictionary, otherwise False.
(ii) not in : it returns True if the given key is not present in the dictionary, otherwise
False.

Example
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> 'Chemistry' in marks True
>>> 'CS' not in marks False
>>> 78 in marks # in and not in only checks the existence of keys not values False
However, if you need to search for a value in dictionary, then you can use in operator with the
following syntax:
Syntax
value in dictionary-name. values( )
Example
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> 78 in [Link]( ) True
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

PRETTY PRINTING A DICTIONARY

What is Pretty Printing?


• To print a dictionary in more readable and presentable form.
• For pretty printing a dictionary you need to import json module and then you can use
dumps( ) function from json module.

Example
>>> print([Link](marks, indent=2))

OUTPUT
{
"physics": 75,
"Chemistry": 78,
"Maths": 81,
"CS": 78
}
dumps( ) function prints key:value pair in separate lines with the number of spaces which is the value
of indent argument.
COUNTING FREQUENCY OF ELEMENTS IN A LIST USING DICTIONARY
Steps:
1. import the json module for pretty printing
2. Take a string from user
3. Create a list using split( ) function
4. Create an empty dictionary to hold words and frequency
5. Now make the word as a key one by one from the list
6. If the key not present in the dictionary then add the key in dictionary and count
7. Print the dictionary with frequency of elements using dumps( ) function.
Program
import json sentence=input("Enter a string: ")
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

L = [Link]()
d={ }
for word in L: key=word
if key not in d: count=[Link](key)
d[key]=count
print("The frequqency of elements in the list is as follows: ") print([Link](d,indent=2))

DICTIONARY FUNCTIONS
Consider a dictionary marks as follows:
>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }

S. Function Description Example


Name
No.

1 len( ) Find the length of >>> len(marks) 4


a dictionary.
Syntax:
len (dictionary-name)

2 clear( ) removes all >>> [Link]( )


elements from
the dictionary Syntax:
>>> marks
[Link]( )

{}

3. get( ) Returns value of a key.


Syntax
[Link](key) >>> [Link]("physics") 75
Note: When key does not exist it returns no value without any error.
>>> [Link]('Hindi')
>>>
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

4 items( ) returns all elements as a sequence of (key,value) tuples in any order.


Syntax
[Link]( ) >>> [Link]()

dict_items([('physics', 75), ('Chemistry',


78), ('Maths', 81), ('CS', 78)])
Note: You can write a loop having two variables to access key: value pairs.
>>> seq=[Link]()
>>> for i, j in seq:
print(j, i)
OUTPUT:
75 physics
78 Chemistry
81 Maths
78 CS
5 keys( ) Returns all keys in the form of a list.
Syntax
[Link]( ) >>> [Link]()
dict_keys (['physics', 'Chemistry', 'Maths', 'CS'])
6 values( ) Returns all values in the form of a list.
Syntax
[Link]( ) >>> [Link]() dict_values([75, 78, 81, 78])
7 update( ) Merges two dictionaries. Already present elements are override.
Syntax
[Link](dictionary2)
Example
>>> marks1 = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> marks2 = { "Hindi" : 80, "Chemistry" : 88, "English" : 92 }
>>> [Link](marks2)
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

>>> marks1
{'physics': 75, 'Chemistry': 88, 'Maths': 81, 'CS': 78, 'Hindi': 80, 'English': 92}
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

UNIT – III
FILES AND EXCEPTIONS:
Introduction to File Input and Output - Writing Structures to a File - Using loops to process files Processing
Records - Exception. Classes and Objects in Python: Overview of OOP – Data encapsulation –
Polymorphism – Class definition – Creating objects – Inheritance – Multiple inheritances – Method
overriding – Data encapsulation – Data hiding.

Introduction
The file handling plays an important role when the data needs to be stored permanently into the
file. A file is a named location on disk to store related information. We can access the stored information
(non-volatile) after the program termination.
• File handling functions are creating a file, writing into the file, reading the file, and updating
the file.
• Files are generally used to store information fetched from the programs.
• Files are of 2 types such as normal text files and binary files.
• Text files have a terminator for each line with a special character in python.
• Binary files are written in binary languages i.e., 0s and 1s, which does not require a terminator.
• As these are binary files data is stored in a file after converting it into machine-understandable
binary language.
Access Modes for using files
Access modes here are used to open a file in that particular mode and then access with the
specified mode.
Access modes in python are,
1. Read Only (‘r’): Opening a file for only reading, and a file pointer positioned at
the beginning ofthe file.
If the file selected does not exist, it returns an error.
2. Read and Write (‘r+’): Opening a file for reading and writing, the file pointer is
positioned at thebeginning of the file.
If the file selected does not exist, it returns an error.
3. Write Only (‘w’): Opening the file for writing content to the file, the file
pointer position at thebeginning of the file.
If the file selected does not exist, it returns an error.
4. Write and Read (‘w+’): Opening a file for reading and writing, the file
pointer is positioned atthe beginning of the file.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

5. Append Only (‘a’): Opening the file for writing, the file pointer is positioned
at the end of the file.
If the file selected does not exist, it creates a file and uses it.
6. Append and Read(‘a+’): Opening the file for reading and writing, the file
pointer is positioned atthe end of the file.
If the file selected does not exist, it creates a file and uses it.
7. Binary (‘b’): Opening the file in binary mode.
File operations

Opening the File in Python


Python has a built-in function for opening a file that is open() function.
Syntax:
f = open(“file name”, “Access mode”)
Example:
file =
open(“C:/PythonPrograms/[Link]”)
We can also specify the mode of
the file,
Opening the file in write mode,
file = open(“C:/PythonPrograms/[Link]”, ‘w’)
Opening the file in read mode,
file = open(“C:/PythonPrograms/[Link]”, ‘r’)
Opening the file in read and write in binary mode,
file =open(“C:/PythonPrograms/[Link]”, ‘r+b’)
We can also write the statement as
file = open(“C:/PythonPrograms/[Link]”, mode= ‘r+b’)

And it is recommended to write encoding type,


file = open(“C:/PythonPrograms/[Link]”, mode= ‘r+b’, encoding= ‘utf-8’)
Closing the file in python:
Python has a built-in function for closing a file that is
close() function.
Syntax:
[Link]()
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

#file is created file name.


Example:
file = open(“C:/PythonPrograms/[Link]”)
[Link]()
Closing a file using the close() method in python.
We can also write it in a safe way using try and
finally blocks,

try:
file = open(“[Link]”, encoding = ‘utf-8’)
finally:
[Link]()
This way helps us from occurring exceptions.
We also have another way to close the file using with
statement as,

with open (“[Link]”, encoding = ‘utf-8’) as f:


#executable statements
Writing to the file in Python
Python has a built-in function for writing a file which is the write()
function.
Syntax:
[Link]()
#f is file created file
name
Example:
with open(“[Link]”, encoding = ‘utf-8’) as f:
[Link](“This is file created using python code”)
[Link](“This is next line of file”)
If [Link] exists in the specified location, it writes the specified content in the
specified [Link] [Link] does not exist in the specified location, it shows an error.
writelines() method is used to write items in a list. The newline characters (“\n”)
are part of thestring.
L = [“This is a created file. \n”, This file is taken as
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

an example. \n”]F = open(“[Link]”, “w”)


[Link](L)
[Link]()
Output:
This is a created file.
This file is taken as an example.

Reading the file in Python


Python has a built-in function for Reading a file that is the
read() function.
Syntax:
[Link](size to read) #f is file created
file nameExample:
with open(“[Link]”, encoding = ‘utf-8’) as f:
[Link](10) # reads the first 10 contents of the file
If [Link] exists in the specified location, it reads the specified content in the specified file.
If [Link] does not exist in the specified location, it shows an error.

For reading entire file write,

print([Link]())
We can read a file line-wise
using a for loop,for i in f:
print(i, end= ‘ ’)# reads content line by line.
We can read a single line using readline()
[Link]()
Used to read individual lines.
Appending to the file in Python
For appending the content to the file we open the file using the open() method in
append(a) modeand then use the write() method to write content into the file.
F = open(“[Link]”, ‘a’)
[Link](“Appending this sentence to the file”)
[Link]()

For every python program, when we use the files, the closing of the
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

file must usethe close() method.


We can also open the file using the open() method in append plus(a+) mode
and then usethe write() method to write content into the file.
F = open(“[Link]”, ‘a+’)
[Link](“Appending this sentence to the file”)
[Link]()
This writes or appends the content to the file and then also reads the file and at
last closes thefile.
We also have some methods in file handling in python, seek() method and
the tell() [Link]() method is used to change the position of the file
pointer.
tell() method is used to tell the current position of the file [Link] methods such as detach(),
fileno(), flush(), isatty().
Use write() to Write to File in Python
The first step to write a file in Python is to open it, which means you can access it through
ascript. There are two ways to open a file. The first one is to use open(), as shown below:
# open the file in the write mode
f = open('[Link]', 'w')
However, with this method, you need to close the file yourself by calling the close() method:
# close the file
[Link]()
It is shorter to use the with statement, as we do not need to call the close() method.
This is the method we’ll use in this tutorial:
with open("[Link]", "w") as file:
The above line of code will open [Link] and will assign the file handler to the variable
called file.
We can then call the write() method to modify our file
[Link]’s run an example:
[Link]("Python is awesome!")
Once this command has been executed, we want to read the file to see if it has been updated.
We
need to call the read() method, as shown below:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

# Open and read the file after writing:


with open("[Link]", "r") as file:
print([Link]())
It’s important to note that the parameters in the open() function will decide where
the write() method will be active.
EXCEPTION
An exception is an event, which occurs during the execution of a program that disrupts the normal
flow of the program's instructions. In general, when a Python script encounters a situation that it cannot
cope with, it raises an exception. An exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception immediately
otherwise it terminates and quits.
HANDLING AN EXCEPTION
If you have some suspicious code that may raise an exception, you can defend your program by
placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by
a block of code which handles the problem as elegantly as possible.
Syntax
Here is simple syntax of
try....except...else blocks −try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute
this [Link] ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Here are few important points about the above-mentioned syntax
• A single try statement can have multiple except statements. This is useful when the try
block contains statements that may throw different types of exceptions.
• You can also provide a generic except clause, which handles any exception.
• After the except clause(s), you can include an else-clause. The code in the else-
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

blockexecutes if the code in the try: block does not raise an exception.
The else-block is a good place for code that does not need the try: block's protection.
Example
This example opens a file, writes content in the, file and comes out
gracefully because there isno problem at all −
#!/usr/bin/python
try:
fh = open("testfile", "w")
[Link]("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
[Link]()

Output
This produces the following result −
Written content in the file successfully
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Python Objects and Classes


Python is an object-oriented programming language. Unlike procedure-oriented
programming,where the main emphasis is on functions, object-oriented programming stresses on
objects.
An object is simply a collection of data (variables) and methods (functions) that act on t hose
data. Similarly, a class is a blueprint for that object.
We can think of a class as a sketch (prototype) of a house. It contains all the details about thefloors,
doors, windows, etc. Based on these descriptions we build the house. House is the object. As many houses can be
made from a house's blueprint, we can create many objects from a [Link] object is also called an instance of a
class and the process of creating this object iscalled instantiation.

Defining a Class in Python


Like function definitions begin with the def keyword in Python, class definitions
begin witha class keyword.
The first string inside the class is called docstring and has a brief description
of the [Link] not mandatory, this is highly recommended.
Here is a simple class definition.
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
A class creates a new local namespace where all its attributes are defined. Attributes may be data
or functions.
There are also special attributes in it that begins with double underscores . For
example, doc gives us the docstring of that class.
As soon as we define a class, a new class object is created with the same name. This class object
allows us to access the different attributes as well as to instantiate new objects of that class.
It allows us to access the different attributes as well as to instantiate new objects of that class.
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

# Output: 10
print([Link])
# Output: <function [Link]>
print([Link])
# Output: "This is a person class"
print(Person. doc )

Run Code
Output

10
<function [Link] at 0x7fc78c6e8160>
This is a person class

Creating an Object in Python


We saw that the class object could be used to access different attributes.
It can also be used to create new object instances (instantiation) of that class. The procedure to
create
an object is similar to a function call.

>>> harry = Person()

This will create a new object instance named harry . We can access the attributes of objects using
the object name prefix.
Attributes may be data or method. Methods of an object are corresponding functions of that class.

This means to say, since is a function object (attribute of class), will be


a method
object.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

class Person:
"This is a person class"
age = 10
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
# create a new object of Person
# Output: <function [Link]>
print([Link])
# Output: <bound method [Link] of < main .Person object>>
print([Link])
# Calling object's greet() method #
Output: Hello
[Link]()

Output
<function [Link] at 0x7fd288e4e160>
<bound method [Link] of < main .Person object at 0x7fd288e9fa30>>
Hello

You may have noticed the self parameter in function definition inside the class but we
called the method simply as [Link]() without any arguments. It still worked.
This is because, whenever an object calls its method, the object itself is passed as the first
argument. So, [Link]() translates into [Link](harry).
In general, calling a method with a list of n arguments is equivalent to calling the corresponding
function with an argument list that is created by inserting the method's object before the first
argument.
For these reasons, the first argument of the function in class must be the object itself. This is
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

conventionally called self. It can be named otherwise but we highly recommend to follow the
convention.
Now you must be familiar with class object, instance object, function object, method object and
their differences.
Constructors in Python
Class functions that begin with double underscore _-are called special functions as they have
special meaning.
Of one particular interest is the __init__() new object of that class is instantiated. function. This
special function gets called whenever a new object of that class is instantiated.

This type of function is also called constructors in Object Oriented Programming (OOP). We
normally use it to initialize all the variables.

class ComplexNumber:
def init (self, r=0, i=0):
[Link] = r
[Link] = i
def get_data(self):
print(f'{[Link]}+{[Link]}j')
# Create a new ComplexNumber object
num1 = ComplexNumber(2, 3)
# Call get_data() method
# Output: 2+3j
num1.get_data()
# Create another ComplexNumber object
# and create a new attribute 'attr'
num2 = ComplexNumber(5)
[Link] = 10
# Output: (5, 0, 10)
print(([Link], [Link], [Link]))
# but c1 object doesn't have attribute 'attr'
# AttributeError: 'ComplexNumber' object has no attribute 'attr'
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

print([Link])

Run Code
Output

2+3j
(5, 0, 10)
Traceback (most recent call last):

In the above example, we defined a new class to represent complex numbers. It has two
functions, init () to initialize the variables (defaults to zero) and get_data() to display the
number properly.

An interesting thing to note in the above step is that attributes of an object can be created on the
fly. We created a new attribute attr for object num2 and read it as well. But this does not create
that attribute for object num1.

Deleting Attributes and Objects


Any attribute of an object can be deleted anytime, using the del statement. Try the following on
On the python cell to see the output.
>>> num1 = ComplexNumber(2,3)
>>> del [Link]
>>> num1.get_data()
Traceback (most recent call last):
...
AttributeError: 'ComplexNumber' object has no attribute 'imag'

>>> del ComplexNumber.get_data


>>> num1.get_data()
Traceback (most recent call last):
...
AttributeError: 'ComplexNumber' object has no attribute 'get_data'

We can even delete the object itself, using the del statement.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

>>> c1 = ComplexNumber(1,3)
>>> del c1
>>> c1
Traceback (most recent call last):
...
NameError: name 'c1' is not defined

Actually, it is more complicated than that. When we do c1 = ComplexNumber(1,3), a new


instance object is created in memory and the name binds with it.
On the command del c1, this binding is removed and the name c1 is deleted from the
corresponding namespace. The object however continues to exist in memory and if no
other name is bound to it, it is later automatically destroyed.

Python OOPs Concepts


Like other general-purpose programming languages, Python is also an object-
oriented language since its beginning. It allows us to develop applications using
an Object-Oriented [Link] Python, we can easily create and use classes and
objects.
An object-oriented paradigm is to design the program using classes and
objects. The object isrelated to real-word entities such as book, house, pencil,
etc. The oops concept focuses onwriting the reusable code. It is a widespread
technique to solve the problem by creating objects. Major principles of object-
oriented programming system are given below.
• Class
• Object
• Method
• Inheritance
• Polymorphism
• Data Abstraction
• Encapsulation
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Class
The class can be defined as a collection of objects. It is a logical entity that has
some specific attributes and methods. For example: if you have an employee class,
then it should contain an attribute and method, i.e. an email id, name, age, salary,
etc.

Syntax

class ClassName:
<statement-1>
.
.
<statement-N>

Object
• The object is an entity that has state and behavior. It may be any real-world
object like themouse, keyboard, chair, table, pen, etc.

• Everything in Python is an object, and almost everything has attributes and


methods. All functions have a built-in attribute doc , which returns the docstring
defined in the function source code.
• When we define a class, it needs to create an object to allocate the memory.
Consider the following example.
Example:
class car:
def init (self,modelname, year):
[Link] = modelname
[Link] = year
def display(self):
print([Link],[Link]
)
c1 = car("Toyota", 2016)
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

display c1
Toyota 2016
In the above example, we have created the class named car, and it has two attributes modelname and
[Link] have created a c1 object to access the class attribute. The c1 object will allocate memory for these
values. We will learn more about class and object in the next tutorial.
Method
The method is a function that is associated with an object. In Python, a method is not unique to
class instances. Any object type can have methods.
Inheritance
Inheritance is the most important aspect of object-oriented programming, which simulates the real-
world concept of inheritance. It specifies that the child object acquires all the properties and behaviors of
the parent object.
By using inheritance, we can create a class which uses all the properties and behavior of another class.
The new class is known as a derived class or child class, and the one whose properties are acquired is
known as a base class or parent class.
It provides the re-usability of the code.
Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many, and morph means
shape. By polymorphism, we understand that one task can be performed in different ways. For example -
you have a class animal, and all animals speak. But they speak differently. Here, the
"speak" behavior is polymorphic in a sense and depends on the animal. So, the abstract "animal" concept
does not actually "speak", but specific animals (like dogs and cats) have a concrete implementation of the
action "speak".
Encapsulation
Encapsulation is also an essential aspect of object-oriented programming. It is used to restrict
access to methods and variables. In encapsulation, code and data are wrapped together within a single unit
from being modified by accident.
Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are nearly synonyms
because data abstraction is achieved through encapsulation.
Abstraction is used to hide internal details and show only functionalities. Abstracting something
means to give names to things so that the name captures the core of what a function or a whole program
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

does.
Object-oriented vs. Procedure-oriented Programming languages
The difference between object-oriented and procedure-oriented programming is given below:

Object-oriented Programming Procedural Programming


Index
1. Object-oriented programming is the Procedural programming uses a list of
problem-solving approach and used instructionsto do computation step by step.
where computation is done by using
objects.

2. It makes the development In procedural programming, It is not easy to


andmaintenance easier. maintain the codes when the project becomes
lengthy.

3. It simulates the real world entity. So It doesn't simulate the real world. It works on
real- world problems can be easily step by step instructions divided into small
solved through oops. parts called functions.

4. It provides data hiding. So it is more Procedural language doesn't provide any


secure than procedural languages. properway for data binding, so it is less
You cannot access private data from secure.
anywhere.

5. Example of object-oriented Example of procedural languages are: C,


programming languages is C++, Java, Fortran,Pascal, VB etc.
.Net, Python, C#, etc.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

UNIT – IV DATA MANIPULATION TOOLS & SOFTWARES


Numpy: Installation - Ndarray - Basic Operations -Indexing, Slicing, and Iterating - Shape
Manipulation - Array Manipulation - Structured Arrays -Reading and Writing Array Data on Files.
Pandas: The pandas Library: An Introduction - Installation -Introduction to pandas Data
Structures - Operations between Data Structures - Function Application and Mapping - Sorting
and Ranking - Correlation and Covariance - ―Not a Number Data - Hierarchical Indexing and
Leveling – Reading and Writing Data: CSV or Text File - HTML Files – Microsoft Excel Files.

What is NumPy?

• NumPy is a Python library used for working with arrays.

• It also has functions for working in domain of linear algebra, fourier transform, and matrices.

• NumPy was created in 2005 by Travis Oliphant. It is an open source project and you can use it
freely.

• NumPy stands for Numerical Python.

• In Python we have lists that serve the purpose of arrays, but they are slow to process.

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

There are the following advantages of using NumPy for data analysis.

1. NumPy performs array-oriented computing.


2. It efficiently implements the multidimensional arrays.
3. It performs scientific computations.
4. It is capable of performing Fourier Transform and reshaping the data stored in multidimensional
arrays.
5. NumPy provides the in-built functions for linear algebra and random number generation

NumPy Getting Started


Installation of NumPy
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

If you have Python and PIP already installed on a system, then installation of NumPy is very easy.

Install it using this command:

C:\Users\Your Name>pip install numpy


If this command fails, then use a python distribution that already has NumPy installed like, Anaconda,
Spyder etc.

Import NumPy
Once NumPy is installed, import it in your applications by adding the import keyword:
import numpy

Now NumPy is imported and ready to use.


import numpy

arr = [Link]([1, 2, 3, 4, 5])

print(arr)

NumPy as np
NumPy is usually imported under the np alias.
alias: In Python alias are an alternate name for referring to the same thing.
Create an alias with the as keyword while importing:
import numpy as np
Now the NumPy package can be referred to as np instead of numpy.
Example
import numpy as np

arr = [Link]([1, 2, 3, 4, 5])

print(arr)
Ndarray
An Ndarray is a multidimensional array of objects all of the same type. In Python, this is typically
a NumPy array. The Ndarray allows for efficient operations on the data elements without creating
temporary copies.
The N-dimensional array (ndarray)
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

An ndarray is a (usually fixed-size) multidimensional container of items of the same type and size.
The number of dimensions and items in an array is defined by its shape, which is a tuple of N non-negative
integers that specify the sizes of each dimension. The type of items in the array is specified by a separate
data-type object (dtype), one of which is associated with each ndarray.
As with other container objects in Python, the contents of an ndarray can be accessed and modified
by indexing or slicing the array (using, for example, N integers), and via the methods and attributes of the
ndarray.
Different ndarrays can share the same data, so that changes made in one ndarray may be visible in
another. That is, an ndarray can be a “view” to another ndarray, and the data it is referring to is taken care
of by the “base” ndarray. ndarrays can also be views to memory owned by Python strings or objects
implementing the buffer or array interfaces.
Example
A 2-dimensional array of size 2 x 3, composed of 4-byte integer elements:
>>> x = [Link]([[1, 2, 3], [4, 5, 6]], np.int32)
>>> type(x)
<class '[Link]'>
>>> [Link]
(2, 3)
>>> [Link]
dtype('int32')
The array can be indexed using Python container-like syntax:
>>> # The element of x in the *second* row, *third* column, namely, 6.
>>> x[1, 2]
6

Basic Slicing and Advanced Indexing in NumPy Python


Indexing of ndarrays can be done using the standard python x[obj] syntax, where x is the array
and obj the selection.
There are three kinds of indexing available −
• field access
• basic slicing
• advanced indexing

In this section, we are going to mainly concentrate on basic slicing & advanced indexing.
We can divide advanced indexing into two parts −
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

• Integer array indexing


• Boolean indexing Basic Slicing
Python basic concept of slicing is extended in basic slicing to n dimensions. As with python slice object
which is constructed by giving a start, stop & step parameters to slice function. To get specific output, the
slice object is passed to the array to extract a part of an array.
Example 1
import numpy as np
arr = [Link](25)
s = slice(2, 21, 4)
print (arr[s])

[ 2 6 10 14 18]
In the above example, we first created a ndarray object (arr) using arange() function. Then a slice object
is created by assigning start, stop and step value to it (s). When we passed the slice object to the ndarray,
we get part (slice) of the array starting with index 2 up to 21 with a step of 4.

# Another way to write above program


import numpy as np
arr = [Link](25)
s = arr[Link]
print (s)
Output
[ 2 6 10 14 18]

Slice single item


#Slice single item from an array
import numpy as np
arr = [Link](10)
s = arr[9]
print(s)

Output
9
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Slice items starting from index


#slice item starting from index
import numpy as np
arr = [Link](10)
s = arr[3:]
print(s)

Output
[3 4 5 6 7 8 9]

Slice item between indexes


#slice item between indexes
import numpy as np
arr = [Link](10)
s = arr[3: 7]
print(s)

Output
[3 4 5 6]

Above two methods will be applied to multi-dimensional ndarray too, like below –
#slice item between indexes
import numpy as np
arr = [Link]([[[1],[2],[3]], [[4],[5],[6]], [[7], [8], [9]]])
s = arr[1:]
print(s)

Output
[[[4]
[5]
[6]]
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

[[7]
[8]
[9]]]

Advanced indexing Integer array indexing:


Let’s create a simple array with integers
arr=[Link]([[1,2],[3,4],[5,6]])
print(arr)

Output
[[1 2]
[3 4]
[5 6]]

Let’s try to select a specific element from the array, like elements with row index [0, 1, 2] and column
index [1, 0, 1] from the multidimensional ndarray
import numpy as np
arr=[Link]([[1,2],[3,4],[5,6]])
s = arr[[0, 1, 2],[1, 0, 1]]
print(s)
Output
[2 3 6]

Selecting with 0 indexes will give you first row −


>>> arr=[Link]([[1,2],[3,4],[5,6]])
>>> print(arr[0]) [1 2]

Similarly, we can select a single item from the array, for example- select the 1 as row index and 1 as the
column index element which gives an array value of 4.
>>> print(arr[[1], [1]])
[4]
We can arithmetic operation like addition and returns the value of a particular index after performing
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

the addition.
>>> print(arr[[1], [1]]+ 1)
[5]
As we can see the index value is incremented by 1 but the actual array remains the same.
>>> arr array([[1, 2],
[3, 4],
[5, 6]])
But we can change the values of the array and returns the new copy of an array.
>>> arr[[1], [1]] +=1
>>> arr array([[1, 2],
[3, 5],
[5, 6]])
Boolean indexing
We used boolean indexing when the result is going to be the outcome of boolean operations.
>>> arr=[Link]([[0,1,2], [3,4,5], [6,7,8], [9,10,11]])
>>> arr
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
Returns the values which are 1.
>>> arr[arr == 1] array([1])
Returns the values which are even numbers
>>> arr[arr %2 == 0]
array([ 0, 2, 4, 6, 8, 10])

What is shape Manipulation of arrays in Python?


Shape manipulation is a technique by which we can manipulate the shape of a NumPy array and
then convert the initial array into an array or matrix of required shape and size. This may include
converting a one-dimensional array into a matrix and vice-versa and finding transpose of the matrix by
using different functions of the NumPy module. Suppose we have an array an of
length 15.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

import numpy as np
a=[Link]((15))
print(a)
Output:
[0.45571673, 0.60686929, 0.34301217, 0.68924335, 0.87628601,
0.81087616, 0.22130314, 0.08402535, 0.75766745, 0.97000277,
0.1947358 , 0.60662285, 0.87718557, 0.74830521, 0.92319394]

Introduction to Python Array Functions


Array functions in python are defined as functions that will have arrays as parameters to the
function and perform set of instructions to perform a particular task on input parameters to achieve a
particular task is called array functions in python. Array functions will take an array as an argument, it
will be implemented in such a way that it will operate on a different number of objects.
[Link](dataype, valuelist)
The above function, an array is used to create an array in python which accepts parameters as data type
and value-list where data type is the type of the value-list like integer, decimal, float, etc. The value-list
is a list of values of that particular data type.
Example:
Code:
a=array(‘i’,[1,2,3,4])
print(a)
The above example will create an array of ‘integer’ data type with values 1, 2, 3, 4 as its elements.
Output:

[Link](pos, value)
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

The above function, insert() is used to insert an element to the array at a specific index or position.
It will take pos, and value as its parameters where pos variables tell the position and value is the value
need to insert into array.

Example:

Code:

[Link](2,9)
print(“Array after inserting 9 is”, a)

The above example will add a value 9 to the array ar at the index position 2 and the remaining
elements will be arranged appropriately.

Output:

[Link](value)
The above function, append() is used to add value or append a value to the existing array in the
end. It will take the value which we want to add as an argument.

Example:
Code:
[Link](6)
print(ar)

The above example will add a value 6 to the end of the array ar which is created in the previous example.

Output:

[Link](value)
The above function, remove() will also remove the given element from the array. It will take value
to remove as an argument and removes the element from the array and it won’t display the element.

Example:
Code:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

[Link](9)
print(a)

The above examples remove element 9 from the array ar and we will see list of all available elements in
the array.

Output:

[Link](arr)
The above function, extend() is used to add an array of values at the end of the existing array
created. It will take an array of values or an array as its input argument.

Example:
Code:

[Link]([7,5,8])
print(a)

In the above example, we will add an array of values 7, 5, 8 to the end of the existing array ar.

Output:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

[Link]()
The above function, pop() is used to remove an element from the array. It can take the argument
as a position of the element we want to remove or by default it removes the element at the last index.

Example:
Code:

[Link]()
It removes last element in the array and displays element.

Code:

[Link](4)
It removes the element at 4th index position in the array and displays element

Output:

[Link](value)
The above function, index() will return the first position of the value in the array, it will take the value as
an argument to it and returns the first occurrence position of the value in the array as output.

Example:
Code:

[Link](2)

The above example will return the position of the element 2 in the array ar as output.
Output:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

[Link]()
The above function, reverse() will reverse the array and returns the reversed array as an output of
it. It doesn’t take any argument.

Example:
Code:

[Link]()
print(“Array after reverse is:”,a)

The above example will reverse the array ar and stores the result in ar. The print statement will display
the reversed array.

output

[Link](list)
The above function, fromlist() is used to add a list to the end of the array. It will take a list as its
input argument and the output of this function is an array with list appended at the end of the array.

Example:
Code:

li=[10,9,8] [Link](li)
print(“Array after appending the list is:”,a)

In the above example, we have created a list with a list of values of the same data type as an array
and we called the function fromlist() to add the list to the array and the output is an array with list elements
added at the end of the array.

Output:

[Link](value)
The above function, count() will tell the total number of occurrences of the given value in the
array. It will take a value as an argument to it to know the total number of occurrences.

Example:
Code:

[Link]([2,1,3,2,1])
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

[Link](2)

In the above example, we have extended the array “a” with values 2, 1, 3, 2, 1 and we are trying
to find the count of value 2 in the array after extending operation. It will give the number of occurrences
of value 2 in the array.

Output:

Reading and Writing Array Data on Files:


• While working with data entry and data collection for training models, we come across .data files.
• This is a file extension used by a few software in order to store data, one such example would be
Analysis Studio, specializing in statistical analysis and data mining.
• Working with the .data file extension is pretty simple and is more or less identifying the way the
data is sorted, and then using Python commands to access the file accordingly.

What is a .data file?


• .data files were developed as a means to store data.
• A lot of the times, data in this format is either placed in a comma separated value format or a tab
separated value format.
• Along with that variation, the file may also be in text file format or in binary. In which case, we
will be needing to access it in a different method.
• We will be working with .csv files for this article, but let us first identify whether the content of
the file is in text, or in binary.
Identifying data inside .data files
• .data files come in two different variations, and the file itself is either in the form of text or in
binary.
• In order to find out which one it belongs to, we’ll need to load it up and test it out for ourselves.
Let’s get started!
[Link]: Text file
• .data files may mostly exist as text files, and accessing files in Python is pretty simple.
• Being pre-built as a feature included in Python, we have no need to import any module in order to
work with file handling.
• That being said, the way to open, read, and write to a file in Python is as such: # reading from the
file
file = open("[Link]", "r") [Link]()
[Link]()
[Link]("Chocolate Chip")
[Link]()
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

[Link]: Binary File


• The .data files could also be in the form of binary files. This means that the way we must access
the file also needs to change.
• We will be working with a binary mode of reading and writing to the file, in this case, the mode
is rb, or read binary.

# reading from the file


file = open("[Link]", "rb") [Link]()
[Link]()
# writing to the file
file = open("[Link]", "wb") [Link]("Oreos")
[Link]()

• File operations are relatively easy to understand in Python and are worth looking into if you wish
to see the different file access modes and methods to access them.
• Either one of these approaches should work, and should provide you with a method to retrieve the
information regarding the contents stored inside the .data file.
• Now that we know which format the file is present in, we can work with pandas to create a
DataFrame for the csv file.

[Link] Pandas to read .data files


A simple method to extract info from these files after checking the type of content provided would be to
simply use the read_csv() function provided by Pandas.
import pandas as pd
# reading csv files
data = pd.read_csv('[Link]', sep=",")
print(data)
# reading tsv files
data = pd.read_csv('[Link]', sep="\t")
print(data)
This method also converts the data into a dataframe automatically
Python Pandas - Introduction
• Pandas is an open-source Python Library providing high-performance data manipulation and
analysis tool 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.
• Prior to Pandas, Python was majorly used for data munging and preparation. It had very little
contribution towards 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,
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

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.
Key Features of Pandas
• Fast and efficient DataFrame object with default and customized indexing.
• Tools for loading data into in-memory data objects from different file formats.
• Data alignment and integrated handling of missing data.
• Reshaping and pivoting of date sets.
• 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.

Introduction to pandas Data Structures:


To add the Pandas to Python, you need to write the code below to the terminal and install the Pandas.
pip install pandas
The Pandas library in Python deals with 3 data types:
• Series
• DataFrame
• Panel
These data structures are built on numpy. This means they are fast.
Dimension & Description
Let’s liken this to matryoshkas. What is matryoshkas logic? The nesting of shapes in decreasing
dimensions. The logic is the same here. It includes the largest, that is, other sub-dimensions with the
largest size.
Creating and processing arrays of two or more dimensions is tedious, load is placed on the user to take
into account the direction of the data set when writing functions. However, using the pandas data
structures, the user’s mental effort is reduced. For example, with tabular data (DataFrame), it is more
semantically useful to think of index (rows) and columns instead of axis 0 and axis 1
PYTHON Pandas Series
The series is a one-dimensional tagged array that can hold any type of data (integer, string, float, python
objects, etc.). Axis labels are collectively called directories.
A pandas Series can be created using the following builder:
[Link]( data, index, dtype, copy)
The founder’s parameters are as follows: data: data takes various forms such as ndarray, list, constant
• Index: Index values must be unique and hashable, with the same length as the data.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

• dtype: for the dtype data type. If not, the data type will be removed.
• copy: copies the data. the default value is false.

It can be created using several inputs, such as a series:


• Array
• Dict
• Scalar value and constant

Creating an Empty Series


A basic array that can be created is an empty series. Series([], dtype: float64)
Creating a Series with ndarray
If the data is a ndarray, the passed directory must be of the same length. By default, the index takes
the range where n is the array length, rather than the index of the same length. That is: (n) [0,1,2,3 ….
Range (len (series)) — 1]..
Example 1:
0 a
1 b
2 c
3 d
dtype: object

Data Operations in Pandas


Pandas handles data through Series,Data Frame, and Panel. We will see some examples from each
of these.
Pandas Series
Series is a one-dimensional labeled array capable of holding data of any type (integer, string, float,
python objects, etc.). The axis labels are collectively called index. A pandas Series can be created using
the following constructor −
[Link]( data, index, dtype, copy)
Example
Here we create a series from a Numpy Array.

#import the pandas library and aliasing as pd


Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

import pandas as pd
import numpy as np
data = [Link](['a','b','c','d'])
s = [Link](data)
print s
Its output is as follows −
0 a
1 b
2 c
3 d
dtype: object

Pandas DataFrame
A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows
and columns. A pandas DataFrame can be created using the following constructor − [Link](
data, index, columns, dtype, copy)
Let us now create an indexed DataFrame using arrays
import pandas as pd
data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = [Link](data, index=['rank1','rank2','rank3','rank4'])
print df
Its output is as follows −

Age Name
rank1 28 Tom
rank2 34 Jack
rank3 29 Steve
rank4 42 Ricky

Pandas Panel
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

A panel is a 3D container of data. The term Panel data is derived from econometrics and is partially
responsible for the name pandas − pan(el)-da(ta)-s.
A Panel can be created using the following constructor − [Link](data, items, major_axis,
minor_axis, dtype, copy)
In the below example we create a panel from dict of DataFrame Objects
#creating an empty panel
import pandas as pd
import numpy as np
data = {'Item1' : [Link]([Link](4, 3)), 'Item2' : [Link]([Link](4, 2))}
p = [Link](data)
print p
Its output is as follows −
<class '[Link]'>
Dimensions: 2 (items) x 4 (major_axis) x 5 (minor_axis)
Items axis: 0 to 1
Major_axis axis: 0 to 3
Minor_axis axis: 0 to 4
Python Pandas - Function Application
To apply your own or another library’s functions to Pandas objects, you should be aware of the
three important methods. The methods have been discussed below. The appropriate method to use depends
on whether your function expects to operate on an entire DataFrame, row- or column-wise, or element
wise.
• Table wise Function Application: pipe()
• Row or Column Wise Function Application: apply()
• Element wise Function Application: applymap()

Table-wise Function Application


Custom operations can be performed by passing the function and the appropriate number of
parameters as pipe arguments. Thus, operation is performed on the whole DataFrame.
For example, add a value 2 to all the elements in the DataFrame. Then, adder function
The adder function adds two numeric values as parameters and returns the
sum. def adder(ele1,ele2):
return ele1+ele2
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

We will now use the custom function to conduct operation on the DataFrame.
df = [Link]([Link](5,3),columns=['col1','col2','col3'])
[Link](adder,2)
Let’s see the full program
import pandas as pd
import numpy as np
def adder(ele1,ele2):
return ele1+ele2
df = [Link]([Link](5,3),columns=['col1','col2','col3'])
[Link](adder,2)
print [Link]([Link])
Its output is as follows −
col1 col2 col3
0 2.176704 2.219691 1.509360
1 2.222378 2.422167 3.953921
2 2.241096 1.135424 2.696432
3 2.355763 0.376672 1.182570
4 2.308743 2.714767 2.130288

Row or Column Wise Function Application


Arbitrary functions can be applied along the axes of a DataFrame or Panel using the
apply() method, which, like the descriptive statistics methods, takes an optional axis argument. By default,
the operation performs column wise, taking each column as an array-like.
Example 1
import pandas as pd
import numpy as np
df = [Link]([Link](5,3),columns=['col1','col2','col3'])
[Link]([Link])
print [Link]([Link])
Its output is as follows −
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

col1 -0.288022
col2 1.044839
col3 -0.187009
dtype: float64
By passing axis parameter, operations can be performed row wise.
Example 2
import pandas as pd
import numpy as np
df = [Link]([Link](5,3),columns=['col1','col2','col3'])
[Link]([Link],axis=1)
print [Link]([Link])
Its output is as follows −
col1 0.034093
col2 -0.152672
col3 -0.229728
dtype: float64
Example 3
import pandas as pd
import numpy as np
df = [Link]([Link](5,3),columns=['col1','col2','col3'])
[Link](lambda x: [Link]() - [Link]())
print [Link]([Link])
Its output is as follows −
col1 -0.167413
col2 -0.370495
col3 -0.707631
dtype: float64
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Element Wise Function Application


Not all functions can be vectorized (neither the NumPy arrays which return another array nor any
value), the methods applymap() on DataFrame and analogously map() on Series accept any Python
function taking a single value and returning a single value.
Example 1
import pandas as pd
import numpy as np
df = [Link]([Link](5,3),columns=['col1','col2','col3'])
# My custom function df['col1'].map(lambda x:x*100)
print [Link]([Link])

Its output is as follows −


col1 0.480742
col2 0.454185
col3 0.266563
dtype: float64

Example 2
import pandas as pd
import numpy as np
# My custom function
df = [Link]([Link](5,3),columns=['col1','col2','col3'])
[Link](lambda x:x*100)
print [Link]([Link])

Its output is as follows −


col1 0.395263
col2 0.204418
col3 -0.795188
dtype: float64

[Link]

[Link](arg, na_action=None)[source]

• Map values of Series according to an input mapping or function.


• Used for substituting each value in a Series with another value, that may be derived from a
function, a dict or a Series.
Parameters
argfunction, [Link] subclass or Series
Mapping correspondence.
na_action{None, ‘ignore’}, default None
If ‘ignore’, propagate NaN values, without passing them to the mapping correspondence. Returns
Series
Same index as caller. See also
[Link]
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

For applying more complex functions on a Series.


[Link]
Apply a function row-/column-wise.
[Link]

Apply a function elementwise on a whole DataFrame.

Python Pandas – Sorting and Ranking


• Python Sorting and Ranking
• Another fundamental operation that uses indexing is sorting.
• Sorting the data is often a necessity and it is very important to be able to do it easily.
• pandas provides the sort_ index() function, which returns a new object that's identical to the start,
but in which the elements are ordered.
• Let's start by seeing how you can sort items in a series.
• The operation is quite trivial since the list of indexes to be ordered is only one.

Copy
>>> ser = [Link]([5,0,3,8,4],
... index=['red','blue','yellow','white','green'])
>>> ser red 5
blue 0
yellow 3
white 8
green 4 dtype: int64
>>> ser.sort_index() blue 0
green 4
red 5
white 8
yellow 3
dtype: int64

the items were sorted in ascending alphabetical order based on their labels (from A to Z).
This is the default behavior, but you can set the opposite order by setting the ascending
option toFalse.
Copy

>>> ser.sort_index(ascending=False)
yellow 3
white 8
red 5
green 4
blue 0
dtype: int64
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

With the dataframe, the sorting can be performed independently on each of its two axes.
So if you want to order by row following the indexes, you just continue to use the sort_index() function
without arguments as you've seen before, or if you prefer to order by columns, you need to set the axis
options to 1

In this case, you have to differentiate depending on whether you have to sort the
values of aseries or a dataframe.
If you want to order the series, you need to use the sort_values() function.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

If you need to order the values in a dataframe, use the sort_values() function seen previously but
with the by option.
Then you have to specify the name of the column on which to sort.

If the sorting criteria will be based on two or more columns, you can assign an array containing the names
of the columns to the by option

The ranking is an operation closely related to sorting.


It mainly consists of assigning a rank (that is, a value that starts at 0 and then increase gradually) to each
element of the series.
The rank will be assigned starting from the lowest value to the highest.

>>> [Link]()
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

red 4.0
blue 1.0
yellow 2.0
white 5.0
green 3.0
dtype: float64

The rank can also be assigned in the order in which the data are already in the data structure
(without a sorting operation).
In this case, you just add the method option with the first value assigned.

>>> [Link](method='first')
red 4.0
blue 1.0
yellow 2.0
white 5.0
green 3.0
dtype: float64

By default, even the ranking follows an ascending sort.


To reverse this criteria, set the ascending option to False.

Covariance and Correlation


Both covariance and correlation are about the relationship between the variables. Covariance
defines the directional association between the variables. Covariance values range from - inf to +inf
where a positive value denotes that both the variables move in the same direction and a negative value
denotes that both the variables move in opposite directions.
Correlation is a standardized statistical measure that expresses the extent to which two variables
are linearly related (meaning how much they change together at a constant rate). The strength
and directional association of the relationship between two variables are defined by correlation
and it ranges from -1 to +1. Similar to covariance, a positive value denotes that both variables move in
the same direction whereas a negative value tells us that they move in opposite directions.
Both covariance and correlation are vital tools used in data exploration for feature selection and
multivariate analyses. For example, an investor looking to spread the risk of a portfolio might look for
stocks with a high covariance, as it suggests that their prices move up at the same time. However, a similar
movement is not enough on its own. The investor would then use the correlation metric to determine how
strongly linked those stock prices are to each other.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

HIERARCHICAL INDEXING OR MULTIPLE INDEXING IN PYTHON PANDAS


Create Dataframe:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

import pandas as pd
import numpy as np
#Create a DataFrame
d={
'Name':['Alisa','Bobby','Cathrine','Alisa','Bobby','Cathrine',
'Alisa','Bobby','Cathrine','Alisa','Bobby','Cathrine'],
'Exam':['Semester 1','Semester 1','Semester 1','Semester 1','Semester 1','Semester 1',
'Semester 2','Semester 2','Semester 2','Semester 2','Semester 2','Semester 2'],

'Subject':['Mathematics','Mathematics','Mathematics','Science','Science','Science',
'Mathematics','Mathematics','Mathematics','Science','Science','Science'],
'Score':[62,47,55,74,31,77,85,63,42,67,89,81]}

df = [Link](d,columns=['Name','Exam','Subject','Score'])
df

so the resultant dataframe will be


Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Hierarchical indexing or multiple indexing in python pandas:

# multiple indexing or hierarchical indexing


df1=df.set_index(['Exam', 'Subject'])
df1

set_index() Function is used for indexing , First the data is indexed on Exam and
then on Subjectcolumn
So the resultant dataframe will be a hierarchical dataframe as shown below

View Index:
One can view the details of index as shown below
1 # View index
2 [Link]
So the result will be
MultiIndex(levels=[[‘Semester 1’, ‘Semester 2’], [‘Mathematics’, ‘Science’]],labels=[[0, 0, 0, 0,
0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1]],
names=[‘Exam’, ‘Subject’])
Reading and Writing CSV File using Python
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

CSV (stands for comma separated values) format is a commonly used data format
used by spreadsheets. The csv module in Python’s standard library presents classes
and methods to perform read/write operations on CSV files.
writer()
This function in csv module returns a writer object that converts data into a delimited string and
stores in a file object. The function needs a file object with write permission as a parameter. Every row
written in the file issues a newline character. To prevent additional space between lines, newline parameter
is set to ‘’.
The writer class has following methodswriterow()
This function writes items in an iterable (list, tuple or string) ,separating them nby comma
character.

writerows()
This function takes a list of iterables as parameter and writes each item as a comma separated line
of items in the file.
Following example shows use of write() function. First a file is opened in ‘w’ mode. This file is
used to obtain writer object. Each tuple in list of tuples is then written to file using writerow() method.

>>> import csv


>>> persons=[('Lata',22,45),('Anil',21,56),('John',20,60)]
>>> csvfile=open('[Link]','w', newline='')
>>> obj=[Link](csvfile)
>>> for person in persons: [Link](person)
>>> [Link]()

This will create ‘[Link]’ file in current directory. It will show following data.
Lata,22,45
Anil,21,56
John,20,60

Instead of iterating over the list to write each row individually, we can use writerows() method.

>>> csvfile = open('[Link]','w', newline='')


>>> obj = [Link](csvfile)
>>> [Link](persons)
>>> [Link]()

read()
This function returns a reader object which returns an iterator of lines in the csv file. Using the regular for
loop, all lines in the file are displayed in following example.

>>> csvfile=open('[Link]','r', newline='')


>>> obj=[Link](csvfile)
>>> for row in obj:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

print (row)
['Lata', '22', '45']
['Anil', '21', '56']
['John', '20', '60']
Since reader object is an iterator, built-in next() function is also useful to display all lines in csv file.

>>> csvfile = open('[Link]','r', newline='')


>>> obj = [Link](csvfile)
>>> while True: try: row=next(obj)
print (row)
except StopIteration: break

The csv module also defines a dialect class. Dialect is set of standards used to implement CSV
protocol. The list of dialects available can be obtained by list_dialects() function.

>>> csv.list_dialects()
['excel', 'excel-tab', 'unix']

DictWriter()
This function returns a DictWriter object. It is similar to writer object, but the rows are mapped
to dictionary object. The function needs a file object with write permission and a list of keysused in
dictionary as fieldnames parameter. This is used to write first line in the file as header.
writeheader()
This method writes list of keys in dictionary as a comma separated line as first line in the [Link]
following example, a list of dictionary items is defined. Each item in the list is a [Link] writrows()
method, they are written to file in comma separated manner.

>>> persons=[{'name':'Lata','age':22,'marks':45}, {'name':'Anil', 'age':21,'marks':56},


{'name':'John', 'age':20, 'marks':60}]
>>> csvfile=open('[Link]','w', newline='')
>>> fields=list(persons[0].keys())
>>> obj=[Link](csvfile, fieldnames=fields)
>>> [Link]()
>>> [Link](persons)
>>> [Link]()

The file shows following contents.


name,age,marks Lata,22,45 Anil,21,56 John,20,60

DictReader()
This function returns a DictReader object from the underlying CSV file. As in case of readerobject,
this one is also an iterator, using which contents of the file are retrieved.

>>> csvfile = open('[Link]','r', newline='')


>>> obj = [Link](csvfile)
The class provides fieldnames attribute, returning the dictionary keys used as header of file.

>>> [Link] ['name', 'age', 'marks']


Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Use loop over the DictReader object to fetch individual dictionary objects.

>>> for row in obj:


print (row)

This results in following output.


OrderedDict([('name', 'Lata'), ('age', '22'), ('marks', '45')])
OrderedDict([('name', 'Anil'), ('age', '21'), ('marks', '56')])
OrderedDict([('name', 'John'), ('age', '20'), ('marks', '60')])

To convert OrderedDict object to normal dictionary, we have to first import OrderedDict from collections
module.
>>> from collections import OrderedDict
>>> r=OrderedDict([('name', 'Lata'), ('age', '22'), ('marks', '45')])
>>> dict(r)
{'name': 'Lata', 'age': '22', 'marks': '45'}

Python - Reading HTML Pages Reading the HTML file


In the below example we make a request to an url to be loaded into the python environment. Then use the
html parser parameter to read the entire html file. Next, we print first few lines of the html page.
import urllib2
from bs4 import BeautifulSoup
# Fetch the html file
response = [Link]('[Link]
html_doc = [Link]()
# Parse the html file

soup = BeautifulSoup(html_doc, '[Link]')


# Format the parsed html file
strhtm = [Link]()
# Print the first few characters
print (strhtm[:225])
When we execute the above code, it produces the following result.

<!DOCTYPE html>
<!--[if IE 8]><html class="ie ie8"> <![endif]-->
<!--[if IE 9]><html class="ie ie9"> <![endif]-->
<!--[if gt IE 9]><!-->
<html>
<!--<![endif]-->
<head>
<!-- Basic -->
<meta charset="utf-8"/>
<title>

Introduction
Just like with all other types of files, you can use the Pandas library to read and write Excel files
using Python as well. In this short tutorial, we are going to discuss how to read and write Excel files via
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

DataFrame s.
In addition to simple reading and writing, we will also learn how to write multiple DataFrame s
into an Excel file, how to read specific rows and columns from a spreadsheet, and how to name single and
multiple sheets within a file before doing anything.
If you'd like to learn more about other file types, we've got you covered:

• Reading and Writing JSON Files in Python with Pandas


• Reading and Writing CSV Files in Python with Pandas

Reading and Writing Excel Files in Python with Pandas


Naturally, to use Pandas, we first have to install it. The easiest method to install it is via pip . If you're
running Windows:
$ python pip install pandas
If you're using Linux or MacOS:
$ pip install pandas
Note that you may get a ModuleNotFoundError or ImportError error when running the code in
this article. For example:
ModuleNotFoundError: No module named 'openpyxl'
If this is the case, then you'll need to install the missing module(s):
$ pip install openpyxl xlsxwriter xlrd
Writing Excel Files Using Pandas
We'll be storing the information we'd like to write to an Excel file in a DataFrame . Using the built-
in to_excel() function, we can extract this information into an Excel file.

import pandas as pd
import numpy as np
# Create multiple lists
technologies = ['Spark','Pandas','Java','Python', 'PHP']
fee = [25000,20000,15000,15000,18000]
duration = ['5o Days','35 Days',[Link],'30 Days', '30 Days']
discount = [2000,1000,800,500,800]
columns=['Courses','Fee','Duration','Discount']
# Create DataFrame from multiple lists
df = [Link](list(zip(technologies,fee,duration,discount)), columns=columns)
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

print(df)

Outputs:
# Courses Fee Duration Discount
# 0 Spark 25000 5o Days 2000
# 1 Pandas 20000 35 Days 1000
#2 Java 15000 NaN 800
# 3 Python 15000 30 Days 500
#4 PHP 18000 30 Days 800

1. pandas DataFrame to Excel


Use to_excel() function to write or export pandas DataFrame to excel sheet with extension xslx.
Using this you can write excel files to the local file system, S3 e.t.c. Not specifying any parameter it
default writes to a single sheet.
to_excel() takes several optional params that can be used skip columns, skip rows, not to write
index, set column names, formatting, and many more.
# Write DataFrame to Excel file
df.to_excel('[Link]')
This creates an excel file with the contents as below. By default, It exports column names, indexes, and
data to a sheet named 'Sheet1'.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

UNIT – V
PROGRAMMING WITH R
Variables - Vector, matrix, arrays – List – Data Frames – Functions – Strings – Factors – Loops –
Packages –Date and Time – Files - Making packages
Introduction to R- Programming
• R is a programming language and software environment for statistical analysis, graphics
representation and reporting.
• R was created by Ross Ihaka and Robert Gentleman at the University of Auckland, NewZealand,
and is currently developed by the R Development Core Team.
• R is freely available under the GNU General Public License, and pre-compiled binary versions are
provided for various operating systems like Linux, Windows and Mac.
• This programming language was named R,based on the first letter of first name of the two R
authors (Robert Gentleman and Ross Ihaka),and partly a play on the name of theBell Labs
Language S.
• R is the most popular data analytics tool as it is open-source, flexible, offers multiple packages
and has a huge community.

Why Do We Need Analytics?


Before an answer to above question, let us see some of the problems and their solutions in R in
multiple domains.
Banking:
Large amount of customer data is generated every day in Banks. While dealing with millions of
customers on regular basis, it becomes hard to track their mortgages.
Solution:
R builds a custom model that maintains the loans provided to every individual customer which
helps us to decide the amount to be paid by the customer over time.
Insurance:
Insurance extensively depends on forecasting. It is difficult to decide which policy to accept or
reject.
Solution:
By using the continuous credit report as input, we can create a model in R that will not only assess
risk appetite but also make a predictive forecast as well.
Healthcare:
Every year millions of people are admitted in hospital and billions are spent annually just in the
admission process.
Solution:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Given the patient history and medical history, a predictive model can be built to identify who is at
risk for hospitalization and to what extent the medical equipment should be scaled.
There are various tools available in the market for Data Visualization:R, Power BI, Spark,
Qlikview etc.

Evolution of R
• R is an implementation of S programming language which was created by John Chambers at Bell
Labs.
• R was initially written by Ross Ihaka and Robert Gentleman at the Department of Statistics of the
University of Auckland in Auckland, New Zealand.
• R made its first public appearance in 1993.
• A large group of individuals has contributed to R by sending code and bug [Link] mid-1997
there has been a core group (the "R Core Team") who can modify the R source code archive.
• In the year 2000 R 1.0.0 released.
• R 3.0.0 was released in 2013.

Features of R:
• R supports procedural programming with functions and object-oriented programming with generic
functions. Procedural programming includes procedure, records, modules, and procedure calls.
While object-oriented programming language includes class, objects, and functions.
• Packages are part of R programming. Hence, they are useful in collecting sets of R functions into
a single unit.
• R is a well-developed, simple and effective programming language which includes conditionals,
loops, user defined recursive functions and input and output facilities.
• R has an effective data handling and storage facility,
• R provides a suite of operators for calculations on arrays, lists, vectors and matrices.
• R provides a large, coherent and integrated collection of tools for data analysis. It provides
graphical facilities for data analysis and display either directly at the computer or printing at the
papers.
• Rs programming features include database input, exporting data, viewing data, variable labels,
missing data, etc.
• R is an interpreted language. So we can access it through command line interpreter.
• R supports matrix arithmetic.
• R, SAS, and SPSS are three statistical languages. Of these three statistical languages, R is the only
an open source
The prominent editors available for R programming language are:
RGUI(R graphical user interface) - Rstudio – Studio R offers a richer editing environment than RGUI and
makes some common tasks easier and more fun.
RStudio - RStudio is an integrated development environment (IDE) for R language. RStudio is a code
editor and development environment, with some nice features that make code development in R easy and
fun.
R Command Prompt
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Once you have R environment setup, then it’s easy to start your R command prompt by just clicking on R
Software icon. This will launch R interpreter and you will get a prompt > where
you can start typing your programs or commands.
>x=6
>print(x)
Usually, you will do your programming by writing your programs in script files and then you execute
those scripts at your command prompt with the help of R interpreter called Rscript. So let's start with
writing following code in a text file called test.R as under –

# My first program in R Programming


myString<- "Hello, World!"
print ( myString)

Save the above code in a file test.R. Execute by opening that script in R editor, select all (Ctrl
+A) and click on run line or selection (Ctrl+R) option in Edit menu of R [Link] we run the above
program, it produces the following result.
"Hello, World!"
Variables, Datatypes in R:
Everything in R is an object.R has 6 atomic vector types.
• character
• numeric (real or decimal)
• integer
• logical
• complex

By atomic, we mean the vector only holds data of a single type.


• character: "a", "swc"
• numeric: 2, 15.5
• integer: 2L (the L tells R to store this as an integer)
• logical: TRUE, FALSE
• complex: 1+4i (complex numbers with real and imaginary parts)

R provides many functions to examine features of vectors and other objects, for example
• class() - what kind of object is it (high-level)?
• typeof() - what is the object’s data type (low-level)?
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

• length() - how long is it? What about two dimensional objects?


• attributes() - does it have any metadata?

Basics types of data


4.5 is a decimal value called numeric.
4 is a natural value called integers. Integers are also numeric.
TRUE or FALSE is a Boolean value called logical.
The value inside " " or ' ' are text (string). They are called characters.
3+4i is a complex type of data.

Data Objects in R:
Data types are used to store information. In R, we do not need to declare a variable as some data
type. The variables are assigned with R-Objects and the data type of the R-object becomes the data type
of the variable.
There are mainly six data types present in R:
• Vectors
• Lists
• Matrices
• Arrays
• Factors
• Data Frames

Scalar: Scalar variable A scalar is a single number. The following code creates. a scalar variable with the
numeric value 5: x = 5. Vector variable A vector is a sequence of numbers.
1. Vector: A Vector is a sequence of data elements of the same basic type.
Example 1:
>vtr = c(1, 3, 5 ,7 9) or >vtr<- c (1, 3, 5 ,7 9)
>print(vtr)
o/p: [1] 1 3 5 7 9

Example 2: Creating sequence vector by using colon operator.


>v = 2:12
>print(v)
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

o/p: [1] 2 3 4 5 6 7 8 9 10 11 12

> v = 3.5:10.5
>v
o/p: [1] 3.5 4.5 5.5 6.5 7.5 8.5 9.5 10.5
Example 3: If the final element specified does not belong to the sequence then it is discarded.
>v <- 3.8:11
>v
[1] 3.8 4.8 5.8 6.8 7.8 8.8 9.8 10.8
Example 4: using seq()(sequence) function, create vector from 1 to9 increment by 2.
>a=seq(1,10,by=2)
>a
o/p: [1] 1 3 5 7 9
Example 4: Accessing vector elements by its position (index).
>day = c("Mon","Tue","Wed","Thurs","Fri","Sat","sun")
>print(day[3])
o/p: [1] "Wed"
>weekend=day[c(6,7)]
>weekend
o/p: [1] "Sat" "sun".
>print(day[c(-2,-3)]) // Negative indexing
o/p: [1] "Mon" "Thurs" "Fri" "Sat" "sun"
There are 5 Atomic vectors, also termed as five classes of vectors.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

1.# Atomic vector of type character.


Ex: v = "TRUE"
print(class(v))
o/pt: [1] "character"

2.#Atomic vector of type numeric.


Ex: v = 23.5
print(class(v))
o/p: [1] "numeric"

3.# Atomic vector of type integer.


Ex: v = 2L
print(class(v))
o/p: [1] "integer"

4.# Atomic vector of type logical.


Ex: v = TRUE
print(class(v))
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

o/p: [1] "logical"

5.# Atomic vector of type complex.


Ex: v = 2+5i
print(class(v))
o/p: [1] "complex"

[Link]:
Lists are the R objects which contain elements of different types like − numbers, strings, vectors
and another list inside it.A list can also contain a matrix or a function as its elements. List is created using
list() function.
Example 1:
>n = c(2, 3, 5)
>s = c("aa", "bb", "cc", "dd", "ee")
>x = list(n, s, TRUE)
>x

O/p
[[1]]
[1] 2 3 5
[[2]]
[1] "aa" "bb" "cc" "dd" "ee" [[3]]
[1] TRUE

Example 2: Accessing the elements of list


>mylist = list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2), list("green",12.3))
>print(mylist[1]) [[1]]

o/p: [1] "Jan" "Feb" "Mar"

>print(mylist[c(1,3)])

o/p:

[[1]]
[1] "Jan" "Feb" "Mar"
[[2]]
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

[[2]][[1]]
[1] "green"
[[2]][[2]]
[1] 12.3

[Link]
Matrices are the R objects in which the elements are arranged in a two-dimensional rectangular
layout. A Matrix is created using the matrix() function.

Example: matrix (data, nrow, ncol, byrow, dimnames)


Where data is the input vector which becomes the data elements of the matrix.
• nrow is the number of rows to be created.
• ncol is the number of columns to be created.
• byrow is a logical clue. If TRUE then the input vector elements are arranged by row.
• dimname is the names assigned to the rows and columns.

Examples 1:>Mat = matrix(c(1:16), nrow = 4, ncol = 4 )
>Mat

Output :
[,1] [,2] [,3] [,4]
[1,] 1 5 9 13
[2,] 2 6 10 14
[3,] 3 7 11 15
[4,] 4 8 12 16

Examples 2:using byrow=TRUE/FALSE

# Create a matrix.
>M = matrix( c('a','a','b','c','b','a'), nrow = 2, ncol = 3, byrow = TRUE)
>print(M)
o/p:
[,1] [,2] [,3]
[1,] "a" "a" "b"
[2,] "c" "b" "a"

>M = matrix( c('a','a','b','c','b','a'),nrow=3,byrow=FALSE)


>M
[,1] [,2]
[1,] "a" "c"
[2,] "a" "b"
[3,] "b" "a"

Examples 3:Accessing the elements of matrix

>print(Mat[1,3]) to access 1st row third element.


Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

o/p: [1] 9

>print(Mat[,3]) to access 3rd column


o/p: [1] 9 10 11 12

>print(Mat[1,]) to access 1st row


o/p: [1] 1 5 9 13

Examples 4:giving row names, column names of a matrix

>rownames = c("row1", "row2", "row3", "row4")


>colnames = c("col1", "col2", "col3")
> P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames))
> P
o/p:

col1 col2 col3


row1 3 4 5
row2 6 7 8
row3 9 10 11
row4 12 13 14

>P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames =list(c('a','b','c','d'),c(1,2,3)))


>P

o/p: 1 2 3
a 3 45
b 6 7 8
c 9 10 11
d 12 13 14

>P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames =list(1:4,5:7))


>P
o/p: 5 6 7
1345
2678
3 9 10 11
4 12 13 14

[Link]:
Arrays are the R data objects which can store data in more than two [Link] example − If
we create an array of dimension (2, 3, 4) then it creates 4 rectangular matrices each with 2 rows and 3
[Link] matrices areconfined to two dimensions, arrays can be of any number of [Link]
array is created using the array() function. It takes vectors as input and uses the values in the dim parameter
to create an array. In the below example we create 2 arrays of which are 3x3 matrices each.

Examples 1: Here we create two arrays with two elements which are 3x3 matrices each
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

>v1 <- c(5,9,3)


>v2 <- c(10,11,12,13,14,15)
>result<- array(c(v1,v2),dim = c(3,3,2))
>result

Output –
,,1
[,1] [,2] [,3]
[1,] 5 10 13
[2,] 9 11 14
[3,] 3 12 15

,,2
[,1] [,2] [,3]
[1,] 5 10 13
[2,] 9 11 14
[3,] 3 12 15

Examples 2.
>a <- array(c('green','yellow'),dim = c(3,3,2))
>print(a)

o/p: ,,1
[,1] [,2] [,3]
[1,] "green" "yellow" "green"
[2,] "yellow" "green" "yellow"
[3,] "green" "yellow" "green"

,,2
[,1] [,2] [,3]
[1,] "yellow" "green" "yellow"
[2,] "green" "yellow" "green"
[3,] "yellow" "green" "yellow"

[Link]:

Factors are the data objects which are used to categorize the data and store it as levels. They can
store both strings and integers. They are useful in data analysis for statistical modeling.
Factors are created using the factor() function. The nlevels functions gives the count of levels.

# Create a vector.
apple_colors<- c('green','green','yellow','red','red','red','green')
# Create a factor object.
factor_apple<- factor(apple_colors)
# Print the factor.
print(factor_apple)
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

print(nlevels(factor_apple))

When we execute the above code, it produces the following result –

[1] green green yellow red redred green Levels: green red yellow
[1] 3

Ex2:
>data <- c("East","West","East","North","North","East","West","West“,"East“)
>factor_data<- factor(data)
>factor_data

Output :

[1] East West East North North East West West East
Levels: East North West

[Link] Frames:
A data frame is a table or a two-dimensional array-like structure in which each column contains
values of one variable and each row contains one set of values from each [Link] frames are tabular
data objects. Unlike a matrix in data frame each column can contain different modes of data. The first
column can be numeric while the second column can be character and third column can be logical. It is a
list of vectors of equal [Link] Frames are created using the [Link]() function.

# Create the data frame.


BMI <-[Link](gender = c("Male", "Male","Female"), height = c(152, 171.5, 165),
weight = c(81,93, 78), Age = c(42,38,26)
)
print(BMI)

When we execute the above code, it produces the following result –


gender height weight Age
1 Male 152.0 81 42
2 Male 171.5 93 38
3 Female 165.0 78 26

Ex2:

>std_id = c (1:5)
>std_name = c("Rick","Dan","Michelle","Ryan","Gary")
>marks = c(623.3,515.2,611.0,729.0,843.25)
>[Link]<- [Link](std_id, std_name, marks)
>[Link]

Output :
std_id std_name marks

1 1 Rick 623.30
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

2 2 Dan 515.20
3 3 Michelle 611.00
4 4 Ryan 729.00
5 5 Gary 843.25
By this, we come to the end of different data types in R. Next, let us move forward in R Tutorial
blog and understand another key concept – flow control statements.

Variables:
A variable provides us with named storage that our programs can manipulate. A variable in R can
store an atomic vector, group of atomic vectors or a combination of many R- objects. A valid variable
name consists of letters, numbers and the dot or underline characters. The variable name starts with a letter
or the dot not followed by a number.

Variable Name Validity Reason


var_name2. valid Has letters, numbers, dot and underscore
var_name% Invalid Has the character '%'. Only dot(.) and underscore allowed.
2var_name invalid Starts with a number
.var_name ,
[Link] valid Can start with a dot(.) but the dot(.)should not be followed
by a number.
.2var_name invalid The starting dot is followed by a number making it invalid.
_var_name invalid Starts with _ which is not valid

Variable Assignment

The variables can be assigned values using leftward, rightward and equal to operator. The values
of the variables can be printed using print() or cat()function. The cat() function combines multiple items
into a continuous print output.

# Assignment using equal operator. var.1 = c(0,1,2,3)


# Assignment using leftward operator. var.2 <- c("learn","R")
# Assignment using rightward operator. c(TRUE,1) -> var.3

print(var.1)
cat ("var.1 is ", var.1 ,"\n")
cat ("var.2 is ", var.2 ,"\n")
cat ("var.3 is ", var.3 ,"\n")

When we execute the above code, it produces the following result − [1] 0 1 2 3

var.1 is 0 1 2 3 var.2 is learn R var.3 is 1 1

Note − The vector c(TRUE,1) has a mix of logical and numeric class. So logical class is coerced to
numeric class making TRUE as 1.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Data Type of a Variable


In R, a variable itself is not declared of any data type, rather it gets the data type of the R - object
assigned to it. So R is called a dynamically typed language, which means that we can change a variable’s
data type of the same variable again and again when using it in a program.
var_x<- "Hello"
cat("The class of var_x is ",class(var_x),"\n")
class(var_x)
var_x<- 34.5
cat(" Now the class of var_x is ",class(var_x),"\n")
class(var_x)
var_x<- 27L
cat(" Next the class of var_x becomes ",class(var_x),"\n")
class(var_x)

Finding Variables
To know all the variables currently available in the workspace we use the ls()function. Also the
ls() function can use patterns to match the variable names.

print(ls())

When we execute the above code, it produces the following result –

[1]"myvar" "my_new_var" "my_var" "var.1"


[5] "var.2" "var.3" "[Link]" "var_name2."
[9] "var_x" "varname"

The ls() function can use patterns to match the variable names. # List the variables starting with the pattern

"var". print(ls(pattern = "var"))


When we execute the above code, it produces the following result –

[1] "myvar" "my_new_var" "my_var" "var.1"


[5] "var.2" "var.3" "[Link]" "var_name2."
[9] "var_x" "varname"

Deleting Variables

Variables can be deleted by using the rm() function. Below we delete the variable var.3. On
printing the value of the variable error is thrown.

rm(var.3) print(var.3)

When we execute the above code, it produces the following result –

[1] "var.3"
Error in print(var.3) : object 'var.3' not found

All the variables can be deleted by using the rm() and ls() function together. rm(list = ls())
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

print(ls())
When we execute the above code, it produces the following result − character(0)

Conditional Statements:

Conditional control structures require the programmer to specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the condition is determined to be
false.
Example:If,If-Else,If-ElseIf Ladder,switch

If:
An if statement consists of a Boolean expression followed by oneor more statements.
Syntax:
If(condition)

Statement

Example:Check for Positive Number

output

If-Else
Syntax:
if(condition)
{

}
Else
{
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Statement1
Statement 2
}

Example: Check for Odd or Even Number

If-Else if Ladder
If-Else statements can be chained using If-Else if Ladder

Syntax:
if(condition)
{
Statement1
}
else if{
Statement 2
}
Else
{
Statement 3
}

Example: Greatest of three numbers


Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Switch
A switch statement allows a variable to be tested for equality against a list of values. Each value
is called a case, and the variable being switched on is checked for each case.

Syntax:
switch(Expression, "Option 1", "Option 2", "Option 3" "OptionN")

Example:Print Department names using Switch

Output:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Looping Statements in R
A loop statement allows us to execute a statement or group of statements multiple times.

Example : for,while,Repeat

For:
A For loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.

Syntax:

for(value in vector)
{
Statements
}
Example: Printing elements of vector

Output:

While:
The While loop executes the same code again and again until astop condition is met.

Syntax:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

while(condition)
{
Statement
}

Example: Sum of Series

Output:

Repeat:
The Repeat loop executes the same code again and again until astop condition is met.

Syntax:
repeat
{
Commands
If(condition)
Break
}

Example:Printing even numbers till 10


Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Output

Jump Statements:
Loop control statements change execution from its normalsequence
Example: break, next

Break:
Terminates the loop statement and transfers execution to the statement immediately following the
loop.

Syntax: break

Example :print numbers till 5

Output:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Next:
The next statement in R programming language is useful when we want to skip the current iteration
of a loop without terminating it. On encountering next, the R parser skips further evaluation and starts
next iteration of the loop.
Syntax:
next
Example: Print numbers from 1 to 10 except 5

Output:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Functions in R
A function is a set of statements organized together to perform a specific task.R has a large number
of in-built functions and the user can create their own functions.
Syntax:
An R function is created by using the keyword function. The basic syntax of an R function
definition is as follows.
Function name=function(ar1,ar2,……)
{
Function body
}

Function Components:
The different parts of a function are −
Function Name − This is the actual name of the function. It is stored in R environment as an object
with this name.
Arguments − An argument is a placeholder. When a function is invoked, you pass a value to the argument.
Arguments are optional; that is, a function may contain no arguments. Also arguments can have default
values.
Function Body − The function body contains a collection of statements that defines what the function
does.
Return Value − The return value of a function is the last expression in the function body to be evaluated.

Built-in Functions
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

R has many in-built functions which can be directly called in the program without defining
them first.
Eg: [Link],abs,round .
Example:

Output:

User Defined Function

We can create user-defined functions in R. They are specific to what a user wants and once created
they can be used like the built-in functions. Belowis an example of how a function is created and used.

Function without Arguments:


Here the function does not receive any arguments.
Example:

Output
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Function with Arguments:


The arguments to a function call can be supplied in the same sequence as defined in the function or they
can be supplied in a different sequence but assigned to the names of the arguments.

Example

Function with Default Argument


We can define the value of the arguments in the function definition and call the function without
supplying any argument to get the default result. But we can also call such functions by supplying new
values of the argument and get non default result.

Example:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

LOOPING FUNCTIONS IN R
The for, while loops can often be replaced by looping functions:

lapply:
Definition:Loop over a list and evaluate a function on each element

Syntax
lapply(X, FUN, ...) X =List FUN=A

Function
…. =other arguments

Example:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

sapply:

Definitio: same as lapply but try to simplify the result .

Syntax :

lapply(X, FUN, ...)

X=Li st FUN=A

Function
…. =other arguments

Example:

apply:
Definition: apply a function over the margins of an array Syntax: apply(X, MARGIN, FUN, ...)
X=An Array
MARGIN =Integer vector indicating which margins should be “retained”.

FUN =Function to be applied


... = other arguments to be passed to FUN

Example: Row wise sum in a given matrix using apply()


Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

mapply
Definition: Multivariate version of lapply
Syntax: mapply (FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE, [Link]
= TRUE)

FUN : the function to be applied


.. : arguments to apply over MoreArgs : a list of other arguments to
SIMPLIFY : logical; whether the result should be simplified to a vector or matrix.

Example:

Matrices in R
Matrices are the R objects in which the elements are arranged in a two-dimensional rectangular
layout. We use matrices containing numeric elements to be used in mathematical calculations.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Syntax:
The basic syntax for creating a matrix in R is

matrix(data, nrow, ncol, byrow, dimnames)

• data is the input vector which becomes the data elements of the matrix.
• nrow is the number of rows to be created.
• ncol is the number of columns to be created.
• byrow is a logical clue. If TRUE then the input vector elements
arearranged by row.
• dimname is the names assigned to the rows and columns.

Matrix Creation:
Arrange elements sequentially by row.
Example:

(ii) Arrange elements sequentially by column.


Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Accessing Elements of Matrix:


Elements of a matrix can be accessed by using the column and row index of the element
Example

Matrix Operations
Various mathematical operations are performed on the matrices using the Roperators. The result
of the operation is also a [Link] dimensions (number of rows and columns) should be same for the
matrices involved in the operation.
Matrix Addition
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Matrix Subtraction
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

String Operations in R String:


Any value written within a pair of single quote or double quotes in R istreated as a string.
Example:
S=”Hello”
S1=’hai’
String Manipulation:
Concatenating Strings - paste() function:
Many strings in R are combined using the paste() function. It can takeany number of arguments to
be combined together.
Syntax:
paste(..., sep = " ", collapse = NULL)
... represents any number of arguments to be combined.
sep represents any separator between the arguments. It is optional.
collapse is used to eliminate the space in between two strings. Butnot the space within two words of one
string.
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

Counting number of characters in a string - nchar() function


This function counts the number of characters including spaces in a string.
Syntax:
The basic syntax for nchar() function is –
nchar(x)
Following is the description of the parameters used −
• x is the vector input
Example

Changing the case - toupper() & tolower() functions


These functions change the case of characters of a string.
Syntax
The basic syntax for toupper() & tolower() function is −
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

toupper(x)
tolower(x)

Following is the description of the parameters used −

• x is the vector input.


Example:

Extracting parts of a string - substring() function


This function extracts parts of a String.
Syntax
The basic syntax for substring() function is −
substring(x,first,last)
Following is the description of the parameters used −
• x is the character vector input.
• first is the position of the first character to be extracted.
• last is the position of the last character to be extracted.
Replacement Functions:sub() and gsub()
These are replacement functions, which replaces the occurrence of asubstring with other substring.
• sub() Function in R replaces the first instance of a substring
• gsub() function in R replaces all the instances of a substring
Syntax for sub() and gsub() function in R:
1. sub(old, new, string)
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

2. gsub(old, new, string)

Pattern Matching Function:


Grep() function
Syntax:
grep(value = FALSE) returns an integer vector of the indices of the elements of x that yielded a match .
grep(value = TRUE) returns a character vector containing the selected elements of x.

R Date and Time


Dates and times are very frequently used concept in data analysis
Date and Time Classes
There are three types of date and time classes which arrive with R programming.
These are:
• POSIXct
• POSIXlt and
• Date.
POSIX Dates and Time Classes
POSIX dates and times are classic R
The function [Link]() is used to return the current date and time in POSIXct notation:
(now_ct <- [Link] ())
# [1] "2023-07-13 [Link] BST"
Here, ct is the short form for calendar time.
Again, when the date needs to be printed, you just see a formatted version of it, so it won't go obvious
how the date is stored. By using 'unclass', you can see where it is indeed just a number:
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

unclass (now_ct)
# [1] 1.374e+09

Date Class
The third is the 'date' class in base R which is better named as the 'Date' class. It keeps dates as if
the number of days since the starting of 1970. The 'Date' class is finely used in cases where programmers'
do not bother about the time of day.
(now_date <- as. Date (now_ct))
## [1] "2016-10-28"
class (now_date)
## [1] "Date"
unclass(now_date)
## [1] 15903
Other classes for date and time have add-on packages which include date, dates, chron, year mon,
yearqtr, timeDate, ti, and jul.
input / output
Reading from the Keyboard
Now we can use scan():
> z <- scan()
1: 12 5
3: 2
4:
Read 3 items

>z

[1] 12 5 2

We can use readline() for inputing a line from the keyboard in the form of a string:
> w <- readline()
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

xyz vw u
>w
[1] "xyz vw u"

Printing to the Screen

In batch mode, one can use the print() function


e.g.
print(x)
to use cat() instead of print()
> print("xyz")
[1] "xyz"
> cat("xyz \n")
xyz
The arguments to cat() will be printed out with intervening spaces, for instance
> g <- 62
> cat(g,"xyz","gs\n")
62 kyz gs

R Packages
Packages are part of R programming and they are useful in collecting sets of R functions into a single
unit. It also contains compiled code and sample data. All of these are kept stored in a directory called the
"library" in the R environment.
(Or)
A package is a set of R functions and data-sets and the library is a folder on your system / computer
which stores the files for those package(s).

Loading Packages in R
For loading a package which is already existing and installed on your system, you can make use of and
call the library function.
library(lattice)
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

We can now employ all the functions included within lattice package.

pkges <- c ("lattice", "utils", "rpart")


for (pkg1 in pkges)
{
library (pkg1, [Link] = TRUE)
}
Installing any new package in R
There are 2 means for adding new packages within a R program. 1st is installing package directly from
within CRAN directory like this:
install. packages("Package Name")
# Install the package named "XML".
install. packages ("XML")

Secondly by downloading the package to your local machine and then adding / installing it manually.
Search Path
We can see the packages which are loaded by means of the search function
> search()
## [1] ".GlobalEnv" "package:stats" "package:graphics"
## [4] "package:grDevices" "package:utils" "package:datasets"
## [7] "package:methods" "Autoloads" "package:base"

This collection of packages confirms the order of places which R will come across to try finding any
variable. The global environment always comes at the beginning, and then the most recently loaded
packages.
Maintaining Packages
By default, the function will remind you to update each package.
[Link] (ask = FALSE)
# this won't ask for package updating

We want to delete any package. It is possible using the [Link]().


Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur

[Link]("zoo")

R Programming Excel and Binary File


Install the xlsx package
There is a command which is generally used in the R console for installing the "xlsx" package.
install. packages ("xlsx")
After your xlsx package get installed, you can verify it using the command
any (grepl ("xlsx", [Link]()))
Reading the Excel File
Any .xlsx file can be read by using the [Link]() function. An example is shown below. The
result gets stored as a data frame within the R environment.
info <- [Link] ("[Link]", sheetIndex = 1)
print (info)

Binary File Format


A binary file is a type of file which holds information that are in the form of bits and bytes only
i.e. 0's and 1's. This information cannot be read by human as the bytes in it translate to characters and
symbols that contain various other non-printable characters.
R provides two different functions for dealing with binary files. These are:
• WriteBin()
• readBin()
1st one is for creating files and 2nd is for reading binary files.
The syntax of writing them is as follows:
writeBin (object, con)
readBin (con, what, n )
Here, the parameters used are:
• con is the connection object used for reading or writing the binary file
• object here, is a binary file that to be written
• what is the mode which can be character, integer etc and it represents the readable bytes.
• n is the amount of bytes for reading from the binary file.

You might also like