Python
Python
PG Department of CS
Arasu College of Arts & Science for Women, Karur
Introduction:
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 −
(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
Python Java
Uses Indentation for structuring code Uses braces for structuring code
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]):
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
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.
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.
All the keywords are in lowercase except 03 keywords (True, False, None).
Code
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
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
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
\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
• 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
➢ 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.
123E+8
1230E04
-0.123E-3
163.E4
.34E-2
4.E3
• Python provides no braces to indicate blocks of code for class and function definition
orflow control.
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.
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:
[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)
Example x=y=z=5
You can also assign multiple values to multiple variables. For example −
x , y , z = 4, 5, “python”
Python first evaluates the RHS expression and then assigns to [Link]:
p, q, r= 5, 10, 7
print (p,q,r)
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)
<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
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
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
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.
Vishnu Priya
Name: John
Age: 30
print("welcome \n to all.")
Output
welcome
to all.
Type Casting:
To convert one data type into another data type.
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:
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
y=20
z=30
print(x,y,z, sep=’@’, end= ‘ ‘)
Output:
10@20@30
Data Types in Python
Data Types
Primitive Collection
Data Type Data Type
Number String
• 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
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
Python Operators
The operator is a symbol that performs a specific operation between two operands, according to
one definition.
• 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
+ Addition 10 + 20 = 30
- Subtraction 20 – 10 = 10
* Multiplication 10 * 20 = 200
/ Division 20 / 10 = 2
% Modulus 22 % 10 = 2
** Exponent 4**2 = 16
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)
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)
= 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
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)
<< 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
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
Operator Description
~+- Complement, unary plus and minus (method names for the last two are
+@ and -@)
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.
FLOW CONTROL
• Decision Making and branching (Conditional Statement)
• Looping or Iteration
• Jumping statements
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”)
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:
• range(stop)
• range(start, stop)
• [Link](start, stop, step)
Note:
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:
Output:
2
3
4
5
Range (start, stop, step): Third parameter specifies to increment or decrement the value byadding or
subtracting the value.
Example:
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
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
Output: Output:
1 java c++
2
4
5
6
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
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
statement(s)
statement(s)
Example:
for i in range(1,4):
for j in range(1,i):
print("*", end=" ")
print(" ")
if num%2==0:
print(num, " is even number")
else:
print(num, " is odd number")
if num%i==0:
print(num, "is not prime number")
break;
else:
print(num,"is prime number")
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")
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
else:
sum=0
for i in range(1,num):
if(num%i==0):
sum=sum+i
if num==sum:
print(num, "is perfect number")
else:
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
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:
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.
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.
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
Syntax:
function-name(parameter)
Example:
ADD(10,20)
OUTPUT:
Sum = 30.0
… .. …
def functionName(parameter):… .. …
… .. …
functionName(parameter)
… .. …
… .. …
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:
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
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
OUTPUT:
How many terms you want to display: 8
0 1 1 2 3 5 8 13
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
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.
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.
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 – 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.
‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
Example:
>>> 'abc'>'abcD' False
>>> 'ABC'<'abc' True
>>> 'abcd'>'aBcD' True
>>> 'aBcD'<='abCd' True
Function Description
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%@’
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
9 isspace( ) Returns True if there are only >>> " ".isspace() True
whitespace characters in the string.
>>> "".isspace() False
False otherwise.
14 split( ) breaks a string into words and creates a >>> str="Data Structure"
list out of it
>>> [Link]( ) ['Data',
'Structure']
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
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
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
>>> 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
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")
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'
Error: If the tuple contains values of different data types, then it will give an error because
mixed data type comparison is not possible.
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]
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.
List String
Mutable Immutable
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
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
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=[12,56,87,45,23,97,56,27]
>>> 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
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)
>>> [Link](-16,"TCS")
>>> company
['TCS', 'IBM', 'HCL', 'Apple',
'Wipro',
'Microsoft']
>>>
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'
>>>company=["IBM","HCL", "Wipro"]
>>> [Link](reverse=True)
>>> company
['Wipro', 'IBM',
'HCL']
>>> del L # deletes all elements and the list object too.
>>> L
NameError: name 'L' is not defined
2 Takes one element as argument Takes one list Takes two arguments,
asargument position and element.
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'
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
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
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
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}
(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
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 }
{}
>>> 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
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,
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
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
# 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
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.
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.
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
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.
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:
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.
What is NumPy?
• 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.
• 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.
If you have Python and PIP already installed on a system, then installation of NumPy is very easy.
Import NumPy
Once NumPy is installed, import it in your applications by adding the import keyword:
import numpy
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
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
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
[ 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.
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
Output
[3 4 5 6 7 8 9]
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]]]
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]
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])
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]
[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:
• 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.
• dtype: for the dtype data type. If not, the data type will be removed.
• copy: copies the data. the default value is false.
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()
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
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
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])
[Link]
[Link](arg, na_action=None)[source]
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
>>> [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
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
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.
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.
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.
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.
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.
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.
Use loop over the DictReader object to fetch individual dictionary objects.
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'}
<!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:
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
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.
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 –
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
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
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
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
[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
>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.
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
# 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"
o/p: [1] 9
o/p: 1 2 3
a 3 45
b 6 7 8
c 9 10 11
d 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
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))
[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.
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 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.
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
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
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())
The ls() function can use patterns to match the variable names. # List the variables starting with the pattern
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)
[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
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
}
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
}
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")
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
}
Output:
Repeat:
The Repeat loop executes the same code again and again until astop condition is met.
Syntax:
repeat
{
Commands
If(condition)
Break
}
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
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:
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.
Output
Mrs S Seetha, Asst Prof PROBLEM SOLVING USING PYTHON AND R
PG Department of CS
Arasu College of Arts & Science for Women, Karur
Example
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:
Syntax :
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”.
mapply
Definition: Multivariate version of lapply
Syntax: mapply (FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE, [Link]
= TRUE)
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
• 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:
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
toupper(x)
tolower(x)
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"
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.
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
[Link]("zoo")