Programming_Python_--_Lecture__1
Programming_Python_--_Lecture__1
Lecture#1
Adeel-ur-Rehman
Programming in Python
Scheme of Lecture
What is Python?
History of Python
Installation of Python
Interactive Mode
Python Basics
Functions
String Handling
Data Structures
Using Modules
What is Python?
Python is a computer programming
language which is:
General-purpose
Open source
Object-oriented
Interpreted
What is Python?
Combines remarkable power with
very clear syntax.
Also usable as an extension language.
Has portable implementation:
Many brands of UNIX
Windows
OS/2
Mac
Amiga
ASC, National Centre for
03/10/25 Physics 4
Programming in Python
History of Python
Created in the early 1990s
By Guido van Rossum.
At Stichting Mathematisch Centrum in the
Netherlands.
As a successor of a language called ABC.
Guido remains Python’s principal author.
Includes many contributions from others.
Installation of Python
The current production versions are
Python 2.7.8 and Python 3.4.2.
Download Python-2.7.8.tgz file from the URL:
http://www.python.org/download/
Unzip and untar it by the command:
tar -zxvf Python-2.7.8.tgz
Change to the Python-2.7.8 directory and run:
./configure to make the Make file
make to create ./python executable
make install to install ./python
Interactive Mode
On Linux systems, the Python is already
installed usually.
But it does not have any unique interface
for programming in it.
An attractive interface is IDLE which
does not get automatically installed with
the Linux distribution.
Type python on the console and then try
the statement print “Python Course” on
the invoked interpreter prompt.
To use the interpreter prompt for
executing Python statements is called
interactive mode.
ASC, National Centre for
03/10/25 Physics 9
Programming in Python
Operators in Python
Operators Description
or Boolean OR
Operators in Python
Operators Description
Operators in Python
Operators Description
^ Bitwise XOR
+, - Addition and
Subtraction
ASC, National Centre for
03/10/25 Physics 12
Programming in Python
Operators in Python
Operators Description
*, /, % Multiplication,
Division and
Remainder
+x, -x Positive, Negative
~x Bitwise NOT
** Exponentiation
ASC, National Centre for
03/10/25 Physics 13
Programming in Python
Operators in Python
Operators Description
x[index] Subscription
x[index:index] Slicing
Operators in Python
Operators Description
Statements
# Decision Making in Python
number = 23
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it’
print "(but you don't win any prizes!)"
elif guess < number:
print 'No, it is a little higher than that.'
else:
print 'No, it is a little lower than that.'
print 'Done'
Loops
Loops makes an execution of a program
chunk iterative.
Two types of loops in Python:
for loop
while loop
When our iterations are countable , we
often use for loop.
When our iterations are uncountable,
we often use while loop.
Statement
# Demonstrating break statement
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
print 'Length of the string is', len(s)
print 'Done'
ASC, National Centre for
03/10/25 Physics 21
Programming in Python
Statement
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
if len(s) < 4:
continue
print 'Sufficient length'
Functions
Functions are reusable pieces of
programs.
They allow us to give a name to a block
of statements.
We can execute that block of
statements by just using that name
anywhere in our program and any
number of times.
This is known as calling the function.
ASC, National Centre for
03/10/25 Physics 25
Programming in Python
Functions
Functions are defined using the def
keyword.
This is followed by an identifier name for
the function.
This is followed by a pair of parentheses
which may enclose some names of
variables.
The line ends with a colon and this is
followed by a new block of statements
which forms the body of the function.
ASC, National Centre for
03/10/25 Physics 26
Programming in Python
Defining a function
def sayHello():
print 'Hello World!' # A new block
# End of the function
sayHello() # call the function
Function Parameters
Are values we supply to the function to
perform any task.
Specified within the pair of parentheses in the
function definition, separated by commas.
When we call the function, we supply the
values in the same way and order.
the names given in the function definition are
called parameters.
the values we supply in the function call are
called arguments.
Arguments are passed using call by value
(where the value is always an object
reference, not the value of the object).
ASC, National Centre for
03/10/25 Physics 28
Programming in Python
Strings
A string is a sequence of
characters.
Strings are basically just words.
Usage of strings:
Using Single Quotes (')
Using Double Quotes(")
Using Triple Quotes (''' or """)
Strings
Escape Sequences.
These are the characters starting from
‘\’ (backslash).
‘\’ means that the following character
has a special meaning in the current
context.
There are various escape characters
(also called escape sequences).
Some of them are:
ASC, National Centre for
03/10/25 Physics 37
Programming in Python
Escape Sequences
Escape Sequence Description
\n Newline. Position the
screen cursor to the
beginning of the next line.
\t Horizontal tab. Move the
screen cursor to the next
tab stop.
\r Carriage return. Position
the screen cursor to the
beginning of the current
line; do not advance to the
next line.
Escape Sequences
\a Alert. Sound the system bell
(beep)
Strings
Raw Strings.
To avoid special processing on a
string such as escape sequences
Specify a raw string by prefixing r or
R to the string
e.g., r"Newlines are indicated by \n."
Strings
Unicode Strings.
Unicode is a standard used for
internationalization
For writing text in our native language
such as Urdu or Arabic, we need to
have a Unicode-enabled text editor
To use Unicode strings in Python, we
prefix the string with u or U
E.g., u"This is a Unicode string."
Strings
Strings are immutable.
Once created, cannot be changed
String literal concatenation.
Placing two string literals side by side
get concatenated automatically by
Python.
E.g., 'What\'s ' "your name?" is
automatically converted to "What's
your name?" .
ASC, National Centre for
03/10/25 Physics 42
Programming in Python
Some Important String
Methods
# Demonstrating some String Methods
name = 'Swaroop' # This is a string object
if name.startswith('Swa'):
print 'Yes, the string starts with "Swa"'
if 'a' in name:
print 'Yes, it contains the string "a"'
if name.find('war') != -1:
print 'Yes, it contains the string "war"'
delimiter = '-*-'
mylist = [‘Pakistan', 'China', 'Finland', 'Brazil']
print delimiter.join(mylist)
ASC, National Centre for
03/10/25 Physics 43
Programming in Python
Python’s Built-in Data
Structures
Structures which hold data
together.
Used to store a collection of related
data.
There are three built-in data
structures in Python:
List
Tuple
Dictionary
ASC, National Centre for
03/10/25 Physics 44
Programming in Python
List
A data structure that holds an
ordered collection of items.
i.e. you can store a sequence of
items in a list.
The list of items should be
enclosed in square brackets
separated by commas.
We can add, remove or search for
items in a list.
ASC, National Centre for
03/10/25 Physics 45
Programming in Python
Using a List
# List Demonstration
shoplist = ['apple', 'mango', 'carrot',
'banana']
print 'I have', len(shoplist), 'items to
purchase.'
print 'These items are:',
for item in shoplist:
print item,
print '\nI also have to buy rice.'
shoplist.append('rice')
print 'My shopping list now is', shoplist
ASC, National Centre for
03/10/25 Physics 46
Programming in Python
Using a List
shoplist.sort()
print 'Sorted shopping list is', shoplist
print 'The first item I will buy is',
shoplist[0]
olditem = shoplist[0]
del shoplist[0]
print 'I bought the', olditem
print 'My shopping list now is', shoplist
ASC, National Centre for
03/10/25 Physics 47
Programming in Python
List
We can access members of the list
by using their position.
Remember that Python starts
counting from 0.
if we want to access the first item
in a list then we can use mylist[0]
just like arrays.
Lists are mutable; these can be
modified. ASC, National Centre for
03/10/25 Physics 48
Programming in Python
Tuple
Tuples are just like lists except that
they are immutable.
i.e. we cannot modify tuples.
Tuples are defined by specifying
items separated by commas within
a pair of parentheses.
Typically used in cases where a
statement or a user-defined
function can safely assume that the
collection of values i.e. the tuple of
values used will not change.
ASC, National Centre for
03/10/25 Physics 49
Programming in Python
Using Tuples
# Tuple Demonstration
zoo = ('wolf', 'elephant', 'penguin')
print 'Number of animals in the zoo is', len(zoo)
new_zoo = ('monkey', 'dolphin', zoo)
print 'Number of animals in the new zoo is',
len(new_zoo)
print new_zoo # Prints all the animals in the new_zoo
print new_zoo[2] # Prints animals brought from zoo
print new_zoo[2][2] # Prints the last animal from zoo
Dictionary
A dictionary is like an address-book
used to find address/contact details of a
person by knowing only his/her name.
i.e. we associate keys (name) with
values (details).
Note that the key must be unique.
i.e. we cannot find out the correct
information if we have two persons with
the exact same name.
Dictionary
We can use only immutable values
(like strings) for keys of a dictionary.
But We can use either immutable or
mutable values for values.
This basically means to say that we
can use only simple objects as keys.
Pairs of keys and values are
specified in a dictionary by using
the notation:
ASC, National Centre for
03/10/25 Physics 52
Programming in Python
Dictionary
d = {key1 : value1, key2 : value2 }.
Notice that:
the key and value pairs are separated
by a colon
pairs are separated themselves by
commas
all this is enclosed in a pair of curly
brackets or braces
Using Dictionaries
# Dictionary Demonstration
ab={ 'Swaroop' : 'python@g2swaroop.net',
'Miguel' : 'miguel@novell.com',
'Larry' : 'larry@wall.org',
'Spammer' : 'spammer@hotmail.com' }
print "Swaroop's address is %s" % ab['Swaroop']
# Adding a key/value pair
ab['Guido'] = 'guido@python.org'
Using Dictionaries
# Deleting a key/value pair
del ab['Spammer']
print "\nThere are %d contacts in the
address-\ book\n" % len(ab)
for name, address in ab.items():
print 'Contact %s at %s' % (name,
address)
if ab.has_key('Guido'):
print "\nGuido's address is %s" % ab['Guido']
ASC, National Centre for
03/10/25 Physics 55
Programming in Python
Sequences
Lists, tuples and strings are
examples of sequences.
Two of the main features of a
sequence is:
the indexing operation which allows us
to fetch a particular item in the
sequence
and the slicing operation which allows
us to retrieve a slice of the sequence
i.e. a part of the sequence
ASC, National Centre for
03/10/25 Physics 56
Programming in Python
Using Sequences
# Sequence Demonstration
shoplist = ['apple', 'mango', 'carrot',
'banana']
# Indexing or 'Subscription'
print shoplist[0]
print shoplist[1]
print shoplist[2]
print shoplist[3]
print shoplist[-1]
print shoplist[-2]
ASC, National Centre for
03/10/25 Physics 57
Programming in Python
Using Sequences
# Slicing using a list
print shoplist[1:3]
print shoplist[2:]
print shoplist[1:-1]
print shoplist[:]
Using Sequences
# Slicing using a string
name = 'swaroop'
print name[1:3]
print name[2:]
print name[1:-1]
print name[:]
References
Lists are examples of objects.
When you create an object and
assign it to a variable, the variable
only refers to the object and is not
the object itself.
i.e. the variable points to that part
of our computer's memory where
the list is stored.
ASC, National Centre for
03/10/25 Physics 60
Programming in Python
Modules
We can reuse code in our program by defining
functions once.
What if we want to reuse a number of
functions in other programs we write?
The solution is modules.
A module is basically a file containing all our
functions and variables that we have defined.
The filename of the module must have a .py
extension.
A module can be imported by another program
to make use of its functionality.
ASC, National Centre for
03/10/25 Physics 62
Programming in Python
The os module
os stands for Operating System.
The os module has lots of useful
functions for manipulating files and
processes – the core of an
operating system.
And os.path has functions for
manipulating file and directory
paths.
ASC, National Centre for
03/10/25 Physics 65
Programming in Python
Using os module
# A use of os module
import os
print os.getcwd()
os.chdir(“/dev”)
print os.listdir(os.getcwd())
print os.getpid()
print os.getppid()
print os.getuid()
print os.getgid()
ASC, National Centre for
03/10/25 Physics 66
Programming in Python
statement
If we want to directly import the argv
variable into our program, then we can
use the from sys import argv statement.
If we want to import all the functions,
classes and variables in the sys module,
then we can use the from sys import *
statement.
This works for any module.
In general, avoid using the from..import
statement and use the import statement
instead since our program will be much
more readable ASC,that
Nationalway.
Centre for
03/10/25 Physics 70