0% found this document useful (0 votes)
9 views76 pages

Python Programming Overview and History

The document provides an overview of Python, highlighting its simplicity, ease of learning, and versatility as a programming language. It covers Python's history, features such as being interpreted and object-oriented, and its extensive libraries, while also discussing its application in various fields and companies. Additionally, it touches on Python's data types, semantics, and mathematical operations, making it suitable for rapid development and prototyping.

Uploaded by

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

Python Programming Overview and History

The document provides an overview of Python, highlighting its simplicity, ease of learning, and versatility as a programming language. It covers Python's history, features such as being interpreted and object-oriented, and its extensive libraries, while also discussing its application in various fields and companies. Additionally, it touches on Python's data types, semantics, and mathematical operations, making it suitable for rapid development and prototyping.

Uploaded by

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

16-09-2024

Dr Perugu Shyam
[Link], PGDBI, [Link], Ph.D
Assistant Professor
Department of Biotechnology
National Institute of Technology Warangal

1
16-09-2024

python
• Simple
• Python is a simple and minimalistic language in nature
• Reading a good python program should be like reading English
• Its Pseudo-code nature allows one to concentrate on the problem rather
than the language

• Easy to Learn

• Free & Open source


• Freely distributed and Open source
• Maintained by the Python community

• High Level Language –memory management

• Portable – *runs on anything C code will

python
• Interpreted
• You run the program straight from the source code.
• Python program → Bytecode → a platforms native language
• You can just copy over your code to another system and it will automatically
work with python platform

• Object-Oriented
• Simple and additionally supports procedural programming
• Extensible – easily import other code
• Embeddable –easily place your code in non-python programs
• Extensive libraries
• (i.e. reg. expressions, doc generation, CGI, ftp, web browsers, ZIP, WAV,
cryptography, etc...) (wxPython, Twisted, Python Imaging library)

2
16-09-2024

python Timeline/History
• Python was conceived in the late 1980s.
• Guido van Rossum, Benevolent Dictator For Life
• Rossum is Dutch, born in Netherlands
• Descendant of ABC, he wrote glob( ) func in UNIX
• He worked @ Univ of Amsterdam, worked for CWI, NIST, CNRI,
Google
• Also, helped develop the ABC programming language

• In 1991 python 0.9.0 was published and reached the masses

• In January of 1994 python 1.0 was released


• Functional programming tools like lambda, map, filter, and reduce
• [Link] formed, greatly increasing python’s userbase

python Timeline/History
• In 1995, python 1.2 was released.
• By version 1.4 python had several new features
• Keyword arguments (similar to those of common lisp)
• Built-in support for complex numbers
• Basic form of data-hiding through name mangling (easily
bypassed however)

• Computer Programming for Everybody (CP4E) initiative


• Make programming accessible to more people, with basic “literacy”
similar to those required for English and math skills for some jobs.
• Project was funded by DARPA
• CP4E was inactive as of 2007, not so much a concern to get employees
programming “literate”

3
16-09-2024

python Timeline/History
• In 2000, Python 2.0 was released.
• Introduced list comprehensions similar to Haskells
• Introduced garbage collection
• In 2001, Python 2.2 was released.
• Included unification of types and classes into one hierarchy,
making pythons object model purely Object-oriented
• Generators were added(function-like iterator behavior)
• Standards
• [Link]

Latest versions of Python


• Python 3.8. 1, documentation released on 18
December 2019.
• Python 3.8. 0, documentation released on 14
October 2019.
• Python 3.7. 6, documentation released on 18
December 2019.
• Python 3.7. 5, documentation released on 15
October 2019.

4
16-09-2024

Scripting language: A script is a program that controls other programs.


Scripting languages are good for quick development and prototyping because
they're good at passing messages from one component to another and at
handling fiddly stuff like memory management so that the programmer doesn't
have to. Python has grown beyond scripting languages, which are used mostly
for small applications.

The Python community prefers to call Python a dynamic programming


language.

Indentation for statement grouping: Python specifies that several statements


are part of a single group by indenting them. The indented group is called a
code block. Other languages use different syntax or punctuation for statement
grouping.

For example, the C programming language uses { to begin an instruction and }


to end it. Indentation is considered good practice in other languages also, but
Python was one of the first to enforce indentation. Indentation makes code
easier to read, and code blocks set off with indentation have fewer begin/end
words and punctuation to accidentally leave out (which means fewer bugs).

High-level data types: Computers store everything in 1s and 0s, but humans need to
work with data in more complex forms, such as text. A language that supports such
complex data is said to have high-level data types. A high-level data type is easy to
manipulate. For example, Python strings can be searched, sliced, joined, split, set to
upper- or lowercase, or have white space removed.

Extensibility: An extensible programming language can be added to. These languages


are very powerful because additions make them suitable for multiple applications and
operating systems. Extensions can add data types or concepts, modules, and plug-ins.
Python is extensible in several ways. A core group of programmers works on modifying
and improving the language, while hundreds of other programmers write modules for
specific purposes.

Interpreted: Interpreted languages run directly from source code that humans
generate. Interpreted languages run more slowly because the translation takes place
on the fly, but development and debugging is faster because you don't have to wait for
the compiler. Interpreted languages are easier to run on multiple operating systems.
In the case of Python, it's easy to write code that works on multiple operating
systems—with no need to make modifications.

5
16-09-2024

High-level features make Python a wise alternative for prototyping


and fast development of complex applications:

Python is interpreted, so writing working programs and fixing


mistakes in programs is fast.

TECHNICAL
STUFF
Programs written in interpreted languages can be tested as
soon as they're written, without waiting for the code to compile.

Python takes care of such complex details as memory management


behind the scenes.

Python has debugging features built in.

All features make Python a good language for

• Off-the-cuff, quick programming


• Prototyping (sketching the design basics of complex
programs, or testing particular solutions)
• Applications that change, build on themselves, and
add new features frequently

6
16-09-2024

• Python is a multi-paradigm language (meaning it supports more


than one style or philosophy of programming).

• This makes it good for applications that benefit from a


flexible approach to programming. Python includes tools for
the following paradigms:

• Object-oriented programming (OOP) is one of the


popular programming styles that Python supports.
OOP breaks up code into individual units that pass
messages back and forth.

• Tip Object-oriented programming is good for


applications that have multiple parts that need to
communicate with each other.

• Python has features in common with the following


languages:

7
16-09-2024

• Java: An object-oriented language especially for


applications used over networks
• Perl: A procedural language used for text
manipulation, system administration, Web
development, and network programming
• TCL(Tool Command Language): Used for rapid
prototyping, scripting, GUIs, and testing
• Scheme: A functional programming language (a
language that focuses on performing actions and
calculations by using functions.

Versatility
Python modules (collections of features for performing
tasks)

Multiple operating systems and user interfaces


Tip With Python For Dummies, you can write and run
programs on Windows, Mac, and Unix (including Linux).

Python programmers have also written code for other


operating systems, from cell phones to supercomputers.

· Special kinds of data (such as images and sound)

8
16-09-2024

Companies that use Python

• The main portal to Python and the Python community is


[Link] This portal contains a page that lists some
companies that use Python, including
• Yahoo! (for Yahoo! Maps)
• Google (for its spider and search engine)
• Linux Weekly News (published by using a Web application written
in Python)
• Industrial Light & Magic (used in the production of special effects
for such movies as The Phantom Menace and The Mummy
Returns).

• Other commercial uses include financial applications,


educational software, games, and business software.

Languages
• Some influential ones:

• FORTRAN
• science / engineering

• COBOL
• business data

• LISP
• logic and AI

• BASIC
• a simple language

18

9
16-09-2024

Python types
• Str, unicode – ‘MyString’, u‘MyString’
• List – [ 69, 6.9, ‘mystring’, True]
• Tuple – (69, 6.9, ‘mystring’, True) immutable
• Dictionary or hash – {‘key 1’: 6.9, ‘key2’: False} - group of key and
value pairs

Python types
• Int – 42- may be transparently expanded to long
through 438324932L
• Float – 2.171892
• Complex – 4 + 3j
• Bool – True or False

10
16-09-2024

• input: Get data from the keyboard, a file, or some


other device.
• output: Display data on the screen or send data to a
file or other device.
• math: Perform basic mathematical operations like
addition and multiplication.
• conditional execution: Check for certain conditions
and execute the appropriate sequence of statements.
• repetition: Perform some action repeatedly, usually
with some variation.

11
16-09-2024

Python semantics
• Each statement has its own semantics, the def
statement doesn’t get executed immediately like other
statements

• Python uses duck typing, or latent typing


• Allows for polymorphism without inheritance
• This means you can just declare
“somevariable = 69” don’t actually have to declare a type

• print “somevariable = “ + tostring(somevariable)”


strong typing, can’t do operations on objects not defined
without explicitly asking the operation to be done

• code or source code: The sequence of instructions in a


program.
• syntax: The set of legal structures and commands that
can be used in a particular programming language.
• output: The messages printed to the user by a
program.
• console: The text box onto which output is printed.
• Some source code editors pop up the console as an external
window, and others contain their own console window.

24

12
16-09-2024

Expressions
• expression: A data value or set of operations to compute
a value.
Examples: 1 + 4 * 3

• Arithmetic operators we will use:


• + - * / addition, subtraction/negation,
multiplication,
• division
• % modulus, a.k.a. remainder
• ** exponentiation

• precedence: Order in which operations are computed.


• * / % ** have a higher precedence than + -
1 + 3 * 4 is 13
• Parentheses can be used to force a certain order of evaluation.
(1 + 3) * 4 is 16

25

Arithmetic operators in Python follow the standard mathematical order of


operations, also known as BODMAS/BIDMAS rules:

Brackets
Orders (exponentiation, **)
Division and Multiplication (/, *, //, %)
Addition and Subtraction (+, -)

result = 3 + 2 * 2 ** 2 / 2 - 1 # Output: 6.0


# Explanation: 3 + ((2 * (2 ** 2)) / 2) - 1
# 3 + ((2 * 4) / 2) - 1
# 3 + (8 / 2) - 1
# 3+4-1
# 7-1
# 6.0

13
16-09-2024

Example Data Type


x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", frozenset
"cherry"})
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType

Real numbers

• Python can also manipulate real numbers.


• Examples: 6.022 -15.9997 42.0 2.143e17

• The operators + - * / % ** ( ) all work for real numbers.


• The / produces an exact answer: 15.0 / 2.0 is 7.5
• The same rules of precedence also apply to real numbers:
Evaluate ( ) before * / % before + -

• When integers and reals are mixed, the result is a real number.
• Example: 1 / 2.0 is 0.5
• The conversion occurs on a per-operator basis.
• 7 / 3 * 1.2 + 3 / 2
• 2 * 1.2 + 3 / 2
• 2.4 + 3 / 2
• 2.4 + 1
• 3.4

28

14
16-09-2024

Math commands
• Python has useful commands for performing calculations.

Command name Description Constant Description


abs(value) absolute value e 2.7182818...
ceil(value) rounds up pi 3.1415926...
cos(value) cosine, in radians
floor(value) rounds down
log(value) logarithm, base e
log10(value) logarithm, base 10
max(value1, value2) larger of two values
min(value1, value2) smaller of two values
round(value) nearest whole number
sin(value) sine, in radians
sqrt(value) square root

• To use many of these commands, you must write the following at the top of your Python program:
from math import *
29

Variables
• variable: A named piece of memory that can store a value.
• Usage:
• Compute an expression's result,
• store that result into a variable,
• and use that variable later in the program.

• assignment statement: Stores a value into a variable.


• Syntax:
name = value
• Examples: x = 5
gpa = 3.14

x 5 gpa 3.14

• A variable that has been given a value can be used in expressions.


x + 4 is 9

30

15
16-09-2024

Representing data
>>> 3.2 # canonical
3.2000000000000002
>>> str(3.2) # nice
'3. 2'
>>> repr(3.2) # canonical
'3.2000000000000002'
>>> print 3.2 # nice
3.2

The canonical representation usually tries to be a chunk of text that, when pasted
into the interpreter, re-creates the object

>>> mytuple = (3, 4)


>>> mylist = [1, "2", mytuple]
>>> print repr(mylist)
[1, '2', (3, 4)]
>>> mylist == [1, '2', (3, 4)]
True

16
16-09-2024

>>> y = "The meaning of Life, the Universe, and


Everything is"
>>> x = 42
>>> print y, x
The meaning of Life, the Universe, and Everything
is 42

>>> x = "This is an ex-parrot!"


>>> [Link]()
['This', 'is', 'an', 'ex-parrot!']

>>> 'one and/or two'


['one', 'and/or', 'two']

print
• print : Produces text output on the console.
• Syntax:
print "Message"
print Expression
• Prints the given text message or expression value on the console, and moves
the cursor down to the next line.
print Item1, Item2, ..., ItemN
• Prints several messages and/or expressions on the same line.
• Examples:
print "Hello, world!"
age = 45
print "You have", 65 - age, "years until retirement"
Output:
Hello, world!
34
You have 20 years until retirement

17
16-09-2024

input
• input : Reads a number from user input.
• You can assign (store) the result of input into a variable.
• Example:
age = input("How old are you? ")
print "Your age is", age
print "You have", 65 - age, "years until
retirement"
Output:
How old are you? 53
Your age is 53
You have 12 years until retirement

• Exercise: Write a Python program that prompts the user for


35 his/her amount of money, then reports how many
Nintendo Wiis the person can afford, and how much more

The for loop


• for loop: Repeats a set of statements over a group of values.
• Syntax:
for variableName in groupOfValues:
statements
• We indent the statements to be repeated with tabs or spaces.
• variableName gives a name to each value, so you can refer to it in the
statements.
• groupOfValues can be a range of integers, specified with the range function.

• Example:
for x in range(1, 6):
print x, "squared is", x * x

Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
36

18
16-09-2024

range
• The range function specifies a range of integers:
• range(start, stop) - the integers between start (inclusive)
and stop (exclusive)
• It can also accept a third value specifying the change between values.
• range(start, stop, step) - the integers between start (inclusive)
and stop (exclusive) by step

• Example:
for x in range(5, 0, -1):
print x
print "Blastoff!"

Output:
5
4
3
2
1
Blastoff!
37

Cumulative loops
• Some loops incrementally compute a value that is initialized outside
the loop. This is sometimes called a cumulative sum.
sum = 0
for i in range(1, 11):
sum = sum + (i * i)
print "sum of first 10 squares is", sum

Output:
sum of first 10 squares is 385

38

19
16-09-2024

if
• if statement: Executes a group of statements only if
a certain condition is true. Otherwise, the statements
are skipped.
• Syntax:
if condition:
statements

• Example:
gpa = 3.4
if gpa > 2.0:
print "Your application is accepted."

39

1 >>> x = 6
2 >>> if x >4:
3 print ( 'Yes ' )
4
5 Yes
1 >>> if x >4:
2 print ( 'Yes ' )
3 print ( 'More yes ' )
4
5 Yes
6 More yes

1 >>> if x >4:
2 print ( 'Yes ' )
3 print ( 'More yes ' )
4 else :
5 print ( 'No ' )

20
16-09-2024

if/else
• if/else statement: Executes one block of statements if a certain condition is True, and
a second block of statements if it is False.
• Syntax:
if condition:
statements
else:
statements

• Example:
gpa = 1.4
if gpa > 2.0:
print "Welcome to University of Texas!"
else:
print "Your application is denied."

• Multiple conditions can be chained with elif ("else if"):


if condition:
statements
elif condition:
statements
else:
statements

41

1 >>> if a <3:
2 print ( 'Yes ' )
3 elif b >0:
4 print ( 'No ' )
5 else :
6 print ( 'Maybe ' )
7
8 Yes

21
16-09-2024

while
• while loop: Executes a group of statements as long as a condition is True.
• good for indefinite loops (repeat an unknown number of times)
• Syntax:
while condition:
statements
• Example:
number = 1
while number < 200:
print number,
number = number * 2

• Output:
1 2 4 8 16 32 64 128

43

The while loop will repeatedly perform the same


steps until a condition becomes False.

1 >>> anum = 0
2 >>> while anum < 4:
3 print ( anum )
4 anum = anum + 1
5
60
71
82
93

22
16-09-2024

1 >>> blist = [1, 'GMU ', 'snow days ', 2 ]


2 >>> for i in blist :
3 print ( i )
4
51
6 GMU
7 snow days
82

Range

1 >>> range ( 10 )
2 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3 >>> range (2, 10)
4 [2, 3, 4, 5, 6, 7, 8, 9]
5 >>> range ( 2, 10, 2 )
6 [2, 4, 6, 8]
7 >>> for i in range ( 5 ):
8 print ( i, end='') # py 3.4
9 print i, # py 2.7
10
11 0 1 2 3 4
12 >>> list ( range ( 10 ) ) # py 3.4

23
16-09-2024

Enumerate Function
• Python eases the programmers’ task by providing a
built-in function enumerate( ) for this task.
• The enumerate ( ) function adds a counter to an
iterable and returns it in the form of an enumerating
object.
• This enumerated object can then be used directly for
loops or converted into a list of tuples using the list( )
function.
• enumerate( ) function is an essential skill for efficient
iteration and data manipulation in Python.

Enumerate Function

The enumerate function in Python is a built-in function that


allows programmers to loop over something and have an
automatic counter.

• Syntax: enumerate(iterable, start=0)

• Parameters:

• Iterable: any object that supports iteration


• Start: the index value from which the counter is to be
started, by default it is 0
• Return: Returns an iterator with index and element pairs
from the original iterable

24
16-09-2024

Enumerate Function

If we want to traverse the elements of a sequence and their


indices, we can use the built-in function enumerate:

1 >>> adata = ('Monday ', 'Tuesday ', ' Wednesday ', 'Thursday ', ‘ Friday ' )
2 >>> for a,b in enumerate ( adata ):
3 print ( a, b )
4
5 0 Monday
6 1 Tuesday
7 2 Wednesday
8 3 Thursday
9 4 Friday

Strings
A string is an ordered sequence of characters.
● A string has a length. Get the length with the len( ) builtin function.
● A string is indexable. Get a single character at a position in a string
with the square bracket operator, for example mystring[5].
● You can retrieve a slice (substring) of a string with a slice
operation, for example mystring[5:8].

Create strings with single quotes or double quotes. You can also
escape characters with a backslash.

25
16-09-2024

• string: Strings start and end with quotation mark " or apostrophe ' characters.
• Examples:
"hello"
"This is a string"
"This, too, is a string. It can be very long!"

• A string may not span across multiple lines or contain a " character.
"This is not
a legal String."
"This is not a "legal" String either."
• A string can represent characters by preceding them with a backslash.
• \t tab character
• \n new line character
• \" quotation mark character
• \\ backslash character

• Example: "Hello\tthere\nHow are you?"

51

1 >>> answ = [ ]
2 >>> for i in range ( 0, len (dna ), 10 ):
3 count = dna[i:i +10]. count ('t')
4 pct = count /10.0
5 answ . append ( pct )
6 >>> len ( answ )
7 440384

26
16-09-2024

1 >>> st1 = 'this is a string .'


2 >>> st2 = " this is also a string ."

1 >>> astr = 'aaaa \ tbbbb \ nccccc '


2 >>> astr
3 'aaaa \ tbbbb \ nccccc '
4 >>> print ( astr )
5 aaaa bbbb
6 ccccc

String Concatenation

1 >>> str1 = 'abcde '


2 >>> str2 = " efghi "
3 >>> str3 = str1 + str2
4 >>> str3
5 ' abcdeefghi '

1 >>> alist = st1 . split (' ')


2 >>> alist
3 ['this ', 'is ', 'a', 'string .']
4 >>> st3 = 'X'. join ( alist )
Split and Join Functions. 5 >>> st3
6 ' thisXisXaXstring .'
7 >>> st4 = ''. join ( alist )
8 >>> st4
9 ' thisisastring .'
10 >>> st4 . split ('is ')
1 >>> st1 = 11 ['th ', '', 'astring ']
'atgactagcactacgacggactacgacgactacgacgactacagc
atcatttattacgactacag ‘

3 >>> st2 = st1 . replace ( 'a', 'A' )


4 >>> st2
5'AtgActAgcActAcgAcggActAcgAcgActAcgAcgActA replace function.
cAgcAtcAtttAttAcg ActAcAg ‘

7 >>> st3 = st1 . replace ( 'at ', 'AT ' )


8 >>> st3
9'
ATgactagcactacgacggactacgacgactacgacgactacagc
ATcATttATtacgactacag '

27
16-09-2024

>>> s1 = """how does it feel


... to be on your own
... no directions known
... like a rolling stone
... """
>>> words = [Link]()
>>> words
['how', 'does', 'it', 'feel', 'to', 'be', 'on', 'your',
'own', 'no',
'directions', 'known', 'like', 'a', 'rolling', 'stone']

Complement String.
1 >>> st4 = st2 . replace ( 't', 'a' )
2 >>> st5 = st4 . replace ( 'A', 't' )
3 >>> st5
4 ' tagtcatgctcatcgtcggtcatcgtcgtcatcgtcgtcatctgctactaaataatcgtcatctg '
5 >>> st6 = st5 . replace ('c', 'C' )
6 >>> st7 = st6 . replace ('g', 'c' )
7 >>> st8 = st7 . replace ('C', 'g' )
8 >>> st9 = st8 [::-1]
9 >>> st9
10 ' ctgtagtcgtaataaatgatgctgtagtcgtcgtagtcgtcgtagtccgtcgtagtgctagtcat '

28
16-09-2024

• You can concatenate strings with the "+" operator.


• You can create multiple concatenated copies of a string with the
"*" operator.
• And, augmented assignment (+= and *=) also work.

>>> 'cat' + ' and ' + 'dog'


'cat and dog‘

>>> s1 = 'flower'
>>> s1 += 's'
>>> s1
'flowers'

String properties
• len(string) - number of characters in a
string
(including spaces)
• [Link](string) - lowercase version of a string
• [Link](string) - uppercase version of a string

• Example:
name = "Martin Douglas Stepp"
length = len(name)
big_name = [Link](name)
print big_name, "has", length,
"characters"
Output:
58
MARTIN DOUGLAS STEPP has 20 characters

29
16-09-2024

lower (): [Link]()


str=”PYTHON”
print([Link]())
OP: python

upper (): [Link]()


• In python upper() method converts all the character to
uppercase and returns a uppercase string.
• str=”PyTHOn”
• print([Link]())
• OP: PYTHON

replace(): [Link](old, new[, count])

• In python replace() method replaces the old sequence


of characters with the new sequence. If the optional
argument count is given, only the first count
occurrences are replaced.

old : An old string which will be replaced.


new : New string which will replace the old string.
count : The number of times to process the replace.

30
16-09-2024

str = "Java is Object-Oriented and Java is Portable "


str2 = [Link]("Java","Python")
print("Old String: \n",str)
print("New String: \n",str2)

str3 = [Link]("Java","Python",1)
print("\n Old String: \n",str)
print("New String: \n",str3)

str4 = [Link](str1,"Python is Object-Oriented and


Portable")
print("New String: \n",str4)
OUTPUT:
Python is Object-Oriented and Python is Portable

Python is Object-Oriented and Java is Portable

Python is Object-Oriented and Portable

join(): [Link](sequence)
• Python join() method is used to concat a string with
iterable object. It returns a new string which is the
concatenation of the strings in iterable. It allows
various iterables like: List, Tuple, String etc.

str1 = ":" # string


str2 = “BIOTECH"
str3= [Link](str2)
print(str3)

OUTPUT:
B:I:O:T:E:C:H

31
16-09-2024

find(): [Link](sub[, start[,end]])


• In python find() method finds substring in the whole string
and returns index of the first match.
It returns -1 if substring does not match.
sub: it specifies sub string.
start: It specifies start index of range.
end: It specifies end index of range.

The find() method finds the first occurrence of the specified value.
The find() method returns -1 if the value is not found.
The find() method is almost the same as the index()

str1 = "python is a programming language"


str2 = [Link]("is")
str3 = [Link]("java") OUTPOUT: 7 -1 12 7
str4 = [Link]("p",5)
str5 = [Link]("i", 5, 25)
print(str2,str3,str4,str5)

isalnum( ): [Link]( )
• In python isalnum( ) method checks whether the all characters of the
string is alphanumeric or not.
• A character which is either a letter or a number is known as
alphanumeric. It does not allow special chars even spaces.

str1 = "python"
str2 = "python123"
str3 = "12345"
str4 = "python@123"
str5 = "python 123"
print(str1. isalnum())
print(str2. isalnum())
print(str3. isalnum())
print(str4. isalnum())
print(str5. isalnum())

Output:
True
True
True
False
False

32
16-09-2024

isdigit(): [Link]()
• In python isdigit() method returns True if all the
characters in the string are digits. It returns False
if no character is digit in the string.
str1 = "12345"
str2 = "python123"
str3 = "123-45-78"
str4 = "IIIV"
str5 = “/u00B23” # 23 OUTPUT:
str6 = “/u00BD” # 1/2 True
False
print([Link]()) False
print([Link]()) False
print([Link]()) True
print([Link]()) False
print([Link]())
print([Link]())

isnumeric(): [Link]()
• In python isnumeric() method checks whether all the characters of the
string are numeric characters or not.
• It returns True if all the characters are numeric, otherwise returns False.

str1 = "12345"
str2 = "python123"
str3 = "123-45-78"
str4 = "IIIV"
str5 = “/u00B23” # 23
str6 = “/u00BD” # 1/2 True
print([Link]()) False
print([Link]()) False
print([Link]()) False
print([Link]()) True
print([Link]()) True
print([Link]())

33
16-09-2024

raw_input
• raw_input : Reads a string of text from user input.
• Example:
name = raw_input("Howdy, pardner. What's her
name? ")
print name, "... what a silly name!"
Output:
Howdy, pardner. What's her name? Paris Hilton
Paris Hilton ... what a silly name!

67

Text processing
• text processing: Examining, editing, formatting text.
• often uses loops that examine the characters of a string one by one

• A for loop can examine each character in a string in sequence.


• Example:

for c in “biocomputing":
print c

Output:
b
i
o
c
o
m
p
u
t
i
n
68 g

34
16-09-2024

Indexes
• The Python index( ) method helps you find the index position of
an element or an item in a string of characters or a list of items.

• It spits out the lowest possible index of the specified element in


the list. In case the specified item does not exist in the list, a
ValueError is returned.

• The index( ) in Python returns the position of the element in the


specified list or the characters in the string. It follows the same
syntax whether you use it on a list or a string. The reason being
that a string in Python is considered as a list of characters starting
from the index 0.

>>> list_or_string_name.index(element, start_pos, end_pos)

Indexes
•Element: This is the list element or the string character whose lowest
index/position will be returned.
•Start_pos: This specifies the position of the list item or the character of the
string from where the search begins.
•End_pos: This specifies the position of the list element or the character of the
string from where the search begins.
For example:
• if we have a list [1, 2, 3, 4, 5], we can find the index of the value 3 by calling
[Link](3), which will return the value 2 (since 3 is the third element in the list, and
indexing starts at 0).

list_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


element = 3
list_numbers.index(element)
Output: 2
list_numbers = [1, 'two', 3, 4, 5, 6, 7, 8, 9, 10]
element = 'two’
list_numbers.index(element)
Output: 1

35
16-09-2024

Indexes
• Characters in a string are numbered with indexes starting at 0:
• Example:
name = "P. SHYAM"
index 0 1 2 3 4 5 6 7
character P . S H Y A M

• Accessing an individual character of a string:


variableName [ index ]
• Example:
print name, "starts with", name[0]
Output:
P. SHYAM starts with P

71

Files:
• Primary memory
• Secondary memory

• 1. Open a file,
• 2. Read the data,
• 3. Close the le.

36
16-09-2024

37
16-09-2024

A file object open for reading a text file is iterable. When


we iterate over it, it produces the lines in the file.
A file may be opened in these modes:
● 'r' read mode. The file must exist.
● 'w' write mode. The file is created; an existing
file is overwritten.
● 'a' append mode.

The open( ) builtin function is used to create a file object. For


example, the following code (1) opens a file for writing, then
(2) for reading, then (3) for appending, and finally (4) for
reading again:

38
16-09-2024

Mode Description
r Read Mode (default value)
w Write Mode (file is opened in write-only mode)
Append Mode (Opens a file for appending at the
a
end of the file without truncating)
Create Mode (Creates a new file but will return
x
an error if the file already exists.
t Open the file in text mode.
Opens the file in binary [Link] mode
b returns bytes. It is mainly used while dealing with
the non-text file such as images.
+ Opens the file for updating (reading and writing)

Parameter Description

This parameter value gives the pathname (absolute or relative to the current
file working directory) of the file to be opened.
This is the optional string that specifies the mode in which a file will be opened.
mode The default value is 'r' for reading a text file. We can discuss the other modes in the
later section.

This is an optional integer used to set the buffering policy. Pass 0 to switch
buffering off (only allowed in binary mode), 1 to select line buffering (only usable
buffering in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk
buffer.

This is the name of the encoding used to decode or encode the file. The default one
encoding is platform dependant.
These are optional string denotes how the standard encoding and decoding errors
errors have to be handled.

This is the parameter that indicates how the newline mode works (it only applies to
newline text mode). It can be None, '', '\n', '\r', and '\r\n'.

This parameter indicates whether to close a file descriptor or not. The default value
closefd is True. If closefd is False and a file descriptor rather than a filename was given, the
underlying file descriptor will be kept open when the file is closed.

39
16-09-2024

# 1. Open the file in write mode, which creates the file.


outfile = open(infilename, 'w')
[Link]('line 1\n')
[Link]('line 2\n')
[Link]('line 3\n')
[Link]( )

# 2. Open the file for reading.


infile = open(infilename, 'r')
for line in infile:
print 'Line:', [Link]( )
[Link]( )

>>> fp = file( '[Link]' ) # Py 2.7


>>> fp = open( '[Link]' ) # Py 3.4 or 2.7
>>> data = [Link]()
>>> [Link]()

Accessing les in another directory.

>>> fp = open( 'C:/science/data/[Link]’)


>>> fp = open( '[Link]’)
>>> data = open( fname ).read()

40
16-09-2024

# 3. Open the file in append mode, and add a line to the end of the file.
outfile = open(infilename, 'a')
[Link]('line 4\n')
[Link]( )
print ‘ -‘ * 40

# 4. Open the file in read mode once more.


infile = open(infilename, 'r')
for line in infile:
print 'Line:', [Link]( )
[Link]( )
test('[Link]')

File processing
• Many programs handle data, which often comes from files.

• Reading the entire contents of a file:


variableName = open("filename").read()

Example:
file_text = open("[Link]").read()

82

41
16-09-2024

Line-by-line processing
• Reading a file line-by-line:
for line in open("filename").readlines():
statements
Example:
count = 0
for line in open("[Link]").readlines():
count = count + 1
print "The file contains", count, "lines."

• Exercise: Write a program to process a file of DNA text, such as:


ATGCAATTGCTCGATTAG
• Count the percent of C+G present in the DNA.

83

Function:
• Functions are a nearly universal program-structuring
device. You may have come across them before in other
languages, where they may have been called subroutines or
procedures.

• Function is a named sequence of statements that performs a


computation. When you define a function, you specify the
name and the sequence of statements. Later, you can “call”
the function by name.

• Functions allow us to group and generalize code to be used


arbitrarily many times later.

42
16-09-2024

Example:
• >>> type(32)
• <class int>

• The name of the function is type. The expression in parentheses


is called the argument of the function. The argument is a value
or variable that we are passing into the function as input to the
function. The result, for the type function, is the type of the
argument.

• It is common to say that a function “takes” an argument and


“returns” a result. The result is called the return value.

Function
• Function is a named sequence of statements that performs a
computation.

• When you define a function, you specify the name and the
sequence of statements. Later, you can “call” the function by
name.

• The expression in parentheses is called the argument of the


function. The result, for this function, is the type of the
argument.

• It is common to say that a function “takes” an argument and


“returns” a result.

43
16-09-2024

Built-in Functions in Python:

Declaration of function

44
16-09-2024

Python Function with Arguments

45
16-09-2024

# function definition
def find_square(num):
result = num * num
return result

# function call
square = find_square(3)

print('Square:', square)

Types of Functions in Python


• Built-in Functions: These functions are built into the Python language
and can be used without the need for additional code. Some examples of
built-in functions are print( ), len( ), sum( ), min( ), max( ), etc.

• User-defined Functions: You create these functions to perform a


specific task. You can define your functions using the def keyword
followed by the function name, parameter(s), and the code block that
performs the desired operation.
• the greet() function takes one parameter, name, to personalize the
greeting. When the function is called, it will print out a message to the
console that greets the specified name.
Example:
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Output: Hello, Alice!

46
16-09-2024

• Recursive Functions: These functions call themselves to perform a task


repeatedly until a certain condition is met. Recursive functions can be
useful in situations where a problem can be broken down into smaller sub-
problems.

• factorial() function takes an integer n as its parameter and returns the


factorial of that number. The function first checks if n equals 1, which is
the base case. If n is not equal to 1, the function calls itself with n-1 as the
argument and multiplies the result by n. This process continues recursively
until the base case is reached.

• Example:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(5))
Output: 120

• Lambda Functions: These are small anonymous


functions that can be defined in a single line of code.
Lambda functions are often used for quick, simple
operations that don’t require a full function definition.

• Example:
lambda arguments: expression
add = lambda x, y: x + y
result = add(3, 5)
print(result)
Output: 8

numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
print(squares)
Output: [1, 4, 9, 16, 25]

47
16-09-2024

• Higher-Order Functions: These are functions that take other


functions as arguments and/or return functions as output. Higher-
order functions can be used to create more complex operations by
combining simpler functions.

• Example:
def apply_function(func, arg):
return func(arg)
def square(x):
return x**2
result = apply_function(square, 3)
print(result)
Output: 9

the apply_function() function takes two arguments: a function func and an


argument arg. The function then calls the func function with arg as its argument
and returns the result.

• make_adder() function takes an integer n as its argument and


returns a new function adder. The adder function takes a
single argument x, and returns the sum of x and n.
• To use the make_adder() function, you can call it with an
integer value to create a new function that adds that value to
any number you pass it:

def make_adder(n):
def adder(x):
return x + n
return adder

add_3 = make_adder(3)
result = add_3(5)
print(result)
Output: 8

48
16-09-2024

Python Library Functions

• Python provides some built-in functions that can be directly


used in our program.

• We don't need to create the function, we just need to call


them.

• Some Python library functions are:

• print() - prints the string inside the quotation marks


• sqrt() - returns the square root of a number
• pow() - returns the power of a number

• import math
# sqrt computes the square root
square_root = [Link](4)
print("Square Root of 4 is",square_root)

# pow() comptes the power


power = pow(2, 3)
print("2 to the power 3 is", power)

Output:
Square Root of 4 is 2.0
2 to the power 3 is 8

We imported a math module to use the


library functions sqrt() and pow().

49
16-09-2024

Functions
• def print_hello( ):# returns nothing
print “hello”

• def has_args(arg1,arg2=['e', 0]):


num = arg1 + 4
mylist = arg2 + ['a',7]
return [num, mylist]
has_args(5.16,[1,'b'])# returns [9.16,[[1, ‘b’],[ ‘a’,7]]

• def duplicate_n_maker(n): #lambda on the fly func.


return lambda arg1:arg1*n
dup3 = duplicate_n_maker(3)
dup_str = dup3('go') # dup_str == 'gogogo'

Lists
• LIST is a sequence of values. In a string, the values are
characters; in a list, they can be any type. The values in
lists are called elements or sometimes items.

• There are several ways to create a new list; the simplest is


to enclose the elements in square brackets (“[" and "]”):

[10, 20, 30, 40]


[biology, physics, chemistry]

The first example is a list of four integers. The second


is a list of three strings.

50
16-09-2024

• The following list contains a string, a float, an integer,


and (lo!) another list:
[spam, 2.0, 5, [10, 20]]
• A list within another list is nested.
A list that contains no elements is called an empty list;
you can create one with empty brackets, [ ]

>>> cheeses = [Cheddar, Edam, Gouda]


>>> numbers = [17, 123]
>>> empty = [ ]
>>> print(cheeses, numbers, empty)
[Cheddar, Edam, Gouda] [17, 123] [ ]

Lists are mutable:


• lists are mutable because you can change the order of
items in a list or reassign an item in a list.

• When the bracket operator appears on the left side of


an assignment, it identifies the element of the list
that will be assigned.

>>> numbers = [17, 123]


>>> numbers[1] = 5
>>> print(numbers)
[17, 5]

51
16-09-2024

✓list as a relationship between indices and elements. This


rela tionship is called a mapping; each index “maps to”
one of the elements.
✓List indices work the same way as string indices:
• Any integer expression can be used as an index.
• If you try to read or write an element that does not exist,
you get an IndexError.
• If an index has a negative value, it counts backward
from the end of the list.
• The in operator also works on lists.

>>> cheeses = [Cheddar, Edam, Gouda]


>>> Edam in cheeses True
>>> Brie in cheeses False

Traversing a list
• The most common way to traverse the elements of a list is with a for loop. The syntax
is the same as for strings:

for cheese in cheeses: print(biotech)


A common way to do that is to combine the functions range and len:
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2

loop traverses the list and updates each element. len returns the number of
elements in the list. range returns a list of indices from 0 to n − 1, where n is the
length of the list.
Each time through the loop, i gets the index of the next element. The assignment
statement in the body uses i to read the old value of the element and to assign the
new value.

[spam, 1, [Brie, Roquefort, Pol le Veq], [1, 2, 3]]

52
16-09-2024

List operations:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print(c)
[1, 2, 3, 4, 5, 6]

>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

List slices:
>>> t = [a, b, c, d, e, f]
>>> t[1:3]
[b, c]
>>> t[:4]
[a, b, c, d]
>>> t[3:]
[d, e, f]

>>> t[:]
[a, b, c, d, e, f]

>>> t = [a, b, c, d, e, f]
>>> t[1:3] = [x, y]
>>> print(t)
[a, x, y, d, e, f]

53
16-09-2024

List methods:
append adds a new element to the end of a list:
>>> t = [a, b, c]
>>> [Link](d)
>>> print(t)
[a, b, c, d]

extend takes a list as an argument and appends all of the elements:


>>> t1 = [a, b, c]
>>> t2 = [d, e]
>>> [Link](t2)
>>> print(t1)
[a, b, c, d, e]

sort arranges the elements of the list from low to high:


>>> t = [d, c, e, b, a]
>>> [Link]()
>>> print(t)

Deleting elements
>>> t = [a, b, c]
>>> x = [Link](1)
>>> print(t)
[a, c]
>>> print(x)
B

pop modifies the list and returns the element that


was removed. If you don’t provide an index, it deletes
and returns the last element.

54
16-09-2024

Lists and strings:


• string is a sequence of characters and a list is a sequence of values, but a
list of characters is not the same as a string. To convert from a string to a list
of characters, you can use list:
>>> s = spam
>>> t = list(s)
>>> print(t)
[s, p, a, m]

>>> s = ‘ping for the gods’


>>> t = [Link]()
>>> print(t)
[‘pining’, ‘for’, ‘the’, ‘gods’]
>>> print(t[2])
the

• split with an optional argument called a delimiter that


specifies which characters to use as word boundaries.
>>> s = spam-spam-spam
>>> delimiter = ‘- ‘
>>> [Link](delimiter)
[spam, spam, spam]

55
16-09-2024

Dictionaries
• A dictionary is like a list. In a list, the index positions have to be integers; in
a dictionary, the indices can be (almost) any type.

• Python has several tools that can manipulate long strings of data and the
fastest is the dictionary. For example; it may be desired to know the location
of every word in the text. Each word is used as a key and the data for each
key is a list of the locations of that word.

• You can think of a dictionary as a mapping between a set of indices (which


are called keys) and a set of values. Each key maps to a value.

• The association of a key and a value is called a key-value pair or sometimes


an item.
• The function dict creates a new dictionary with no items. Because dict is
the name of a built-in function, you should avoid using it as a variable
name.

• We want to count how many times each letter appears in given a


string. There are several ways you could do it:

• 1. You could create 26 variables, one for each letter of the alphabet. Then
you could traverse the string and, for each character, increment the
corresponding counter, probably using a chained conditional.

• 2. You could create a list with 26 elements. Then you could convert each
character to a number (using the built-in function ord), use the number
as an index into the list, and increment the appropriate counter.

• 3. You could create a dictionary with characters as keys and counters as


the corresponding values. The first time you see a character, you would
add an item to the dictionary. After that you would increment the value
of an existing item.

56
16-09-2024

• Each of these options performs the same


computation

• An implementation is a way of performing a


computation; some implementations are better than
others.

• For example, an advantage of the dictionary


implementation is that we don’t have to know ahead
of time which letters appear in the string and we only
have to make room for the letters that do appear.

word = bioinformatics
d = dict()
for c in word:
if c not in d:
d[c] = 1
else:
d[c] = d[c] + 1
print(d)

Output: {b: 1, i: 3, o: 2, n: 1, f:1, r:1, m:1, a: 1, t: 1, c:1, s: 1}


The output indicates that the letters “b” “n”, ”f”, “r”, ”m”, “a”, “t”, “c”, “s” and “ appear
once; “i” appears thrice “o” appears twice, and so on.

57
16-09-2024

• The for loop traverses the string. Each time through


the loop, if the character c is not in the dictionary, we
create a new item with key c and the initial value 1
(since we have seen this letter once).

• If c is already in the dictionary we increment d[c].

• Dictionaries have a method called get that takes a key


and a default value. If the key appears in the
dictionary, get returns the corresponding value;
otherwise it returns the default value.

>>> counts = { chuck : 1 , annie : 42, jan: 100}


>>> print([Link](jan, 0))
100
>>> print([Link](tim, 0))
0

We can use get to write our histogram loop more concisely. get method automatically
handles the case where a key is not in a dictionary, we can reduce four lines down to one
and eliminate the if statement.

word = brontosaurus
d = dict()
for c in word:
d[c] = [Link](c,0) + 1
print(d)
The use of the get method to simplify this counting loop ends up
being a very commonly used “idiom” in Python and we will use it
many times in the rest of the book.

58
16-09-2024

Dictionaries and files


• Python program to read through the lines of the file, break
each line into a list of words, and then loop through each
of the words in the line and count each word using a
dictionary.

• The outer loop is reading the lines of the file and the
inner loop is iterating through each of the words on that
particular line. This is an example of a pattern called
nested loops because one of the loops is the outer loop and
the other loop is the inner loop.

• Inner loop executes all of its iterations each time the outer
loop makes a single iteration, we think of the inner loop as
iterating “more quickly” and the outer loop as iterating
more slowly.

fname = input('Enter the file name: ')


try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
counts = dict()
for line in fhand:
words = [Link]()
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
print(counts)

In our else statement, we use the more compact alternative for incrementing a variable. counts[word] += 1 is equivalent
to counts[word] = counts[word] + 1. Either method can be used to change the value of a variable by any desired amount.
Similar alternatives exist for-=, *=, and /=.

59
16-09-2024

But soft what light through yonder window breaks


It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief

Enter the file name: [Link]


{But: 1, soft: 1, what: 1, light: 1, through: 1, yonder: 1,
window : 1, breaks: 1, It: 1, is: 3, the: 3, east: 1, and: 3,
Juliet : 1, sun: 2, Arise: 1, fair: 1, kill: 1, envious: 1,
moon: 1, Who: 1, already: 1, sick: 1, pale: 1, with: 1,
grief: 1}

Looping and dictionaries


• Use a dictionary as the sequence in a for statement, it
traverses the keys of the dictionary. This loop prints
each key and the corresponding value:

counts = { chuck : 1 , annie : 42, jan: 100}


for key in counts:
print(key, counts[key])

Output:

chuck 1
annie 42
jan 100

60
16-09-2024

For example : if we wanted to find all the entries in a dictionary with a value
above ten, we could write the following code:

counts = { chuck : 1 , annie : 42, jan: 100}


for key in counts:
if counts[key] > 10 :
print(key, counts[key])

The for loop iterates through the keys of the dictionary, so we must use the index
operator to retrieve the corresponding value for each key.

Output:

annie 42
jan 100

counts = { chuck : 1 , annie : 42, jan: 100}


lst = list([Link]())
print(lst)
[Link]()
print(lst)
for key in lst:
print(key, counts[key])
Output:
[chuck , annie, jan]
[annie , chuck, jan]
annie 42
chuck 1
jan 100

61
16-09-2024

Dictionaries and tuples


>>> d = {b:1, a:10, c:22}
>>> t = list([Link]())
>>> print(t)
[(b, 1), (a, 10), (c, 22)]

Converting a dictionary to a list of tuples is a way for us


to output the contents of a dictionary sorted by key:
>>> d = {b:1, a:10, c:22}
>>> t = list([Link]())
>>> t [(b, 1), (a, 10), (c, 22)]
>>> [Link]()
>>> t
[(a, 10), (b, 1), (c, 22)]

>>> d = {a:10, b:1, c:22}


>>> l = list()
>>> for key, val in [Link]() :
...
[Link]( (val, key) )
...
>>> l
[(10, a), (1, b), (22, c)]

>>> [Link](reverse=True)
>>> l [(22, c), (10, a), (1, b)]
>>>

62
16-09-2024

METABOLISM (AS EXAMPLE):

INPUT:
glucose_level = 120 # Example glucose level in mg/dL
insulin_level = 5 # Example insulin level in uU/mL
threshold_glucose = 100 # Example threshold for glucose level in mg/dL
if glucose_level > threshold_glucose and insulin_level > 0:
print("Metabolic parameters indicate normal insulin response")
print("Metabolic condition check complete")

Output:
Metabolic parameters indicate normal insulin response
Metabolic condition check complete

BLOOD GROUPING (AS EXAMPLE):


INPUT:
blood_group = 'A'
if blood_group == 'A':
print("Blood group A detected.")
elif blood_group == 'B':
print("Blood group B detected.")
elif blood_group == 'AB':
print("Blood group AB detected.")
elif blood_group == 'O':
print("Blood group O detected.")
else:
print("Unknown blood group.")
print("Blood grouping analysis complete")

Output:
Blood group A detected.
Blood grouping analysis complete

63
16-09-2024

x = ATTAAA as the sequence and count only the number of As.


x="ATTAAA"
count_A = 0
if(x[0] =='A'):
x="ATTAAA"
count_A = count_A + 1 count_A = 0
if(x[1] =='A'): for i in [0, 1, 2, 3, 4, 5]:
count_A = count_A + 1 if(x[i] =='A'):
if(x[2] =='A'): count_A = count_A + 1
print(count_A)
count_A = count_A + 1
if(x[3] =='A'):
count_A = count_A + 1
if(x[4] =='A'):
count_A = count_A + 1
if(x[5] =='A'):
count_A = count_A + 1
print(count_A)

64
16-09-2024

Exception Handling

• Error in Python can be of two types i.e. Syntax errors and Exceptions.

• Errors are problems in a program due to which the program will stop
the execution.

• Exceptions are raised when some internal events occur which change
the normal flow of the program.

An exception is caught by a catch clause only if


the class of the thrown exception object is an
instance of the type of the formal parameter of
the catch clause.

65
16-09-2024

⚫ An “exception” is a (recognized type of) error, and “handling” is what you do


when that error occurs
General syntax:

try:
code-you-want-to-run
except exception1 [as variable1]:
exception1 block
...
except exceptionN [as variableN]:
exceptionN block

⚫ If an error occurs, if it's of exception type 1, then variable1 becomes an alias


to the exception object, and then exception1 block executes. Otherwise,
Python tries exception types 2 ... N until the exception is caught, or else the
program stops with an unhandled exception (a traceback will be printed
along with the exception's text)

⚫ The optional [as variable] will not work with older Python

66
16-09-2024

• Exceptions are mistakes discovered during execution.


Exceptions are triggered whenever there is a mistake in a
program. The program will come to a standstill if these
exceptions are not handled. Python exception handling is
essential to prevent the program from ending
unexpectedly.

• Exception handling in Python is a process of resolving


errors that occur in a program. This involves catching
exceptions, understanding what caused them, and then
responding accordingly.

• Exceptions are errors that occur at runtime when the


program is being executed. They are usually caused by
invalid user input or code that is invalid in Python.
Exception handling allows the program to continue to
execute even if an error occurs.

#Python code after removing the syntax error


string = "Python Exceptions"
for s in string:
if (s != o:
print( s )

Output:

if (s != o:
^
SyntaxError: invalid syntax

67
16-09-2024

#Python code after removing the syntax error

string = "Python Exceptions"


for s in string:
if (s != o):
print( s )

Output:
2 string = "Python Exceptions"
4 for s in string:
----> 5 if (s != o):
6 print( s )
NameError: name 'o' is not defined

Try and Except Statement - Catching Exceptions

# Python code to catch an exception and handle it using try and except code blocks

a = ["Python", "Exceptions", "try and except"]


try:
#looping through the elements of the array a, choosing a range that goes beyond the
length of the array
for i in range( 4 ):
print( "The index and element from the array is", i, a[i] )
#if an error occurs in the try block, then except block will be executed by the Python
interpreter
except:
print ("Index out of range")

OUTPUT:
The index and element from the array is 0 Python
The index and element from the array is 1 Exceptions
The index and element from the array is 2 try and except
Index out of range

68
16-09-2024

Different Types of Exceptions in Python


• NameError: This Exception is raised when a name is not
found in the local or global namespace.
• IndexError: This Exception is raised when an invalid index
is used to access a sequence.
• KeyError: This Exception is thrown when the key is not
found in the dictionary.
• ValueError: This Exception is thrown when a built-in
operation or function receives an argument of the correct
type and incorrect value.
• IOError: This Exception is raised when an input/output
operation fails, such as when an attempt is made to open
a non-existent file.
• ImportError: This Exception is thrown when an import
statement cannot find a module definition or a from ...
import statement cannot find a name to import.
• SyntaxError: This Exception is raised when the input code
does not conform to the Python syntax rules.

• TypeError: This Exception is thrown when an operation or function is


applied to an object of inappropriate type
• AttributeError: occurs when an object does not have an attribute being
referenced, such as calling a method that does not exist on an object.
• ArithmeticError: A built-in exception in Python is raised when an
arithmetic operation fails. This Exception is a base class for other specific
arithmetic exceptions, such as ZeroDivisionError and OverflowError.
• Floating point error: It is a type of arithmetic error that can occur in
Python and other programming languages that use floating point
arithmetic to represent real numbers.
• ZeroDivisionError: This occurs when dividing a number by zero, an
invalid mathematics operation.
• FileExistsError: This is Python's built-in Exception thrown when creating
a file or directory already in the file system.
• PermissionError: A built-in exception in Python is raised when an
operation cannot be completed due to a lack of permission or access
rights.

69
16-09-2024

1. Write a try:except: statement that attempts to open a


file for reading and catches the exception thrown when
the file does not exist.
Question: How do you find out the name of the
exception that is thrown for an input/output error such as
the failure to open a file?
2. Define an exception class. Then write a try:except:
statement in which you throw and catch that specific
exception.
3. Define an exception class and use it to implement a
multilevel break from an inner loop, bypassing an outer
loop.

• In Python, an exception is an event that occurs during the


execution of a program and disrupts the normal flow of
the program. It represents an error or an exception
condition that the program encounters and cannot handle
by itself.

• When an exception occurs, it is "raised" or "thrown" by


the Python interpreter. The exception then propagates up
the call stack, searching for an exception handler that can
catch and handle the exception.

• If no suitable exception handler is found, the program


terminates, and an error message is displayed.

70
16-09-2024

Exception example
⚫ [Link]

try:
i = int("snakes")
print "the integer is", i
except ValueError:
print "oops! invalid value"

Exception handling
• try: print "Unexpected:"
f = open("[Link]")
except IOError: print sys.exc_info()[0]
print "Could not open“ raise # re-throw caught exception
else:
[Link]() try:
a[7] = 0
finally:
• a = [1,2,3] print "Will run regardless"
try:
a[7] = 0
except (IndexError, TypeError): • Easily make your own exceptions:
print "IndexError caught” class myException(except)
except Exception, e: def __init__(self,msg):
print "Exception: ", e [Link] = msg
except: # catch everything
def __str__(self):
return repr([Link])

71
16-09-2024

Classes
class MyVector: """A simple vector class."""
num_created = 0
#USAGE OF CLASS MyVector
def __init__(self, x=0, y=0):
print MyVector.num_created
self.__x = x v = MyVector()
self.__y = y w = MyVector(0.23, 0.98)
MyVector.num_created += 1 print w.get_size()
def get_size(self): bool = isinstance(v, MyVector)
return self.__x+self.__y
@staticmethod Output:
def get_num_created 0
1.21
return MyVector.num_created

Expression

Expression is a combination of values, variables, and


operators. A value all by itself is considered an
expression, and so is a variable, so the following are all
legal expressions.

72
16-09-2024

>>> "monty python" # This is an expression and a literal.


'monty python'
>>> x = 25 # This is a statement. 25 is a literal.
>>> x # This is an expression.
25
>>> 2 in [1, 2, 3] # This is also an expression.
True
>>> def foo(): # This is a statement.
... return 1 # return is a statement; 1 is an expression.
...
>>> foo() # foo is a name; foo() is an expression.
1

>>> x = 1; y = 2
>>> x, y
(1, 2)

>>> x = 5
>>> y = 1.5
>>> x * y
7.5

73
16-09-2024

Threading in Python
import threading
theVar = 1
class MyThread ( [Link] ):
def run ( self ):
global theVar
print 'This is thread ' + \
str ( theVar ) + ' speaking.‘
print 'Hello and good bye.’
theVar = theVar + 1
for x in xrange ( 10 ):
MyThread().start()

what does Python have to do with Internet and web


programming?

• Jython & IronPython(.NET ,written in C#)

• Jython and IronPython are different python implementations, both of which run
on different virtual machines. Jython runs on the JVM (Java virtual machine) and
IronPython runs on the CLR (common language runtime).
For example, using Jython, we can write a plugin for a Java application, and using
IronPython we can use the .NET standard library. The downside to using a
different implementation to CPython is that CPython is the most used python, and
therefore has the best support from libraries and developers.
• Libraries – ftplib, snmplib, uuidlib, smtpd, urlparse, SimpleHTTPServer, cgi,
telnetlib, cookielib, xmlrpclib, SimpleXMLRPCServer, DocXMLRPCServer

• Zope(application server), PyBloxsom(blogger), MoinMoin(wiki), Trac(enhanced


wiki and tracking system), and Bittorrent (6 no, but prior versions yes).

74
16-09-2024

Python Interpreters
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• Many more…

Python on your systems


• Its easy! Go to [Link]
• Download your architecture binary, or source
• Install, make, build whatever you need to do… plenty of info
on installation in readmes
• Make your first program! (a simple on like the hello world
one will do just fine)
• Two ways of running python code. Either in an interpreter or
in a file ran as an executable

75
16-09-2024

76

You might also like