SlideShare a Scribd company logo
1 of 86
Built-in Data structures
Strings
Strings
• Strings in Python have type str
• They represent sequence of characters
– Python does not have a type corresponding to
character.
• Strings are enclosed in single quotes(') or
double quotes(“)
– Both are equivalent
• Backslash () is used to escape quotes and
special characters
Strings
• More readable when print is used
Length of a String
• len function gives the length of a string
n is a single character:
the special character
representing newline
Concatenate and Repeat
• In Python, + and * operations have
special meaning when operating on
strings
• + is used for concatenation of (two)
strings
• * is used to repeat a string, an int number
of time
• Function/Operator Overloading
Concatenate and Repeat
Indexing
• Strings can be indexed
• First character has index 0
Indexing
• Negative indices start counting from the
right
• Negatives indices start from -1
• -1 means last, -2 second last, ...
Indexing
• Using an index that is too large or too
small results in “index out of range” error
Slicing
• To obtain a substring
• s[start:end] means substring of s starting
at index start and ending at index end-1
• s[0:len(s)] is same as s
• Both start and end are optional
– If start is omitted, it defaults to 0
– If end is omitted, it defaults to the length of
string
• s[:] is same as s[0:len(s)], that is same as s
Slicing
More Slicing
A c a d s
0 1 2 3 4
-5 -4 -3 -2 -1
Understanding Indices for slicing
5
Out of Range Slicing
• Out of range indices are ignored for slicing
• when start and end have the same sign, if start
>=end, empty slice is returned
Why?
A c a d s
0 1 2 3 4
-5 -4 -3 -2 -1
Changing Case
• string.capitalize() : returns a string with the first
character capitalized and all the rest in lower case.
>>> s1 = "eXamPLe tEXt"
>>> s1.capitalize()
Output: 'Example text'
• string.title() : capitalize every single word in the
string, leaving everything else as lowercase.
>>> s1.title()
Output: 'Example Text'
Changing Case
• string.upper() : convert the whole string to uppercase.
>>> s1 = "eXamPLe tEXt"
>>> s1.upper()
Output: 'EXAMPLE TEXT‘
• string.lower() : convert the whole string to lowercase.
>>> s1.lower()
Output: ‘example text'
• string.swapcase() : returns a copy of string with the
uppercase characters converted to lowercase and vice
versa.
>>> s1.swapcase()
Output: 'ExAMplE TexT'
Editing Strings
• string.strip([chars]) : returns a copy of the string with chars
removed from the beginning and the end if the sequence is
found. If no arguments are given, then remove whitespace
characters by default.
>>> s2=' hello world'
>>> s2.strip()
Output: 'hello world'
>>> s2=' hello world '
>>> s2.strip()
Output: 'hello world‘
>>> s2='hello world'
>>> s2.strip('he')
Output: 'llo world'
>>> s2.strip('world')
Output: 'hello '
Editing Strings
• string.lstrip([chars]): only strip characters from the start of
the string.
>>> s='hello worldhe'
>>> s.strip('he')
Output: 'llo world'
>>> s.lstrip('he')
Output: 'llo worldhe‘
• string.rstrip([chars]): only strip characters from the end of the
string.
• string.replace(old, new) : replace all occurrences of one
substring with another.
>>> s2='Hello World'
>>> s2.replace('H', 'J')
Output: 'Jello World‘
Finding Strings
• string.find([char]): get the position of the character in the string.
>>> s='hello world'
>>> s.find('h')
Output: 0
>>> s.find('w')
Output: 6
• string.count([chars]): count the number of times a substring occurs in a
string.
>>> s.count('o')
Output: 2
• string.endswith([chars]): check the string, whether it ends with specified
characters or not. (True/False)
>>> s.endswith('d')
Output: True
>>> s.endswith('ld')
Output: True
>>> s.endswith('o')
Output: False
Assignment-1
Q1. Write a program that reads full name as a input and returns
abbreviations of the first and middle names except the last
name.
(Note that the abbreviations must be in capitals. Also, only the
first letter in the Surname must be in upper case).
Example : Input: Sachin Ramesh Tendulkar
Output: S. R. Tendulkar
Q2. Write a program that reads names of two python files and
strips the extension. The filenames are then concatenated to
form a single string. The program then prints 'True' if the
newly generated string is palindrome, or prints 'False'
otherwise.
Example : Input: malay.py aLam.py
Output: True
Lists
• Ordered sequence of values
• Written as a sequence of comma-separated
values between square brackets
• Values can be of different types
– usually the items all have the same type
• Lists are mutable, which means we can add or
remove items from a list.
Lists
• List is also a sequence type
– Sequence operations are applicable
Lists
• List is also a sequence type
– Sequence operations are applicable
Repetition
( )
More Operations on Lists
• L.append(x)
• L.extend(seq)
• L.insert(i, x)
• L.remove(x)
• L.pop(i)
• L.pop()
• L.index(x)
• L.count(x)
• L.sort()
• L.reverse()
• max(L)
• min(L)
• test x in L
• test x not in L
x is any value, seq is a sequence value (list, string, tuple, …),
i is an integer value
Programming Exercise
Q16. Write a python program to perform following tasks:
- Read a list of integers from a user.
- Remove duplicate values from this list. We call it a
super list. Display contents of the super list
Q17. In a single scan of the super list (generated in Q16),
perform following operations:
- If the number is not perfectly divisible by 3, discard it.
- If the number is greater than 30, add 5 to it. Else,
subtract 5 from it.
- Display contents of the list.
Tuples
• A tuple consists of a number of values
separated by commas
• Empty and Singleton Tuples
Nested Tuples
• Tuples can be nested
• Note that course tuple is copied into
student.
– Changing course does not affect student
More Operations on Tuples
• Tuples can be concatenated, repeated,
indexed and sliced
Unpacking Sequences
• Strings and Tuples are examples of
sequences
– Indexing, slicing, concatenation, repetition
operations applicable on sequences
• Sequence Unpacking operation can be
applied to sequences to get the
components
– Multiple assignment statement
– LHS and RHS must have equal length
Unpacking Sequences
( )
Programming Exercise
Q18. Write a python program to perform following tasks:
- Read tuple elements (integers) from a user.
- Display the sum of tuple elements.
- Count the number of occurrence of each element from a
tuple
Sets
• An unordered collection with no duplicate
elements
• Supports
– membership testing
– eliminating duplicate entries
– Set operations: union, intersection, difference,
and symmetric difference.
Sets
Create a set from
a sequence
{ }
Set Operations
{ }
{ }
{ }
{
{ }
Dictionaries
• Unordered set of key:value pairs,
• Keys have to be unique and immutable
• Key:value pairs enclosed inside curly
braces {...}
• Empty dictionary is created by writing {}
• Dictionaries are mutable
– add new key:value pairs,
– change the pairing
– delete a key (and associated value)
Operations on Dictionaries
Operation Meaning
len(d) Number of key:value pairs in d
d.keys() List containing the keys in d
d.values() List containing the values in d
k in d True if key k is in d
d[k] Value associated with key k in d
d.get(k, v) If k is present in d, then d[k] else v
d[k] = v Map the value v to key k in d
(replace d[k] if present)
del d[k] Remove key k (and associated value) from d
for k in d Iterate over the keys in d
Operations on Dictionaries
Operations on Dictionaries
Operations on Dictionaries
# Remember: for ... in iterates over keys only
# Sort values in a list
Dictionary Construction
• The dict constructor: builds dictionaries
directly from sequences of key-value pairs
Programming Exercise
Q19. Given a piece of text, write a program to
build a frequency listing of words and display
them in a sorted order on 'key'.
File Operations in Python
File I/O
• A file is a place on disk where group of related
data are stored.
• Files are persistent storage
• Allow data to be stored beyond program
lifetime
• The basic operations on files are
– open(), close(), read(), write()
• Python treat files as sequence of lines
– sequence operations work for the data read from
files
File I/O: open and close
open(filename, mode)
• While opening a file, you need to supply
– The name of the file, including the path
– The mode in which you want to open a file
– Common modes are r (read), w (write), a
(append)
• Mode is optional, defaults to r
• open(..) returns a file object
• close() on the file object closes the file
– finishes any buffered operations
• r+ opens a text file in both reading and writing mode
• w+ opens a text file in both reading and writing mode
• a+ opens a text file in both reading and append mode
• rb opens a binary file in reading mode
• wb opens or create a binary file in writing mode
• ab opens a binary file in append mode
• rb+ opens a binary file in both reading and writing mode
• wb+ opens a binary file in both reading and writing
mode
• ab+ opens a binary file for both reading as well as
appending.
File I/O: Example
• Do some writing
File I/O: read, write and append
• Reading from an open file returns the
contents of the file
– as sequence of lines in the program
• Writing to a file
– IMPORTANT: If opened with mode 'w',
clears the existing contents of the file
– Use append mode ('a') to preserve the
contents
– Writing happens at the end
File I/O: Examples
File I/O: Examples
(
( )
)
File I/O: Examples
Note empty line due to 'n'
( )
File I/O: Examples
Note the use of for ... in
for sequence
]
( )
File I/O: Examples
( )
( )
( )
Random access to files
• How to jump to a given position (byte number) in
a file without reading all the previous data?
• seek (offset, position);
• position: 0 (beginning), 1 (current), 2 (end)
• offset: number of locations to move from position
Example: fo.seek(-m, 1); /* move back by m bytes from
current position */
fo.seek(m,0); /* move to (m+1)th byte in file */
fo.seek(-10, 2);
• fo.tell( ) returns current byte position in file
Some more read & write functions
• read() : This function reads the entire file and
returns a string.
• readline() : This function reads lines from
that file and returns as a string.
• readlines() : This function returns a list where
each element is a single line of that file.
• write() : This function writes a fixed sequence
of characters to a file.
• writelines() : This function write a list of
string
Programming Exercise
Q20. Write a python program to read the content
from the text file “file.txt” line by line and
display the same on screen.
Q21. Write a python program to count and
display the total number of words in a text file
“file.txt”.
Q22. Write a python program to perform writing
and reading few lines in a text file .
Exception Handling in Python
Syntax errors
• Syntax errors are generated if the rules for
syntax are not followed while writing a
script in Python.
• Syntax errors are the most basic type of
errors.
• There is no way to successfully execute a
piece of code containing syntax errors.
• Most syntax errors are typos (i.e., typing
errors), incorrect indentation or incorrect
arguments.
Exception
• An exception is an error, which happens
during the execution of a program, that
disrupts the normal flow of the program's
instructions.
• In general, when a Python script encounters a
situation that it can't cope with, it raises an
exception.
• For example, trying to open a file that does not
exist, division by zero and so on. Such types of
errors might disrupt the normal execution of
the program and are called exceptions.
The raise Statement
• The raise statement can be used to throw an
exception.
• The syntax of raise statement is:
raise exception-name[(optional argument)]
• The argument is generally a string that is
displayed when the exception is raised.
• The error detected may be a built-in
exception or may be a user-defined one
Built-in exceptions
The assert Statement
• An assert statement in Python is used
to test an expression in the program code.
• The syntax for assert statement is:
assert Expression[,arguments]
• If this expression is false, an
AssertionError exception is raised which
can be handled like any other exception.
Example-The assert Statement
print("use of assert statement")
def negativecheck(number):
assert(number>=0), "OOPS... Negative Number“
print(number*number)
print (negativecheck(100))
print (negativecheck(-350))
use of assert statement
10000
None
Traceback (most recent call last):
File "C:/Python32/Assert.py", line 6, in <module>
print (negativecheck(-350))
File "C:/Python32/Assert.py", line 3, in negativecheck
assert(number>=0), "OOPS... Negative Number"
AssertionError: OOPS... Negative Number
Exception Handling
• Every exception has to be handled by
the programmer.
• This is done by writing additional code
in a program to give proper messages or
instructions to the user on encountering an
exception.
• This process is known as exception
handling.
Catching Exceptions
• Exceptions, if any, are caught in the try
block and handled in the except block.
• The syntax of try … except clause is as
follows:
try:
[program statements where exceptions might occur]
except [exception-name]:
[code for exception handling if the exception-name error is
Encountered]
Example-Catching Exceptions
print ("Practicing for try block")
try:
numerator=50
denom=int(input("Enter the denominator"))
quotient=(numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO.... not allowed")
print(“OUTSIDE try..except block”)
Multiple except clauses
print ("Handling multiple exceptions")
try:
numerator=50
denom=int(input("Enter the denominator: "))
print (numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
except without specifying an
exception
print ("Handling multiple exceptions")
try:
numerator=50
denom=int(input("Enter the denominator: "))
print (numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except :
print(" OOPS.....SOME EXCEPTION RAISED")
try...except…else clause
print ("Handling exception using try...except...else")
try:
numerator=50
denom=int(input("Enter the denominator: "))
quotient=(numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
else:
print ("The result of division operation is ", quotient)
finally clause
• finally should always be placed at the end
of try clause, after all except blocks and
the else block.
• The statements inside the finally block
are always executed regardless of whether
an exception has occurred in the try
block or not.
Example-finally clause
try:
print ("Handling exception using try...except...else...finally")
numerator=50
denom=int(input("Enter the denominator: "))
quotient=(numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
else:
print ("The result of division operation is ", quotient)
finally:
print ("OVER AND OUT“)
Modules and Packages
Modules
• As program gets longer, need to organize them for
easier access and easier maintenance.
• Reuse same functions across programs without
copying its definition into each program.
• Python allows putting definitions in a file
– use them in a script or in an interactive instance of the
interpreter
• Such a file is called a module
– definitions from a module can be imported into other
modules or into the main module
Modules
• A module is a file containing Python definitions
and statements.
• The file name is the module name with the suffix
.py appended.
• Within a module, the module’s name is available
in the global variable __name__.
Modules Example
fib.py - C:
Modules Example
Within a module, the
module’s name is
available as the value of
the global variable
__name__.
Importing Specific Functions
• To import specific functions from a module
• This brings only the imported functions in the current
symbol table
– No need of modulename. (absence of fib. in the example)
Importing ALL Functions
• To import all functions from a module, in the
current symbol table
• This imports all names except those beginning
with an underscore (_).
__main__ in Modules
• When you run a module on the command line with
python fib.py <arguments>
the code in the module will be executed, just as if
you imported it, but with the __name__ set to
"__main__".
• By adding this code at the end of your module
if __name__ == "__main__":
... # Some code here
you can make the file usable as a script as well as an
importable module
__main__ in Modules
if __name__ == "__main__":
import sys
print (fib_iter(int(sys.argv[1])))
• This code parses the command line only if
the module is executed as the “main” file:
$ python fib.py 10
55
• If the module is imported, the code is not
run:
>>> import fib
>>>
Package
• A Python package is a collection of Python
modules.
• Another level of organization.
• Packages are a way of structuring Python’s module
namespace by using dotted module names.
– The module name A.B designates a submodule
named B in a package named A.
– The use of dotted module names saves the authors of
multi-module packages like NumPy or Pillow from
having to worry about each other’s module names.
https://docs.python.org/3/tutorial/modules.html
A sound Package
https://docs.python.org/3/tutorial/modules.html
A sound Package
What are these files
with funny names?
__init.py__
• The __init__.py files are required to make
Python treat directories containing the file as
packages.
• This prevents directories with a common
name, such as string, unintentionally hiding
valid modules that occur later on the module
search path.
• __init__.py can just be an empty file
• It can also execute initialization code for the
package
Importing Modules from Packages
https://docs.python.org/3/tutorial/modules.ht
ml
Importing Modules from Packages
import sound.effects.echo
• Loads the submodule sound.effects.echo
• It must be referenced with its full name:
sound.effects.echo.echofilter(
input, output,
delay=0.7, atten=4
)
Importing Modules from Packages
from sound.effects import echo
• This also loads the submodule echo
• Makes it available without package prefix
• It can be used as:
echo.echofilter(
input, output,
delay=0.7, atten=4
)
Importing Modules from Packages
from sound.effects.echo import echofilter
• This loads the submodule echo, but this
makes its function echofilter() directly
available.
echofilter(input, output,
delay=0.7, atten=4)

More Related Content

Similar to Python_Unit_III.pptx

Similar to Python_Unit_III.pptx (20)

Python basics
Python basicsPython basics
Python basics
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Python Basics
Python BasicsPython Basics
Python Basics
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Lenguaje Python
Lenguaje PythonLenguaje Python
Lenguaje Python
 
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.pptpysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
 
coolstuff.ppt
coolstuff.pptcoolstuff.ppt
coolstuff.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
Introductio_to_python_progamming_ppt.ppt
Introductio_to_python_progamming_ppt.pptIntroductio_to_python_progamming_ppt.ppt
Introductio_to_python_progamming_ppt.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
 
manish python.pptx
manish python.pptxmanish python.pptx
manish python.pptx
 
Programming in Python
Programming in Python Programming in Python
Programming in Python
 
Kavitha_python.ppt
Kavitha_python.pptKavitha_python.ppt
Kavitha_python.ppt
 
1. python programming
1. python programming1. python programming
1. python programming
 
ENGLISH PYTHON.ppt
ENGLISH PYTHON.pptENGLISH PYTHON.ppt
ENGLISH PYTHON.ppt
 
UNIT 4 python.pptx
UNIT 4 python.pptxUNIT 4 python.pptx
UNIT 4 python.pptx
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 

Recently uploaded

HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 

Recently uploaded (20)

HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 

Python_Unit_III.pptx

  • 2. Strings • Strings in Python have type str • They represent sequence of characters – Python does not have a type corresponding to character. • Strings are enclosed in single quotes(') or double quotes(“) – Both are equivalent • Backslash () is used to escape quotes and special characters
  • 3. Strings • More readable when print is used
  • 4. Length of a String • len function gives the length of a string n is a single character: the special character representing newline
  • 5. Concatenate and Repeat • In Python, + and * operations have special meaning when operating on strings • + is used for concatenation of (two) strings • * is used to repeat a string, an int number of time • Function/Operator Overloading
  • 7. Indexing • Strings can be indexed • First character has index 0
  • 8. Indexing • Negative indices start counting from the right • Negatives indices start from -1 • -1 means last, -2 second last, ...
  • 9. Indexing • Using an index that is too large or too small results in “index out of range” error
  • 10. Slicing • To obtain a substring • s[start:end] means substring of s starting at index start and ending at index end-1 • s[0:len(s)] is same as s • Both start and end are optional – If start is omitted, it defaults to 0 – If end is omitted, it defaults to the length of string • s[:] is same as s[0:len(s)], that is same as s
  • 12. More Slicing A c a d s 0 1 2 3 4 -5 -4 -3 -2 -1 Understanding Indices for slicing 5
  • 13. Out of Range Slicing • Out of range indices are ignored for slicing • when start and end have the same sign, if start >=end, empty slice is returned Why? A c a d s 0 1 2 3 4 -5 -4 -3 -2 -1
  • 14. Changing Case • string.capitalize() : returns a string with the first character capitalized and all the rest in lower case. >>> s1 = "eXamPLe tEXt" >>> s1.capitalize() Output: 'Example text' • string.title() : capitalize every single word in the string, leaving everything else as lowercase. >>> s1.title() Output: 'Example Text'
  • 15. Changing Case • string.upper() : convert the whole string to uppercase. >>> s1 = "eXamPLe tEXt" >>> s1.upper() Output: 'EXAMPLE TEXT‘ • string.lower() : convert the whole string to lowercase. >>> s1.lower() Output: ‘example text' • string.swapcase() : returns a copy of string with the uppercase characters converted to lowercase and vice versa. >>> s1.swapcase() Output: 'ExAMplE TexT'
  • 16. Editing Strings • string.strip([chars]) : returns a copy of the string with chars removed from the beginning and the end if the sequence is found. If no arguments are given, then remove whitespace characters by default. >>> s2=' hello world' >>> s2.strip() Output: 'hello world' >>> s2=' hello world ' >>> s2.strip() Output: 'hello world‘ >>> s2='hello world' >>> s2.strip('he') Output: 'llo world' >>> s2.strip('world') Output: 'hello '
  • 17. Editing Strings • string.lstrip([chars]): only strip characters from the start of the string. >>> s='hello worldhe' >>> s.strip('he') Output: 'llo world' >>> s.lstrip('he') Output: 'llo worldhe‘ • string.rstrip([chars]): only strip characters from the end of the string. • string.replace(old, new) : replace all occurrences of one substring with another. >>> s2='Hello World' >>> s2.replace('H', 'J') Output: 'Jello World‘
  • 18. Finding Strings • string.find([char]): get the position of the character in the string. >>> s='hello world' >>> s.find('h') Output: 0 >>> s.find('w') Output: 6 • string.count([chars]): count the number of times a substring occurs in a string. >>> s.count('o') Output: 2 • string.endswith([chars]): check the string, whether it ends with specified characters or not. (True/False) >>> s.endswith('d') Output: True >>> s.endswith('ld') Output: True >>> s.endswith('o') Output: False
  • 19. Assignment-1 Q1. Write a program that reads full name as a input and returns abbreviations of the first and middle names except the last name. (Note that the abbreviations must be in capitals. Also, only the first letter in the Surname must be in upper case). Example : Input: Sachin Ramesh Tendulkar Output: S. R. Tendulkar Q2. Write a program that reads names of two python files and strips the extension. The filenames are then concatenated to form a single string. The program then prints 'True' if the newly generated string is palindrome, or prints 'False' otherwise. Example : Input: malay.py aLam.py Output: True
  • 20. Lists • Ordered sequence of values • Written as a sequence of comma-separated values between square brackets • Values can be of different types – usually the items all have the same type • Lists are mutable, which means we can add or remove items from a list.
  • 21. Lists • List is also a sequence type – Sequence operations are applicable
  • 22. Lists • List is also a sequence type – Sequence operations are applicable Repetition ( )
  • 23. More Operations on Lists • L.append(x) • L.extend(seq) • L.insert(i, x) • L.remove(x) • L.pop(i) • L.pop() • L.index(x) • L.count(x) • L.sort() • L.reverse() • max(L) • min(L) • test x in L • test x not in L x is any value, seq is a sequence value (list, string, tuple, …), i is an integer value
  • 24. Programming Exercise Q16. Write a python program to perform following tasks: - Read a list of integers from a user. - Remove duplicate values from this list. We call it a super list. Display contents of the super list Q17. In a single scan of the super list (generated in Q16), perform following operations: - If the number is not perfectly divisible by 3, discard it. - If the number is greater than 30, add 5 to it. Else, subtract 5 from it. - Display contents of the list.
  • 25. Tuples • A tuple consists of a number of values separated by commas • Empty and Singleton Tuples
  • 26. Nested Tuples • Tuples can be nested • Note that course tuple is copied into student. – Changing course does not affect student
  • 27. More Operations on Tuples • Tuples can be concatenated, repeated, indexed and sliced
  • 28. Unpacking Sequences • Strings and Tuples are examples of sequences – Indexing, slicing, concatenation, repetition operations applicable on sequences • Sequence Unpacking operation can be applied to sequences to get the components – Multiple assignment statement – LHS and RHS must have equal length
  • 30. Programming Exercise Q18. Write a python program to perform following tasks: - Read tuple elements (integers) from a user. - Display the sum of tuple elements. - Count the number of occurrence of each element from a tuple
  • 31. Sets • An unordered collection with no duplicate elements • Supports – membership testing – eliminating duplicate entries – Set operations: union, intersection, difference, and symmetric difference.
  • 32. Sets Create a set from a sequence { }
  • 33. Set Operations { } { } { } { { }
  • 34. Dictionaries • Unordered set of key:value pairs, • Keys have to be unique and immutable • Key:value pairs enclosed inside curly braces {...} • Empty dictionary is created by writing {} • Dictionaries are mutable – add new key:value pairs, – change the pairing – delete a key (and associated value)
  • 35. Operations on Dictionaries Operation Meaning len(d) Number of key:value pairs in d d.keys() List containing the keys in d d.values() List containing the values in d k in d True if key k is in d d[k] Value associated with key k in d d.get(k, v) If k is present in d, then d[k] else v d[k] = v Map the value v to key k in d (replace d[k] if present) del d[k] Remove key k (and associated value) from d for k in d Iterate over the keys in d
  • 38. Operations on Dictionaries # Remember: for ... in iterates over keys only # Sort values in a list
  • 39. Dictionary Construction • The dict constructor: builds dictionaries directly from sequences of key-value pairs
  • 40. Programming Exercise Q19. Given a piece of text, write a program to build a frequency listing of words and display them in a sorted order on 'key'.
  • 42. File I/O • A file is a place on disk where group of related data are stored. • Files are persistent storage • Allow data to be stored beyond program lifetime • The basic operations on files are – open(), close(), read(), write() • Python treat files as sequence of lines – sequence operations work for the data read from files
  • 43. File I/O: open and close open(filename, mode) • While opening a file, you need to supply – The name of the file, including the path – The mode in which you want to open a file – Common modes are r (read), w (write), a (append) • Mode is optional, defaults to r • open(..) returns a file object • close() on the file object closes the file – finishes any buffered operations
  • 44. • r+ opens a text file in both reading and writing mode • w+ opens a text file in both reading and writing mode • a+ opens a text file in both reading and append mode • rb opens a binary file in reading mode • wb opens or create a binary file in writing mode • ab opens a binary file in append mode • rb+ opens a binary file in both reading and writing mode • wb+ opens a binary file in both reading and writing mode • ab+ opens a binary file for both reading as well as appending.
  • 45. File I/O: Example • Do some writing
  • 46. File I/O: read, write and append • Reading from an open file returns the contents of the file – as sequence of lines in the program • Writing to a file – IMPORTANT: If opened with mode 'w', clears the existing contents of the file – Use append mode ('a') to preserve the contents – Writing happens at the end
  • 49. File I/O: Examples Note empty line due to 'n' ( )
  • 50. File I/O: Examples Note the use of for ... in for sequence ] ( )
  • 51. File I/O: Examples ( ) ( ) ( )
  • 52. Random access to files • How to jump to a given position (byte number) in a file without reading all the previous data? • seek (offset, position); • position: 0 (beginning), 1 (current), 2 (end) • offset: number of locations to move from position Example: fo.seek(-m, 1); /* move back by m bytes from current position */ fo.seek(m,0); /* move to (m+1)th byte in file */ fo.seek(-10, 2); • fo.tell( ) returns current byte position in file
  • 53. Some more read & write functions • read() : This function reads the entire file and returns a string. • readline() : This function reads lines from that file and returns as a string. • readlines() : This function returns a list where each element is a single line of that file. • write() : This function writes a fixed sequence of characters to a file. • writelines() : This function write a list of string
  • 54. Programming Exercise Q20. Write a python program to read the content from the text file “file.txt” line by line and display the same on screen. Q21. Write a python program to count and display the total number of words in a text file “file.txt”. Q22. Write a python program to perform writing and reading few lines in a text file .
  • 56. Syntax errors • Syntax errors are generated if the rules for syntax are not followed while writing a script in Python. • Syntax errors are the most basic type of errors. • There is no way to successfully execute a piece of code containing syntax errors. • Most syntax errors are typos (i.e., typing errors), incorrect indentation or incorrect arguments.
  • 57. Exception • An exception is an error, which happens during the execution of a program, that disrupts the normal flow of the program's instructions. • In general, when a Python script encounters a situation that it can't cope with, it raises an exception. • For example, trying to open a file that does not exist, division by zero and so on. Such types of errors might disrupt the normal execution of the program and are called exceptions.
  • 58. The raise Statement • The raise statement can be used to throw an exception. • The syntax of raise statement is: raise exception-name[(optional argument)] • The argument is generally a string that is displayed when the exception is raised. • The error detected may be a built-in exception or may be a user-defined one
  • 60. The assert Statement • An assert statement in Python is used to test an expression in the program code. • The syntax for assert statement is: assert Expression[,arguments] • If this expression is false, an AssertionError exception is raised which can be handled like any other exception.
  • 61. Example-The assert Statement print("use of assert statement") def negativecheck(number): assert(number>=0), "OOPS... Negative Number“ print(number*number) print (negativecheck(100)) print (negativecheck(-350)) use of assert statement 10000 None Traceback (most recent call last): File "C:/Python32/Assert.py", line 6, in <module> print (negativecheck(-350)) File "C:/Python32/Assert.py", line 3, in negativecheck assert(number>=0), "OOPS... Negative Number" AssertionError: OOPS... Negative Number
  • 62. Exception Handling • Every exception has to be handled by the programmer. • This is done by writing additional code in a program to give proper messages or instructions to the user on encountering an exception. • This process is known as exception handling.
  • 63. Catching Exceptions • Exceptions, if any, are caught in the try block and handled in the except block. • The syntax of try … except clause is as follows: try: [program statements where exceptions might occur] except [exception-name]: [code for exception handling if the exception-name error is Encountered]
  • 64. Example-Catching Exceptions print ("Practicing for try block") try: numerator=50 denom=int(input("Enter the denominator")) quotient=(numerator/denom) print ("Division performed successfully") except ZeroDivisionError: print ("Denominator as ZERO.... not allowed") print(“OUTSIDE try..except block”)
  • 65. Multiple except clauses print ("Handling multiple exceptions") try: numerator=50 denom=int(input("Enter the denominator: ")) print (numerator/denom) print ("Division performed successfully") except ZeroDivisionError: print ("Denominator as ZERO is not allowed") except ValueError: print ("Only INTEGERS should be entered")
  • 66. except without specifying an exception print ("Handling multiple exceptions") try: numerator=50 denom=int(input("Enter the denominator: ")) print (numerator/denom) print ("Division performed successfully") except ZeroDivisionError: print ("Denominator as ZERO is not allowed") except : print(" OOPS.....SOME EXCEPTION RAISED")
  • 67. try...except…else clause print ("Handling exception using try...except...else") try: numerator=50 denom=int(input("Enter the denominator: ")) quotient=(numerator/denom) print ("Division performed successfully") except ZeroDivisionError: print ("Denominator as ZERO is not allowed") except ValueError: print ("Only INTEGERS should be entered") else: print ("The result of division operation is ", quotient)
  • 68. finally clause • finally should always be placed at the end of try clause, after all except blocks and the else block. • The statements inside the finally block are always executed regardless of whether an exception has occurred in the try block or not.
  • 69. Example-finally clause try: print ("Handling exception using try...except...else...finally") numerator=50 denom=int(input("Enter the denominator: ")) quotient=(numerator/denom) print ("Division performed successfully") except ZeroDivisionError: print ("Denominator as ZERO is not allowed") except ValueError: print ("Only INTEGERS should be entered") else: print ("The result of division operation is ", quotient) finally: print ("OVER AND OUT“)
  • 71. Modules • As program gets longer, need to organize them for easier access and easier maintenance. • Reuse same functions across programs without copying its definition into each program. • Python allows putting definitions in a file – use them in a script or in an interactive instance of the interpreter • Such a file is called a module – definitions from a module can be imported into other modules or into the main module
  • 72. Modules • A module is a file containing Python definitions and statements. • The file name is the module name with the suffix .py appended. • Within a module, the module’s name is available in the global variable __name__.
  • 74. Modules Example Within a module, the module’s name is available as the value of the global variable __name__.
  • 75. Importing Specific Functions • To import specific functions from a module • This brings only the imported functions in the current symbol table – No need of modulename. (absence of fib. in the example)
  • 76. Importing ALL Functions • To import all functions from a module, in the current symbol table • This imports all names except those beginning with an underscore (_).
  • 77. __main__ in Modules • When you run a module on the command line with python fib.py <arguments> the code in the module will be executed, just as if you imported it, but with the __name__ set to "__main__". • By adding this code at the end of your module if __name__ == "__main__": ... # Some code here you can make the file usable as a script as well as an importable module
  • 78. __main__ in Modules if __name__ == "__main__": import sys print (fib_iter(int(sys.argv[1]))) • This code parses the command line only if the module is executed as the “main” file: $ python fib.py 10 55 • If the module is imported, the code is not run: >>> import fib >>>
  • 79. Package • A Python package is a collection of Python modules. • Another level of organization. • Packages are a way of structuring Python’s module namespace by using dotted module names. – The module name A.B designates a submodule named B in a package named A. – The use of dotted module names saves the authors of multi-module packages like NumPy or Pillow from having to worry about each other’s module names.
  • 82. __init.py__ • The __init__.py files are required to make Python treat directories containing the file as packages. • This prevents directories with a common name, such as string, unintentionally hiding valid modules that occur later on the module search path. • __init__.py can just be an empty file • It can also execute initialization code for the package
  • 83. Importing Modules from Packages https://docs.python.org/3/tutorial/modules.ht ml
  • 84. Importing Modules from Packages import sound.effects.echo • Loads the submodule sound.effects.echo • It must be referenced with its full name: sound.effects.echo.echofilter( input, output, delay=0.7, atten=4 )
  • 85. Importing Modules from Packages from sound.effects import echo • This also loads the submodule echo • Makes it available without package prefix • It can be used as: echo.echofilter( input, output, delay=0.7, atten=4 )
  • 86. Importing Modules from Packages from sound.effects.echo import echofilter • This loads the submodule echo, but this makes its function echofilter() directly available. echofilter(input, output, delay=0.7, atten=4)