Python
Python
Python
College of Computing
Department of Information System
Python:
1
Python
Python is a high-level, interpreted,
interactive and object-oriented scripting
language.
Python is designed to be highly readable.
It uses English keywords frequently
where as other languages use punctuation,
And it has fewer syntactical constructions
than other languages.
2
Python
Python is Interpreted: Python is processed at
runtime by the interpreter. You do not need to
compile your program before executing it. This is
similar to PERL and PHP.
Python is Interactive: You can actually sit at a
Python prompt and interact with the interpreter
directly to write your programs.
Python is Object-Oriented: Python supports
Object-Oriented style or technique of programming
that encapsulates code within objects.
3
Python Features
Print(“hello, Python!”);
Now, try to run this program as follow:
$python text.py
This produces the following result:
hello, Python! 10
Variable Types
Variables are nothing but reserved memory
locations to store values.
This means when you create a variable, you
reserve some space in memory.
Based on the data type of a variable, the interpreter
allocates memory and decides what can be stored
in the reserved memory.
Therefore, by assigning different data types to
variables, you can store integers, decimals, or
characters in these variables. 11
Assigning Values to Variables
• Python variables do not need explicit declaration to
reserve memory space.
• The declaration happens automatically when you
assign a value to a variable.
• The equal sign (=) is used to assign values to
variables.
• The operand to the left of the = operator is the
name of the variable and the operand to the right of
the = operator is the value stored in the variable.
For example: 12
Cont..
#!/usr/bin/python
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print counter
print miles
print name
• Here, 100, 1000.0, and "John" are the values assigned to counter,
miles, and name variables respectively.
• This produces the following result:
100
1000.0
13
John
Multiple Assignment
Python allows you to assign a single value
to several variables simultaneously.
For example: a = b = c = 1
You can also assign multiple objects to
multiple variables.
For example: a, b, c = 1, 2, "john"
14
Standard Data Types
Python has various standard data types that are
used to define the operations possible on them and
the storage method for each of them.
Python has five standard data types:
Numbers
String
List
Tuple
Dictionary
15
Numbers
Python supports four different numerical
types:
int (signed integers)
long (long integers, they can also be
represented in octal and hexadecimal)
float (floating point real values)
complex (complex numbers)
16
Examples
17
Python Strings
Strings in Python are identified as a
contiguous set of characters represented in
the quotation marks.
Python allows for either pairs of single or
double quotes.
The plus (+) sign is the string concatenation
operator and the asterisk (*) is the repetition
operator.
18
Examples
#!/usr/bin/python
str = 'Hello World!'
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
19
The above code will produce the ff result
Hello World!
H
llo
llo World!
Hello World!Hello
World! 20
Python Lists
Lists are the most versatile of Python's compound data types.
A list contains items separated by commas and enclosed
within square brackets ([]).
To some extent, lists are similar to arrays in C.
One difference between them is that all the items belonging to
a list can be of different data type.
The values stored in a list can be accessed using the slice
operator ([ ] and [:]) with indexes starting at 0 in the
beginning of the list and working their way to end -1.
The plus (+) sign is the list concatenation operator, and the
asterisk (*) is the repetition operator.
21
Example
#!/usr/bin/python
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # Prints complete list
print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists
22
This produces the following result:
['abcd', 786, 2.23, 'john', 70.200000000000003]
abcd
[786, 2.23]
[2.23, 'john', 70.200000000000003]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']
23
Python Tuples
A tuple is another sequence data type that is similar to the
list.
A tuple consists of a number of values separated by
commas.
Unlike lists, however, tuples are enclosed within
parentheses.
The main differences between lists and tuples are:
Lists are enclosed in brackets ( [ ] ) and their elements and
size can be changed, while tuples are enclosed in
parentheses ( ( ) ) and cannot be updated.
Tuples can be thought of as read-only lists. 24
Example
#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print tuple # Prints complete list
print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists
25
This produces the following result:
('abcd', 786, 2.23, 'john', 70.200000000000003)
abcd
(786, 2.23)
(2.23, 'john', 70.200000000000003)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')
26
Python Dictionary
• Python's dictionaries are kind of hash table type.
• They work like associative arrays or hashes found
in Perl and consist of key-value pairs.
• A dictionary key can be almost any Python type,
but are usually numbers or strings.
• Values, on the other hand, can be any arbitrary
Python object.
• Dictionaries are enclosed by curly braces ({ }) and
values can be assigned and accessed using square
braces ([]). 27
For Example
#!/usr/bin/python
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values
28
This produces the following result:
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
29
BASIC OPERATORS
Types of Operators
Python language supports the following types of operators.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators 30
Python Arithmetic Operators
Assume variable a hold 10 and variable b hold 20, then:
31
For Example
#!/usr/bin/python
a = 21
b = 10
c=0
c=a+b
print "Line 1 - Value of c is ", c
c=a-b
print "Line 2 - Value of c is ", c
c=a*b
print "Line 3 - Value of c is ", c
c=a/b
print "Line 4 - Value of c is ", c
32
c=a%b
Cont..
print "Line 5 - Value of c is ", c
a=2
b=3
c = a**b
print "Line 6 - Value of c is ", c
a = 10
b=5
c = a//b
print "Line 7 - Value of c is ", c
33
When you execute the above program,
it produces the following result:
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 8
Line 7 - Value of c is 2
34
Python Comparison Operators
These operators compare the values on either sides of them
and decide the relation among them.
They are also called Relational operators.
35
Example
Assume variable a holds 10 and variable b holds 20, then:
#!/usr/bin/python
a = 21
b = 10
c=0
if ( a == b ):
print "Line 1 - a is equal to b“
else:
print "Line 1 - a is not equal to b"
if ( a != b ):
print "Line 2 - a is not equal to b"
else:
print "Line 2 - a is equal to b" 36
Cont..
if ( a <> b ): print "Line 6 - a is either less than
print "Line 3 - a is not equal to b" or equal to b"
else: else:
print "Line 3 - a is equal to b" print "Line 6 - a is neither less than
if ( a < b ): nor equal to b"
print "Line 4 - a is less than b" if ( b >= a ):
else: print "Line 7 - b is either greater
than or equal to b"
print "Line 4 - a is not less than b"
else:
if ( a > b ):
print "Line 7 - b is neither greater
print "Line 5 - a is greater than b" than nor equal to b"
else:
print "Line 5 - a is not greater than b"
a = 5;
b = 20;
if ( a <= b ):
37
When you execute the above program
it produces the following result:
39
Example
Assume variable a holds 10 and variable b holds 20, then:
#!/usr/bin/python c=2
a = 21 c %= a
b = 10 print "Line 5 - Value of c is ", c
c=0 c **= a
c=a+b print "Line 6 - Value of c is ", c
print "Line 1 - Value of c is ", c c //= a
c += a print "Line 7 - Value of c is ", c
print "Line 2 - Value of c is ", c
c *= a
print "Line 3 - Value of c is ", c
c /= a
print "Line 4 - Value of c is ", c
40
When you execute the above program,
it produces the following result:
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
41
Python Bitwise Operators
Bitwise operator works on bits and performs bit by bit
operation. Assume if a = 60; and b = 13;
Now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
42
Example
#!/usr/bin/python c = a << 2; # 240 = 1111 0000
a = 60 # 60 = 0011 1100 print "Line 5 - Value of c is ", c
b = 13 # 13 = 0000 1101 c = a >> 2; # 15 = 0000 1111
c=0 print "Line 6 - Value of c is ", c
c = a & b; # 12 = 0000 1100 When you execute the above
print "Line 1 - Value of c is ", c program it produces the
c = a | b; # 61 = 0011 1101 following result:
print "Line 2 - Value of c is ", c Line 1 - Value of c is 12
c = a ^ b; # 49 = 0011 0001 Line 2 - Value of c is 61
print "Line 3 - Value of c is ", c Line 3 - Value of c is 49
c = ~a; # -61 = 1100 0011 Line 4 - Value of c is -61
print "Line 4 - Value of c is ", c Line 5 - Value of c is 240
43
Line 6 - Value of c is 15
Python Logical Operators
There are following logical operators supported by Python
language.
Assume variable a holds 10 and variable b holds 20 then:
44
Python Membership Operators
Python’s membership operators test for membership in a
sequence, such as strings, lists, or tuples.
There are two membership operators as explained below:
45
Example
#!/usr/bin/python
print "Line 2 - b is available in the given list"
a = 10
a=2
b = 20 if ( a in list ):
list = [1, 2, 3, 4, 5 ]; print "Line 3 - a is available in the given list"
if ( a in list ): else:
print "Line 3 - a is not available in the given list“
print "Line 1 - a is available in the
When you execute the above program it
given list" produces the following result:
else: Line 1 - a is not available in the given list
print "Line 1 - a is not available in the Line 2 - b is not available in the given list
given list" Line 3 - a is available in the given list
if ( b not in list ):
print "Line 2 - b is not available in the
given list"
else: 46
Python Identity Operators
Identity operators compare the memory locations of two
objects.
There are two Identity operators as explained below:
47
Example
#!/usr/bin/python
a = 20 print "Line 2 - a and b do not have same
identity"
b = 20
b = 30
if ( a is b ):
if ( a is b ):
print "Line 1 - a and b have same print "Line 3 - a and b have same identity"
identity" else:
else: print "Line 3 - a and b do not have same
print "Line 1 - a and b do not have identity"
same identity" if ( a is not b ):
if ( id(a) == id(b) ): print "Line 4 - a and b do not have same
identity"
print "Line 2 - a and b have same
else:
identity"
print "Line 4 - a and b have same identity"
else:
48
When you execute the above program
it produces the following result:
49
DECISION MAKING
Python programming language provides following types of
decision making statements.
if statements: if statement consists of a boolean expression
followed by one or more statements.
If…else statements: if statement can be followed by an
optional else statement, which executes when the boolean
expression is FALSE.
The elif statement: The elif statement allows you to check
multiple expressions for TRUE and execute a block of code
as soon as one of the conditions evaluates to TRUE.
Nested if statements: You can use one if or else if statement
inside another if or else if statement(s).
50
If Statement
It is similar to that of other languages.
The if statement contains a logical expression using which
data is compared and a decision is made based on the result
of the comparison.
Syntax
if expression:
statement(s)
51
Example
When the above code is executed,
#!/usr/bin/python it produces the following result:
var1 = 100 1 - Got a true expression value
100
if var1: Good bye!
57
LOOPS
Python programming language provides following types of
loops to handle looping requirements.
58
While Loop
A while loop statement in Python programming language
repeatedly executes a target statement as long as a given
condition is true.
Syntax
The syntax of a while loop in Python programming language is:
while expression:
statement(s)
59
Cont..
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any non-zero value.
The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line
immediately following the loop.
60
Example
#!/usr/bin/python When the above code is executed,
it produces the following result:
count = 0 The count is: 0
while (count < 9): The count is: 1
The count is: 2
print 'The count is:', count The count is: 3
count = count + 1 The count is: 4
print "Good bye!" The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
61
Using else Statement with Loops
Python supports to have an else statement associated with a loop statement.
If the else statement is used with a for loop, the else statement is executed
when the loop has exhausted iterating the list.
If the else statement is used with a while loop, the else statement is executed
when the condition becomes false.
For Example
#!/usr/bin/python
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count,” is not less than 5” 62
When the above code is executed,
it produces the following result:
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
63
64
65
66
67
68
69
70
71
72
73
74
75
76