20-08-2024
Dr Perugu Shyam
[Link], PGDBI, [Link], Ph.D
Assistant Professor
Department of Biotechnology
National Institute of Technology Warangal
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
1
20-08-2024
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)
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
2
20-08-2024
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”
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]
3
20-08-2024
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.
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).
4
20-08-2024
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.
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.
5
20-08-2024
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
• 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:
6
20-08-2024
• 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:
• 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.
7
20-08-2024
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)
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.
8
20-08-2024
Languages
• Some influential ones:
• FORTRAN
• science / engineering
• COBOL
• business data
• LISP
• logic and AI
• BASIC
• a simple language
17
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
9
20-08-2024
Python types
• Int – 42- may be transparently expanded to long
through 438324932L
• Float – 2.171892
• Complex – 4 + 3j
• Bool – True or False
10
20-08-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.
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
11
20-08-2024
• 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.
23
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
24
12
20-08-2024
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
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
13
20-08-2024
Example Data Type
x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = range(6) range
x = dict(name="John", age=36) dict
x = set(("apple", "banana", "cherry")) set
x = frozenset(("apple", "banana", "cherry")) frozenset
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
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
20-08-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
20-08-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
20-08-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
20-08-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
20-08-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
20-08-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
20-08-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
20-08-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
20-08-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
20-08-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
20-08-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
If you specify a start index, the index of the first item will be the specified start index,
and the index of each subsequent item will be incremented by.
For Example:
my_list = ['a', 'b', 'c']
for index, item in enumerate (my_list, 1):
print(index, item)
This function would print out the following:
1a
2b
3c
For Example:
my_set = set([1, 2, 3])
other_set = set([2, 3, 4])
my_set.union(other_set)
set([1, 2, 3, 4])
my_set.intersection(other_set)
set([2, 3])
my_set.difference(other_set)
set([1])
25
20-08-2024
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.
• 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?"
52
26
20-08-2024
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
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 '
27
20-08-2024
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 '
>>> 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']
28
20-08-2024
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 '
29