Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 76

MaddaWalabu University

College of Computing
Department of Information System

Information Storage& Retrieval

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

 Easy-to-learn: Python has few keywords, simple structure,


and a clearly defined syntax. This allows the student to pick
up the language quickly.
 Easy-to-read: Python code is more clearly defined and
visible to the eyes.
 Easy-to-maintain: Python's source code is fairly easy-to-
maintain.
 A broad standard library: Python's bulk of the library is
very portable and cross-platform compatible on UNIX,
Windows, and Macintosh.
4
cont..
 Interactive Mode: Python has support for an interactive mode
which allows interactive testing and debugging of snippets of
code.
 Portable: Python can run on a wide variety of hardware
platforms and has the same interface on all platforms.
 Databases: Python provides interfaces to all major commercial
databases.
 GUI Programming: Python supports GUI applications that can
be created and ported to many system calls, libraries, and
windows systems, such as Windows MFC, Macintosh, and the X
Window system of Unix.
 Scalable: Python provides a better structure and support for
5
large programs than shell scripting.
Running Python
– There are three different ways to start Python
(1) Interactive Interpreter:
 You can start Python from Unix, DOS, or any other
system that provides you a command-line interpreter or
shell window.
 Enter python the command line.
 Start coding right away in the interactive interpreter.
$python # Unix/Linux or
$python% # Unix/Linux
C:>python # Windows/DOS
6
(2) Script from the Command-line

A Python script can be executed at


command line by invoking the
interpreter on your application, as in the
following:
$python script.py # Unix/Linuxor
python% script.py # Unix/Linuxor
C:>python script.py # Windows/DOS
7
(3) Integrated Development Environment

 You can run Python from a Graphical User


Interface (GUI) environment as well, if you
have a GUI application on your system that
supports Python.
 Unix: IDLE is the very first Unix IDE for
Python.
 Windows: PythonWin is the first Windows
interface for Python and is an IDE with a GUI.
8
First Python Program
 Let us execute programs in different modes of programming.
Interactive Mode Programming:
Invoking the interpreter without passing a script file as a
parameter brings up the following prompt:
$ python
Python 2.4.3 (#1, Nov 11 2010, 13:34:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> Type the following text at the Python prompt and press the Enter:
>>> print ("Hello, Python!“);
This produce the following output:
Hello, Python! 9
Script Mode Programming
 Let us write a simple Python program in a script. Python
files have extension .py.
 Type the following source code in a test.py file:

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:

Line 1 - a is not equal to b


Line 2 - a is not equal to b
Line 3 - a is not equal to b
Line 4 - a is not less than b
Line 5 - a is greater than b
Line 6 - a is either less than or equal to b
Line 7 - b is either greater than or equal to b
38
Python Assignment Operators

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:

Line 1 - a and b have same identity


Line 2 - a and b have same identity
Line 3 - a and b do not have same identity
Line 4 - a and b do not have same identity

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!

print "1 - Got a true expression value"


print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
print "Good bye!"
52
If…else Statement
 An else statement can be combined with an if statement.
 An else statement contains the block of code that executes if the
conditional expression in the if statement resolves to 0 or a
FALSE value.
 The else statement is an optional statement and there could be at
most only one else statement following if.
Syntax
The syntax of the if...else statement is:
if expression:
statement(s)
else:
statement(s) 53
For Example
#!/usr/bin/python When the above code is executed,
var1 = 100 it produces the following result:
if var1:
print "1 - Got a true expression value"
1 - Got a true expression value
print var1 100
else: 2 - Got a false expression value
print "1 - Got a false expression value"
print var1
0
var2 = 0 Good bye!
if var2:
print "2 - Got a true expression value"
print var2
else:
print "2 - Got a false expression value"
print var2
54
print "Good bye!"
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.
 Similar to the else, the elif statement is optional.
 However, unlike else, for which there can be at most one statement, there can
be an arbitrary number of elif statements following an if.
Syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else: 55
statements
Example
#!/usr/bin/python print var
var = 100 elif var == 100:
if var == 200: print "3 - Got a true
print "1 - Got a true expression expression value"
value" print var
print var else:
elif var == 150: print "4 - Got a false
print "2 - Got a true expression expression value"
value" print var
print "Good bye!"
56
When the above code is executed,
it produces the following result:

3 - Got a true expression value


100
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

You might also like