SlideShare ist ein Scribd-Unternehmen logo
1 von 208
Downloaden Sie, um offline zu lesen
INTRODUCTION TO
PYTHON PROGRAMMING
ASWINI C, Assistant Professor/IT, GCT 1
Course Outcomes:
 Use various data types.
 Use control statements and functions.
 Analyze the arrangement of data
elements in Lists, tuples, sets and
Dictionary.
 Develop application using object
oriented programming and GUI.
 Handle exceptions and perform file
operations.
ASWINI C, Assistant Professor/IT, GCT 2
Reading Input from the
Console
 Accept input from the user.
 Use the input function to ask the user
to input a value for the radius.
 variable = input("Enter a value: ")
 Use the function eval to evaluate and
convert it to a numeric value Or use
type converters
 Python also supports simultaneous
assignment in syntax like this:
 var1, var2, ..., varn = exp1, exp2, ...,
expn
ASWINI C, Assistant Professor/IT, GCT 3
Operators
ASWINI C, Assistant Professor/IT, GCT 4
ASWINI C, Assistant Professor/IT, GCT 5
Operator Precedence
 following operator precedence rule is used to
determine the order of evaluation.
 ■ Exponentiation (**) is applied first.
 ■ Multiplication (*), float division (/), integer
division (//) , and remainder operators (%)
are applied next.
 ■ Addition (+) and subtraction (-) operators
are applied last.
 Hint: If an expression contains several
addition, subtraction multiplication,
division, and remainder operators, they are
applied from left to right.
ASWINI C, Assistant Professor/IT, GCT 6
Operator Precedence
Example
ASWINI C, Assistant Professor/IT, GCT 7
ASWINI C, Assistant Professor/IT, GCT
Nov 10, 2017 AD c 2018 8
Python Strings
1 Introduction to Strings
2. String Operations
8
ASWINI C, Assistant Professor/IT, GCT
AD c 2018 9
Strings are a collection of characters
contained within quote marks.
Introduction to Strings
The following are examples of strings...
"Anne was here"
"Anne was here on Friday 31st October 2008"
"9396633"
"A"
"7"
9
ASWINI C, Assistant Professor/IT, GCT
Nov 10, 2017 AD c 2018 10
Strings are a collection of characters
contained within quote marks.
Strings are composed of
characters
Each character has a numeric
code and belongs to a set of
characters known as the Unicode
character set.
10
ASWINI C, Assistant Professor/IT, GCT
Nov 10, 2017 AD c 2018 11
The Unicode character set
The Unicode character set
includes the characters A -
Z, the numbers 0 - 9,
punctuation marks, the
space character, as well as
many other characters...
11
ASWINI C, Assistant Professor/IT, GCT
AD c 2018 12
Strings are a collection of characters
contained within quote marks.
Strings are contained within quote
marks
Strings can be contained within single,
double or triple quote marks...
12
ASWINI C, Assistant Professor/IT, GCT
AD c 2018 13
An example program using strings
Strings can be contained within single, double or
triple quote marks...
'Anne was here'
'''Anne was here on
Saturday 30th October 2004'''
“9396633"
13
ASWINI C, Assistant Professor/IT, GCT
AD c 2018 14
If you want to print a double quote mark (")
within a string, contain the string in single
quote marks (')...
print ('Here is a double quote ", and "more" ')
Printing double quote marks within a
string
14
ASWINI C, Assistant Professor/IT, GCT
AD c 2018 15
If you want to print an apostrophe (or a
single quote mark) within a string, contain
the string in double quotes...
print ("This is Anne's spam")
Printing a string which contains an
apostrophe
15
ASWINI C, Assistant Professor/IT, GCT
Nov 10, 2017 AD c 2018 16
Python Strings
1 Introduction to String
2 String Operations
16
ASWINI C, Assistant Professor/IT, GCT
Nov 10, 2017 AD c 2018 17
Within a string, (i.e. contained in
quote marks), a number is
treated as a character.
Numbers can be treated as
characters
You cannot perform regular
arithmetic on numbers stored as
characters...
17
ASWINI C, Assistant Professor/IT, GCT
AD c 2018 18
Repeating (multiplying) strings using
*
You cannot perform regular arithmetic on
numbers stored as characters, but...
you can "multiply" (repeat) strings:
"3" * 4 results in "3333"
18
ASWINI C, Assistant Professor/IT, GCT
AD c 2018 19
Joining strings together using the + symbol
is a process known as concatenation.
Strings can be joined together using
the + symbol
"Anne " + "was " + ("here " * 3)
results in "Anne was here here here "
19
ASWINI C, Assistant Professor/IT, GCT
AD c 2018 20
Any element (character) of a string can be
accessed by indexing.
Indexing strings using the []
operator
s1 = "Anne Dawson"
print (s1[0], s1[5])
prints A D
20
ASWINI C, Assistant Professor/IT, GCT
AD c 2018 21
Any substring of a string can be obtained
by using the [] operator.
Slicing strings using the [ ] operator
s1 = "Anne Dawson"
print (s1[0:1],s1[5:7])
print (s1[6:9])
prints A Da
aws
21
ASWINI C, Assistant Professor/IT, GCT
AD c 2018 22
The length of any string can be determined
using the len method.
Finding the length of a string using
len
s1 = "Anne"
s2 = "Dawson"
s3 = ""
print (len(s1), end=" ")
print (len(s2), end=" ")
print (len(s3))
prints 4 6 0
22
ASWINI C, Assistant Professor/IT, GCT
AD c 2018 23
Printing strings and numbers
d = 10
c = 75
print ('Total is: ', d, 'dollars and', c, ' cents ')
We can print string values and number values from
the same print statement by separating them with
commas:
>>>
Total is: 10 dollars and 75 cents
23
ASWINI C, Assistant Professor/IT, GCT
Nov 10, 2017 AD c 2018 24
Numbers can be printed
from within a single string
by using a special
method known as string
formatting.
24
ASWINI C, Assistant Professor/IT, GCT
AD c 2018 25
String Formatting and %
In string formatting, we use the %
symbol.
The % operator can also be used for a
different purpose as the modulus
operator (finding the remainder after an
integer division).
The % symbol is said to be overloaded.
25
ASWINI C, Assistant Professor/IT, GCT
Nov 10, 2017 AD c 2018 26
String Formatting and %
In the following example we see the %
operator being used to specify how a
string should be printed (i.e. string
formatting).
An overloaded operator behaves
differently depending on the context.
26
ASWINI C, Assistant Professor/IT, GCT
AD c 2018 27
Printing integers within a string
x = 20
y = 75
print ('The sum of %d and %d is %d' % (x, y, x + y))
>>>
The sum of 20 and 75 is 95
The three %d formatting codes represent
where the decimal integers shown in
brackets after the % symbol should be
printed.
27
ASWINI C, Assistant Professor/IT, GCT
AD c 2018 28
Printing floats within a string
x = 20.512
y = 15.269
print ('The sum of %f and %f is %f' % (x, y, x + y))
>>>
The sum of 20.512000 and 15.269000 is 35.781000
The three %f represent where the float
values shown in brackets after the %
symbol should be printed.
28
ASWINI C, Assistant Professor/IT, GCT
AD c 2018 29
Specifying the number of decimal
places
x = 20.512
y = 15.269
print ('The sum of %0.2f and %0.2f is %0.2f' % (x, y, x + y))
>>>
The sum of 20.51 and 15.27 is 35.78
The three %0.2f represent where the
float values (to 2 decimal places) shown in
brackets after the % symbol should be
printed.
29
ASWINI C, Assistant Professor/IT, GCT
AD c 2018 30
%s is the formatting code which represents a
string.print ('Python is a %s language.' % 'great')
>>>
Python is a great language.
String formatting code %s
The %s represents where the string
value (shown after the % symbol) should
be printed.
30
ASWINI C, Assistant Professor/IT, GCT
AD c 2018 31
The string method find is used to
locate the position of one string within
another.
s1 = 'spamandeggs'
x = s1.find('and')
print (x)
>>>
4
Finding a string within a string
The output:
31
ASWINI C, Assistant Professor/IT, GCT
AD c 2018 32
The string method replace is used to
replace text within a string with new
text.
s1 = 'spam and eggs'
s2 = s1.replace('and','without')
print (s2)
>>>
spam without eggs
Replacing text within a string
The output:
32
ASWINI C, Assistant Professor/IT, GCT
Nov 10, 2017 AD c 2018 33
An escape sequence is a
backslash () followed by one
or more characters, which is
inserted into a string to
perform a special task. E.g. n
generates a new line and t
generates a tab within the
string. . .
Escape Sequences
33
ASWINI C, Assistant Professor/IT, GCT
AD c 2018 34
The following example shows a string
with two escape sequences:
s = 'onentwotthree'
print (s)
>>>
one
two three
A string containing escape
sequences
The output:
34
ASWINI C, Assistant Professor/IT, GCT
AD c 2018 35
The following example shows that
each escape sequence counts as
one character:
s = 'onentwotthree'
print (s)
print (len(s))
>>>
one
two three
13
An escape sequence counts as one
character
The output:
35
ASWINI C, Assistant Professor/IT, GCT
AD c 2018 36
The following example shows that you can
iterate over strings in loops using for
statements and test for membership with the in
expression operator:
s = 'Anne was here'
for c in s:
print (c, end=" ")
print ('w' in s, end=" ")
print (' ' in s, end=" ")
print ('x' in s)
>>>
A n n e w a s h e r e True True False
String iteration and membership
The output:
36
ASWINI C, Assistant Professor/IT, GCT
Nov 10, 2017 AD c 2018 37
Most real-world Python programs contain
strings.
Strings
Strings allow you to collect characters, so that
you can treat them as a group.
Strings have left-to-right positional ordering,
with index capability.
Strings are immutable which means that they
cannot be changed. But new string objects
can be created from existing string objects.
Strings are homogeneous in that they consist
only of characters.
37
Control structures
 Sequential control vs selection control vs
iterative control
 A control statement is a statement that
determines the control flow of a set of
statements.
 A control structure is a set of
statements and the control statements
controlling their execution.
◦ Three fundamental forms of control in
programming are
 Sequential
 Selection
 Iteration.
Simple decisions
 For example,
if n < 1:
print("Your input number is too low.")
if n > 10000:
print("Your input number is too large.")
 A relational statement gives either True or
False (Python's keywords)
 Try
◦ print(int(True))
◦ print(int(False))
To do or not to do
The Python if statement is used to
implement the decision.
if <condition>:
<body>
The body is a sequence of one or more
statements indented under the if
heading.
The body is executed if condition is
evaluated to True.
The body is skipped if condition is
evaluated to False.
Introduction to Python
Boolean Expressions
(Conditions)
The Boolean data type contains two Boolean
values, denoted as True and False in Python.
A Boolean expression is an expression that
evaluates to a Boolean value.
Need a relational operator to evaluate a
boolean expression.
The relational operators on the next slide can
be applied to any set of values that has an
ordering.
◦ Number comparison
◦ Lexicographical ordering for string comparison
Relational Operators
Python Mathematics Meaning
< < Less than
<= ≤ Less than or equal to
== = Equal to
>= ≥ Greater than or equal to
> > Greater than
!= ≠ Not equal to
Two other membership operators
The in operator is used to determine if a
specific value is in a given list, returning
True if found, and False otherwise.
The not in operator returns the opposite
result.
Try
 10 in [10, 20, 30, 40]
 10 not in [10, 20, 30, 40]
 "blue" in ["red", "yellow", "black"]
 "blue" not in ["red", "yellow", "black"]
 "o" in "peter paul and mary"
Boolean Operators
Source: Charles Dierbach. 2013. Introduction to Computer Science Using Python. Wiley.
Operator Precedence
Source: Charles Dierbach. 2013. Introduction to Computer Science Using Python. Wiley.
Two-Way Decisions
 In Python, a two-way decision can be implemented
by attaching an else clause onto an if clause.
 This is called an if-else statement:
if <condition>:
<statements>
else:
<statements>
 E.g.,
if 1 <= n and n <= 10000:
print("Your input number is ", str(n)+
".")
else:
print("Your input must be between 1 and
1000.")
Multi-Way Decisions
• Use nested if-else statement to
implement multi-way decisions.
• if <condition1>:
<case1 statements>
• else:
if <condition2>:
<case2 statements>
else:
if <condition3>:
<case3 statements>
else:
<default statements>
Multi-Way Decisions using
elif
• In Python, else-if can be combined
into elif:
if <condition1>:
<case1 statements>
elif <condition2>:
<case2 statements>
elif <condition3>:
<case3 statements>
else:
<default statements>
The else is optional. If there is no else,
it is possible that no indented block would
be executed.
For Loops: A Quick Review
The for statement allows us to iterate
through a sequence of values.
for <var> in <sequence>:
<body>
The loop index variable var takes on
each successive value in the
sequence, and the statements in the
body of the loop are executed once for
each value.
For example,
◦ for num in range(0, 10):
print(num)
Indefinite Loops
 The for loop is a definite loop, meaning
that the number of iterations is determined
when the loop starts.
 We can’t use a definite loop unless we
know the number of iterations ahead of
time.
 The indefinite or conditional loop keeps
iterating until certain conditions are met.
Indefinite Loops
 while <condition>:
<body>
 condition is a Boolean expression, just
like in if statements. The body is a
sequence of one or more statements.
 Semantically, the body of the loop executes
repeatedly as long as the condition remains
true. When the condition is false, the loop
terminates.
A Pre-test Loop
An example
 Here’s an example of using a while
loop to print out range(10).
i = 0
while i <= 9:
print(i)
i = i + 1
 The code has the same output as this
for loop:
for i in range(10):
print i
Interactive Loops
# average2.py
# A program to average a set of numbers
# Illustrates interactive loop with two accumulators
moredata = "yes"
sum = 0.0
count = 0
while moredata[0] == 'y':
x = int(input("Enter a number >> "))
sum = sum + x
count = count + 1
moredata = input("Do you have more numbers (yes or no)?
")
print ("nThe average of the numbers is", sum / count)
Sentinel Loops
 A sentinel loop continues to process data
until reaching a special value that signals
the end.
 This special value is called the sentinel.
 The sentinel must be distinguishable
from the data since it is not processed as
part of the data.
get the first data item
while item is not the sentinel
process the item
get the next data item
Nested Loops
• Consider the following code in A4
def main():
for i in range(1, 6):
for j in range(1, 6):
print("*", end="");
print()
main()
• What is the aim of it?
Designing Nested Loops
 Break the problem into two parts.
 The first is to process line by line
(outer loop).
 The second is to process the items on
each line (inner loop).
 Note that the two parts are not inter-
dependent.
Post-Test Loop
 Say we want to write a program that is
supposed to get a nonnegative
number from the user.
 If the user types an incorrect input, the
program asks for another value.
 This process continues until a valid
value has been entered.
 This process is input validation.
Post-Test Loop
repeat
get a number from the user
until number is >= 0
Post-Test Loop
 Python doesn’t have a built-in
statement to do this, but we can do it
with a slightly modified while loop.
 We could simulate a post-test loop by
number = -1
while number < 0:
number = eval(input("Enter a positive
number: "))
Using a break
• Some programmers prefer to simulate a post-test loop by
using the Python break statement.
• Executing break causes Python to immediately exit the
enclosing loop.
• For example,
while True:
number = eval(input("Enter a positive
number: "))
if number >= 0:
break # Exit loop if number is valid
 Avoid using break often within loops, because the logic of
a loop is hard to follow when there are multiple exits.
Functions
ASWINI C, Assistant Professor/IT, GCT 63
Some Built –in Functions
ASWINI C, Assistant Professor/IT, GCT 64
ASWINI C, Assistant Professor/IT, GCT 65
 function is a named sequence of statements
that belong together.
 to help us organize programs into chunks that
match how we think about the problem.
def <NAME>( <PARAMETERS> ):
<STATEMENTS>
 1. A header line which begins with a keyword
and ends with a colon.
 2. A body consisting of one or more Python
statements, each indented the same amount—
the Python style guide
ASWINI C, Assistant Professor/IT, GCT 66
• any names we want for the functions we create
• except a name that is a Python keyword,
• names must follow the rules for legal identifiers.
• There can be any number of statements inside the
function, but they have to be indented from the def.
• keyword in the header is def, which is followed by
the name of the function and some parameters
enclosed in parentheses.
• The parameter list may be empty, or it may contain
any number of parameters separated from one
another by commas.
• In either case, the parentheses are required.
• The parameters specifies what information, if any,
we have to provide in order to use the new
function. ASWINI C, Assistant Professor/IT, GCT 67
Positional and Keyword
Arguments
 There are two kinds of arguments:
◦ Using positional arguments requires that
the arguments be passed in the same
order as their respective parameters in
the function header.
◦ nPrintln(“hi”, 4)
◦ Prints the message “Hi” 4 times
ASWINI C, Assistant Professor/IT, GCT 68
 keyword arguments, passing each
argument in the form name value.
 nPrintln(n = 5, message = "good")
passes 5 to n and "good" to
message.
 Message “good” is printed 5 times
 The arguments can appear in any
order using keyword arguments.
ASWINI C, Assistant Professor/IT, GCT 69
 It is possible to mix positional
arguments with keyword arguments,
but the positional arguments cannot
appear after any keyword arguments.
ASWINI C, Assistant Professor/IT, GCT 70
ASWINI C, Assistant Professor/IT, GCT 71
This function is named draw_square. It has
two parameters: one to tell the function
which turtle to move around, and the other to
tell it the size of the square we want drawn.
Make sure you know where the body of the
function ends
— it depends on the indentation, and the
blank lines don’t count for this purpose!
ASWINI C, Assistant Professor/IT, GCT 72
Docstrings for documentation
• If the first thing after the function header is a
string, it is treated as a docstring and gets
special treatment in Python and in some
programming tools.
• Docstrings are the key way to document our
functions in Python and the documentation part
is important.
• Docstrings are usually formed using triple-quoted
strings as they allow us to easily expand the
docstring
• Just to differentiate from comments, a string at
the start of a function (a docstring) is retrievable
by Python tools at runtime.
• By contrast, comments are completely eliminated
when the program is parsed.
ASWINI C, Assistant Professor/IT, GCT 73
 Function definition – how it should work
 Function call. Eg: built-in functions like print,
range and int. Function calls contain the
name of the function being executed
followed by a list of values, called
arguments, which are assigned to the
parameters in the function definition.
ASWINI C, Assistant Professor/IT, GCT 74
ASWINI C, Assistant Professor/IT, GCT 75
Functions can call other
functions
• Functions can call other functions.
• So far, it may not be clear why it is worth the
trouble to create all of these new functions.
Actually, there are a lot of reasons, but this
example demonstrates two:
• 1. Creating a new function gives us an
opportunity to name a group of statements.
Functions can simplify a
• program by hiding a complex computation
behind a single command.
• 2. Creating a new function can make a
program smaller by eliminating repetitive
code.
, create a function before we can execute it.
ASWINI C, Assistant Professor/IT, GCT 76
Flow of execution
• to ensure that a function is defined before its first use, we
have to know the order in which statements are executed,
which is called the flow of execution.
• Execution always begins at the first statement of the program.
• Statements are executed one at a time, in order from top to
bottom.
• Function definitions do not alter the flow of execution of the
program, but remember that statements inside the function
are not executed until the function is called.
• we can define one function inside another.
• In this case, the inner definition isn’t executed until the outer
function is called.
• Instead of going to the next statement, the flow jumps to the
first line of the called function, executes all the statements
there, and then comes back to pick up where it left off.
ASWINI C, Assistant Professor/IT, GCT 77
Functions that require
arguments
 Most functions require arguments: the
arguments provide for generalization.
Eg: abs(-5) = 5
 Some functions take more than one
argument. Eg:pow(2,3)=8 takes two
arguments, the base and the
exponent.
 Inside the function, the values that are
passed get assigned to variables
called parameters.
ASWINI C, Assistant Professor/IT, GCT 78
Functions that return
values
ASWINI C, Assistant Professor/IT, GCT 79
Recursion
80ASWINI C, Assistant Professor/IT, GCT
• Recursion means “defining something in
terms of itself”
• smaller scale, perhaps multiple times, to
achieve your objective.
• Programming languages generally
support recursion, which means that, in
order to solve a problem, functions can
call themselves to solve smaller
subproblems.
• Any problem that can be solved
iteratively (with a for or while loop) can
also be solved recursively.
81ASWINI C, Assistant Professor/IT, GCT
Drawing Fractals
 fractal is a drawing which also has
self-similar structure, where it can be
defined in terms of itself.
 This is a typical example of a problem
which is recursive in nature.
82ASWINI C, Assistant Professor/IT, GCT
Recursive data structures
• Lists and tuples can also be nested, providing
many possibilities for organizing data.
• The organization of data for the purpose of
making it easier to use is called a data
structure.
• Eg:Votes arriving from individual wards,
precincts, municipalities, counties, and states
are sometimes reported as a sum total of
votes and sometimes as a list of subtotals of
votes.
• A nested number list is a list whose elements
are either:
– numbers
– nested number lists
83ASWINI C, Assistant Professor/IT, GCT
• recursive data structures that are partially
composed of smaller and simpler instances of
themselves.
• The definition is not circular, since at some point we
will reach a list that does not have any lists as
elements.
• Now suppose our job is to write a function that will
sum all of the values in a nested number list.
• >>> sum([1, 2, 8])
• 11
• >>> sum([1, 2, [11, 13], 8])
• Traceback (most recent call last):
• File "<interactive input>", line 1, in <module>
• TypeError: unsupported operand type(s) for +: 'int'
and 'list'
• the third element of this list, [11, 13], is itself a list,
so it cannot just be added to 1, 2, and 8.
84ASWINI C, Assistant Professor/IT, GCT
Processing recursive number
lists
• To sum all the numbers in our
recursive nested number list we need
to
–traverse the list,
–visiting each of the elements within its
nested structure,
–adding any numeric elements to our sum
–recursively repeating the summing
process
• with any elements which are
themselves sub-lists. 85ASWINI C, Assistant Professor/IT, GCT
Mutual Recursion
 also possible to make multiple
functions that call eachother.
 This is rarely really usefull, but it can
be used to make state machines
86ASWINI C, Assistant Professor/IT, GCT
stack diagram
 A graphical representation of a stack
of functions, their variables, and the
values to which they refer.
 track of which variables can be used
where, it is sometimes useful to draw
a stack diagram.
87ASWINI C, Assistant Professor/IT, GCT
def cat_twice(part1, part2):
cat = part1 + part2
print_twice(cat)
def print_twice(bruce):
print(bruce)
print(bruce)
line1 = 'Bing tiddle ‘
line2 = 'tiddle bang.‘
cat_twice(line1, line2)
 Cat_twice function takes two arguments, concatenates
them, and prints the result twice.
 >>> Bing tiddle tiddle bang.
 Bing tiddle tiddle bang.
 When cat_twice terminates, the variable cat is destroyed. If
we try to print it, we get an exception
88ASWINI C, Assistant Professor/IT, GCT
Fruitful functions and void
functions
 functions, such as the math functions,
return results; for lack of a better
name, which are fruitful functions.
◦ x = math.cos(radians)
◦ golden = (math.sqrt(5) + 1) / 2
 perform an action but don’t return a
value. are called void functions.
◦ print_twice
89ASWINI C, Assistant Professor/IT, GCT
Map, filter and reduce
 To add up all the numbers in a list, you can use a
loop like this:
def add_all(t):
total = 0
for x in t:
total += x
return total
 The += operator provides a short way to update a
variable. This augmented assignment statement,
 As the loop runs, total accumulates the sum of the
elements; a variable used this way is sometimes
called an accumulator.
90ASWINI C, Assistant Professor/IT, GCT
 Adding up the elements of a list using built-
in function, sum:
 >>> t = [1, 2, 3]
 >>> sum(t)
 6
 An operation like this that combines a
sequence of elements into a single value is
sometimes called reduce.
 Sometimes you want to traverse one list
while building another. For example, the
following
 function takes a list of strings and returns a
new list that contains capitalized strings:
91ASWINI C, Assistant Professor/IT, GCT
 res is initialized with an empty list;
each time through the loop, we
append the next element.
 So res is another kind of accumulator.
 capitalize_all is sometimes called a
map because it “maps” a function
(in this case the method capitalize)
onto each of the elements in a
sequence. 92ASWINI C, Assistant Professor/IT, GCT
 Another common operation is to select some of
the elements from a list and return a sublist.
 isupper is a string method that returns True if
the string contains only upper case letters.
 An operation like only_upper is called a filter
because it selects some of the elements and
filters out the others.
93ASWINI C, Assistant Professor/IT, GCT
Python lambda (Anonymous Functions)
 In Python, anonymous function means that a
function is without a name.
 lambda keyword is used to create
anonymous functions. It has the following
syntax:
 lambda arguments: expression
94ASWINI C, Assistant Professor/IT, GCT
 have any number of arguments but only one
expression, which is evaluated and returned.
 use lambda functions wherever function
objects are required.
 lambda functions are syntactically restricted
to a single expression.
 It has various uses in particular fields of
programming besides other types of
expressions in functions.
95ASWINI C, Assistant Professor/IT, GCT
def cube(y):
return y*y*y;
g = lambda x: x*x*x
print(g(7))
print(cube(5))
Output:
343
125
96ASWINI C, Assistant Professor/IT, GCT
Use of lambda() with filter()
 filter out all the elements of a sequence
“sequence”, for which the function returns True.
 program that returns the odd numbers from an
input list:
 li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
 final_list = list(filter(lambda x: (x%2 != 0) , li))
 print(final_list)
 Output:
 [5, 7, 97, 77, 23, 73, 61
97ASWINI C, Assistant Professor/IT, GCT
Use of lambda() with reduce()
 with a lambda function and a list and a new
reduced result is returned.
 This performs a repetitive operation over the
pairs of the list.
 from functools import reduce
 li = [5, 8, 10, 20, 50, 100]
 sum = reduce((lambda x, y: x + y), li)
 print (sum)
 Output:
 193 98ASWINI C, Assistant Professor/IT, GCT
Use of lambda() with map()
 with a lambda function and a list and a new
list is returned which contains all the lambda
modified items returned by that function for
each item. Example:
 li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
 final_list = list(map(lambda x: x*2 , li))
 print(final_list)
 Output:
 [10, 14, 44, 194, 108, 124, 154, 46, 146, 122]
99ASWINI C, Assistant Professor/IT, GCT
my_list = [12, 65, 54, 39, 102, 339, 221,
50, 70, ]
result = list(filter(lambda x: (x % 13 ==
0), my_list))
print(result)
100ASWINI C, Assistant Professor/IT, GCT
my_list = ["geeks", "geeg", "keek",
"practice", "aa"]
result = list(filter(lambda x: (x ==
"".join(reversed(x))), my_list))
print(result)
101ASWINI C, Assistant Professor/IT, GCT
from collections import Counter
my_list = ["geeks", "geeg", "keegs",
"practice", "aa"]
str = "eegsk“
result = list(filter(lambda x: (Counter(str)
== Counter(x)), my_list))
print(result)
102ASWINI C, Assistant Professor/IT, GCT
LISTS
ASWINI C, Assistant Professor/IT, GCT
103
 How lists are useful in programming
 How to create lists- Create lists by using list comprehension
 Common operations for sequences
 Use the len, min, max, sum, and random.shuffle functions with a list
 Access list elements by using indexed variables
 Obtain a sublist from a larger list by using the slicing operator [start : end]
 Use the + (concatenation), * (repetition), and in/not in operators on lists
 Traverse elements in a list using a for loop
 Compare the contents of two lists by using comparison operators
 Invoke a list’s append, count, extend, index, insert, pop, remove, reverse, sort methods
 Split a string into a list using the str’s split method
 Read data from the console into a list.
 Use lists in application development
 Copy the contents of one list to another
 Develop and invoke functions that include list arguments and return lists
 Search elements using the linear or binary search algorithm.
 Sort a list by using the selection sort, Insertion sort
 Develop a bouncing ball animation by using a list
ASWINI C, Assistant Professor/IT, GCT 104
Why lists?
• list can store a
collection of data of
any size.
• type called a list
stores a sequential
collection of
elements
• read 100 numbers,
compute their
average, and then
find out how many
of the numbers are ASWINI C, Assistant Professor/IT, GCT 105
Why can’t we use array?
• Many programming languages, a type
called an array to store a sequence of
data.
• An array has a fixed size.
• A Python list’s size is flexible.
• It can grow and shrink on demand.
• A list is a sequence defined by the list
class.
• It contains the methods for creating,
manipulating, and processing lists.
• Elements in a list can be accessed
through an index. ASWINI C, Assistant Professor/IT, GCT 106
Creating Lists
 Using List constructor
 elements in a list are separated by
commas and are enclosed by a pair of
brackets ([]).
ASWINI C, Assistant Professor/IT, GCT 107
 A list can contain the elements of the same type
or mixed types. For example, the following
 list4 = [2, "three", 4]
 List comprehensions provide a concise way to
create a sequential list of elements.
 A list comprehension consists of brackets
containing an expression followed by a
◦ for clause
 then zero or more for or if clauses.
ASWINI C, Assistant Professor/IT, GCT 108
ASWINI C, Assistant Professor/IT, GCT 109
List Is a Sequence Type
 Strings and lists are sequence types.
 String is a sequence of characters, while a list
is a sequence of any elements.
 x in s True if element x is in sequence s.
 x not in s True if element x is not in sequence s.
 len(s) Length of sequence s, i.e., the number of elements in s.
 min(s) Smallest element in sequence s.
 max(s) Largest element in sequence s.
 sum(s) Sum of all numbers in sequence s.
 for loop Traverses elements from left to right in a for loop.
◦ >>>for u in myList:
◦ >>>…….print(u) # prints all elements in myList
◦ for i in range(0, len(myList), 2):
◦ print(myList[i]) # print elements in index position at 0 to 9 with interval 2
 <, <=, >, >=, =, != Compares two sequences.
 shuffle function in the random module to shuffle the elements randomly in the list.
 s1 + s2 Concatenates two sequences s1 and s2. (Concatenation operator)
 s * n, n * s n copies of sequence s concatenated. (Repetition Operator)
ASWINI C, Assistant Professor/IT, GCT 110
Index Operator []
 range from 0 to len(myList)-1
◦ s[i] ith element in sequence s.
◦ myList[index] can be used just like a variable,
so it is also known as an indexed variable.
>>>myList = [5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123]
>>>myList[2] = myList[0] + myList[1] #adds index 0 and 1 value to 2
>>>myList
[5.6, 4.5, 10.1, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123]
 The following loop assigns 0 to myList[0], 1 to myList[1], ..., and 9 to myList[9]:
 >>>for i in range(len(myList)):
myList[i] = I
>>>myLIst
[0,1,2,3,4,5,6,7,8,9]
 list1[-1] is same as list1[-1 + len(list1)], which gives the last element in the
list.
 list1[-3] is same as list1[-3 + len(list1)], which gives the third last element in
the list.
• s[i : j] Slice of sequence s from index i to j - 1., I refers to start index j to end index
• negative index in slicing is also allowed
• >>>list1 = [2, 3, 5, 2, 33, 21] >>>list1[-4 : -2] #prints [5,2]ASWINI C, Assistant Professor/IT, GCT 111
Comparing List
 two lists must contain the same type of
elements
 Uses lexicographical ordering:
 the first two elements are compared, and if they
differ this determines the outcome of the
comparison;
 if they are equal, the next two elements are
compared, and so on
ASWINI C, Assistant Professor/IT, GCT 112
List methods
ASWINI C, Assistant Professor/IT, GCT 113
ASWINI C, Assistant Professor/IT, GCT 114
ASWINI C, Assistant Professor/IT, GCT 115
Splitting a String into a List
 str class contains the split method, which is
useful for splitting items in a string into a
list.
 items = "Jane John Peter Susan".split()
 >>>items[2] #prints ‘peter’
 >>>items = "09/20/2012".split("/")
 >>>items[2] # prints ‘2012’
ASWINI C, Assistant Professor/IT, GCT 116
Inputting Lists
ASWINI C, Assistant Professor/IT, GCT 117
Copying LIsts
 To copy the data in one list to another list, you have to copy individual
elements from the source list to the target list.
 does not copy the contents of the list referenced by list1 to list2
 copies the reference value from list1 to list2. After this, list1 and
list2 refer to the same list,
 The list previously referenced by list2 is no longer referenced; it
becomes garbage.
 The memory space occupied by list2 will be automatically
collected and reused by the Python interpreter.
ASWINI C, Assistant Professor/IT, GCT 118
Passing Lists to Functions
 When passing a list to a function, the contents of the
list may change after the function call, since a list is a
mutable object.
 just like passing an object to a function
 Last statement creates a list and passes it to the
function.
 There is no explicit reference variable for the list. Such
a list is called an anonymous list.
ASWINI C, Assistant Professor/IT, GCT 119
passlist argument.py
ASWINI C, Assistant Professor/IT, GCT 120
DefaultlistArgument.py
Default Arguments
ASWINI C, Assistant Professor/IT, GCT 121
No default Argument-
ASWINI C, Assistant Professor/IT, GCT 122
Returning a List from a
Function
 When a function returns a list, the list’s reference value is
returned.
 You can pass list arguments when invoking a function.
 A function can also return a list.
ASWINI C, Assistant Professor/IT, GCT 123
MULTIDIMENSIONAL LIST
ASWINI C, Assistant Professor/IT, GCT 124
 Data in a table or a matrix can be
stored in a two-dimensional list.
 value in a 2D list can be accessed
through a row and column index.
 matrix can be accessed using
matrix[i][j], where i and j are the row
and column indexes.
ASWINI C, Assistant Professor/IT, GCT 125
 2D list consists of a list of 1D lists and a 3D
list consists of a list of 2D lists.
 create n-dimensional lists for any integer n.
 For example, you can use a three-
dimensional list to store exam scores for a
class of six students with five exams, and
each exam has two parts
ASWINI C, Assistant Professor/IT, GCT 126
 scores[0][1][0] refers to the multiple-choice
score for the first student’s second exam,
which is 11.0. scores[0][1][1] refers to the
essay score for the first student’s second
exam, which is 22.5.
ASWINI C, Assistant Professor/IT, GCT 127
ASWINI C, Assistant Professor/IT, GCT 128
DATA STRUCTURES
 Eg: No-fly list for aircraft
 a tuple for storing a fixed list of elements, a
set for storing and quickly accessing
nonduplicate elements, and a dictionary for
storing key/value pairs and for accessing
elements quickly using the keys.
ASWINI C, Assistant Professor/IT, GCT 129
Tuples
 Tuples are like lists, but their elements are
fixed; that is, once a tuple is created,
 cannot add new elements, delete elements,
replace elements, or reorder the elements
◦ t1 = () # Create an empty tuple
◦ t2 = (1, 3, 5) # Create a tuple with three elements
◦ t3 = tuple([2 * x for x in range(1, 5)]) # Create a tuple from a
list
◦ t4 = tuple("abac") # t4 is ['a', 'b', 'a', 'c'] # Create a tuple
from a string
ASWINI C, Assistant Professor/IT, GCT 130
ASWINI C, Assistant Professor/IT, GCT 131
Sets
 Sets are like lists for storing a collection of
elements.
 But, elements in a set are nonduplicates and
are not placed in any particular order.
 can contain the elements of the same type or
mixed types. For example, s {1, 2, 3, "one",
"two", "three"}
◦ Each element in a set must be hashable.
◦ Each object in Python has a hash value and an
object is hashable if its hash value never changes
during its lifetime.
◦ All types of objects introduced so far except lists areASWINI C, Assistant Professor/IT, GCT 132
 s1 = set() # Create an empty set
 s2 = {1, 3, 5} # Create a set with three elements
 s3 = set([1, 3, 5]) # Create a set from a tuple
 s4 = set([x * 2 for x in range(1, 10)]) # Create a
set from a list
 s5 = set("abac") # s5 is {'a', 'b', 'c'} # Create a set
from a string
ASWINI C, Assistant Professor/IT, GCT 133
 Manipulating and Accessing Sets
 remove(e) method will throw a KeyError
exception if the element to be removed is not
in the set.
ASWINI C, Assistant Professor/IT, GCT 134
 Subset and Superset
ASWINI C, Assistant Professor/IT, GCT 135
 Equality Test
ASWINI C, Assistant Professor/IT, GCT 136
 Set Operations
ASWINI C, Assistant Professor/IT, GCT 137
 Comparing the Performance of Sets and Lists
◦ Sets are more efficient than lists for the in and not in operator and for
the remove method.
◦ sets do not support the index operator, because the elements in a set are
unordered.
◦ Sets are implemented using hash tables.
◦ add an object to a set, the position within the memory of the set object is
determined using the hash of the object to be added.
◦ when searching data have to look if the object is at the position
determined by its hash, so the speed of this operation does not depend
on the size of the set.
◦ For lists, in contrast, the whole list needs to be searched, which will
become slower as the list grows.
◦ sets do not preserve the order of the objects you add.
◦ sets aren't faster than lists in general -- membership
test is faster for sets, and so is removing an element.
ASWINI C, Assistant Professor/IT, GCT 138
Dictionaries
 A dictionary is a container object that stores a collection of key/value pairs.
 To enable fast retrieval, deletion, and updating of the value by using the
key.
 keys are like an index operator, but In a list, the indexes are integers.
 In a dictionary, the key must be a hashable object.
 A dictionary cannot contain duplicate keys. Each key maps to one value.
 A key and its corresponding value form an item (or entry) stored in a
dictionary
 A dictionary is also known as a map, which maps each key to a value.
ASWINI C, Assistant Professor/IT, GCT 139
 Creating a Dictionary
◦ students = {"111-34-3434":"John", "132-56-6290":"Peter"}
◦ students = {} # Create an empty dictionary
 Adding, Modifying, and Retrieving Values
◦ students["234-56-9010"] = "Susan“
 retrieve a value, using dictionaryName[key].
• If the key is in the dictionary, the value for the key is returned. Otherwise, a KeyError
exception is raised.
 del students["234-56-9010"]
ASWINI C, Assistant Professor/IT, GCT 140
 Looping
 len(students)
Equality Test
ASWINI C, Assistant Professor/IT, GCT 141
Dictionary Methods
ASWINI C, Assistant Professor/IT, GCT 142
Classes and Objects
ASWINI C, Assistant Professor/IT, GCT 143
Defining Classes for Objects
• OOP enables to develop large-scale software
and GUIs effectively.
• Python automatically assigns each object a
unique id for identifying the object at runtime.
• An object’s state (also known as its properties
or attributes) is represented by variables,
called data fields.
• Python uses methods to define an object’s
behavior (also known as its actions). methods
are defined as functions.
• You make an object perform an action by
invoking a method on that object.
ASWINI C, Assistant Professor/IT, GCT 144
 An object is an instance of a class,
and you can create many instances of
a class.
 Creating an instance of a class is
referred to as instantiation.
ASWINI C, Assistant Professor/IT, GCT 145
Defining Classes
• class provides a special method,
__init__, known as an initializer, is
invoked to initialize a new object’s
state when it is created.
• An initializer can perform any action, but
initializers are designed to perform
initializing actions, such as creating an
object’s data fields with initial values.
• The class name is preceded by the
keyword class and followed by a colon
(:).
• The initializer is always named
__init__ (line 5), which is a special
method. ASWINI C, Assistant Professor/IT, GCT 146
ASWINI C, Assistant Professor/IT, GCT 147
Constructing Objects
 create objects from the class with a constructor,
which does two things:
eg:ClassName(arguments)
◦ creates an object in the memory for the class.
◦ invokes the class’s __init__ method to initialize
the object.
 All methods, including the initializer, have the
first parameter self.
 self parameter in the __init__ method is
automatically set to reference the object that
was just created.
 can specify any name for this parameter, but by
convention self is usually used.ASWINI C, Assistant Professor/IT, GCT 148
ASWINI C, Assistant Professor/IT, GCT 149
Accessing Members of
Objects
 Data fields are also called instance
variables,
 To access an object’s data fields and
invoke an object’s methods, assign
the object to a variable :
 objectRefVar =
ClassName(arguments)
 For example, c1 = Circle(5) c2 =
Circle()
ASWINI C, Assistant Professor/IT, GCT 150
 Methods are also called instance methods
 Invoke methods by using the dot operator (.), als
known as the object member access operator.
 objectRefVar.datafield
 objectRefVar.method(args)
ASWINI C, Assistant Professor/IT, GCT 151
self Parameter
 self is a parameter that references
the object itself.
 Using self, you can access object’s
members in a class definition.
 For example, you can use the syntax
self.x to access the instance variable
x and syntax self.m1() to invoke the
instance method m1 for the object
self in a class,
ASWINI C, Assistant Professor/IT, GCT 152
ASWINI C, Assistant Professor/IT, GCT 153
Hiding Data Fields
 Making data fields private protects
data and makes the class easy to
maintain.
 You can access data fields via
instance variables directly from an
object.
ASWINI C, Assistant Professor/IT, GCT 154
 direct access of a data field in an
object is not a good practice—for two
reasons:
First, data may be tampered with.
 ■ Second, the class becomes difficult
to maintain and vulnerable to bugs.
ASWINI C, Assistant Professor/IT, GCT 155
GUI Programming Using
Tkinter
ASWINI C, Assistant Professor/IT, GCT 156
 Tkinter enables you to develop GUI
programs and is an excellent
pedagogical tool for learning object-
oriented programming.
 Tkinter (pronounced T-K-Inter) is short
for “Tk interface.”
 Tk is a GUI library used by many
programming languages for
developing GUI programs on
Windows, Mac, and UNIX.
ASWINI C, Assistant Professor/IT, GCT 157
 The tkinter module contains the
classes for creating GUIs.
 The Tk class creates a window for
holding GUI widgets
 The first argument of a widget class is
always the parent container (i.e., the
container in which the widget will be
placed).
ASWINI C, Assistant Professor/IT, GCT 158
ASWINI C, Assistant Professor/IT, GCT 159
Pack Manager
 pack manager can place widgets on
top of each other or place them side
by side. You can
 also use the fill option to make a
widget fill its entire container.
ASWINI C, Assistant Professor/IT, GCT 160
ASWINI C, Assistant Professor/IT, GCT 161
 These three labels are packed on top
of each other.
 The red label uses the option fill with
value BOTH and expand with value
1.
 The fill option uses named
constants X, Y, or BOTH to fill
horizontally, vertically, or both ways.
 The expand option tells the pack
manager to assign additional space
to the widget
ASWINI C, Assistant Professor/IT, GCT 162
ASWINI C, Assistant Professor/IT, GCT 163
 Developing a GUI application involves
the major steps in writing the program:
 1. Design the user interface (UI) by
drawing a sketch, You can use the grid
manager to position them in the
window.
 2. Process the event. When the button
is clicked, the program invokes a
callback function
ASWINI C, Assistant Professor/IT, GCT 164
ASWINI C, Assistant Professor/IT, GCT 165
ASWINI C, Assistant Professor/IT, GCT 166
ASWINI C, Assistant Professor/IT, GCT 167
Geometry Managers
 to place widgets inside a container.
 Tkinter supports three geometry managers:
◦ grid manager- places widgets into the cells of an
invisible grid in a container. use the rowspan and
columnspan parameters to place a widget in
multiple rows and columns,
◦ sticky option can be S, N, E, and W, or NW, NE,
SW, and SE.
◦ padx and pady options pad the optional
horizontal and vertical space in a cell
◦ ipadx and ipady inside the widget borders.
ASWINI C, Assistant Professor/IT, GCT 168
 pack manager
◦ pack manager can place widgets on top of each
other or place them side by side. You can
 also use the fill option to make a widget fill
its entire container.
 place manager
◦ place manager places widgets in absolute positions
ASWINI C, Assistant Professor/IT, GCT 169
ASWINI C, Assistant Professor/IT, GCT 170
 use Tkinter to create menus, popup
menus, and toolbars
ASWINI C, Assistant Professor/IT, GCT 171
FILES
ASWINI C, Assistant Professor/IT, GCT 172
Why Files?
 Data used in a program is temporary;
if it is not saved,
 lost when the program terminates.
 To permanently store save it in a file
on a disk or some other permanent
storage device.
ASWINI C, Assistant Professor/IT, GCT 173
Why Exception Handling?
 if your program tries to read data from
a file but the file does not exist?
 program will be abruptly terminated.
 how to write the program to handle
this exception so the program can
continue to execute.
ASWINI C, Assistant Professor/IT, GCT 174
Text Input and Output
• To read data from or to a file, use the
open function to create a file object
• To write use the object’s read and write
methods to read and write data.
• An absolute filename contains a filename
with
its complete path and drive letter.
Eg: /home/liang/pybook/Scores.txt,
relative filename is relative to its current
working directory.
Eg: Scores.py
ASWINI C, Assistant Professor/IT, GCT 175
Text & Binary File
• A file that can be processed using a text
editor such as Notepad on Windows or vi on
UNIX is called a text file.
• All the other files are called binary files.
• For example, Python source programs are
stored in text files and can be processed by a
text editor, but Microsoft Word files are stored
in binary files and are processed by the
Microsoft Word program.
• Although it is not technically precise and
correct, you can envision a text file as
consisting of a sequence of characters and a
binary file as consisting of a sequence of bits.
ASWINI C, Assistant Professor/IT, GCT 176
Opening a File
 first create a file object that is
associated with a physical file. This is
called opening a file.
 Syntax : fileVariable = open(filename,
mode)
ASWINI C, Assistant Professor/IT, GCT 177
 in the current directory: input =
open("Scores.txt", "r")
 the absolute filename to open the file in
Windows, as follows: input =
open(r"c:pybookScores.txt", "r")
 r prefix before the absolute filename
specifies that the string is a raw string,
which causes the
 Python interpreter to treat backslash characters
as literal backslashes.
 Without the r prefix, have to write the
statement using an escape sequence as: input
= open("c:pybookScores.txt", "r")ASWINI C, Assistant Professor/IT, GCT 178
Writing Data
 open function creates a file object,
which is an instance of the
_io.TextIOWrapper class.
 This class contains the methods for
reading and writing data and for
closing the file
ASWINI C, Assistant Professor/IT, GCT 179
 If the file already exists, the contents of the file will be
overwritten with new data.
 When a file is opened for writing or reading, a special
marker called a file pointer is positioned internally in
the file.
ASWINI C, Assistant Professor/IT, GCT 180
 invoke print(str), the function
automatically inserts the newline
character n after displaying the
string.
 However, the write function does
not automatically insert the newline
character.
ASWINI C, Assistant Professor/IT, GCT 181
Testing a File’s Existence
 import os.path
if os.path.isfile("Presidents.txt"):
print("Presidents.txt exists")
ASWINI C, Assistant Professor/IT, GCT 182
Reading Data
 the read method to read a specified
number of characters or all characters
from the file and return them as a
string,
 the readline() method to read the
next line, and the readlines() method
to read all the lines into a list of
strings.
ASWINI C, Assistant Professor/IT, GCT 183
ASWINI C, Assistant Professor/IT, GCT 184
ASWINI C, Assistant Professor/IT, GCT 185
Reading All Data from a File
 2 approaches
 read() - read all data from the file
and return it as one string.
 readlines() - read all data and return
it as a list of strings.
 if the file is so large that its contents
cannot be stored in the memory.
ASWINI C, Assistant Professor/IT, GCT 186
 loop to read one line at a time,
process it, and continue reading the
next line until it reaches the end of the
file:
ASWINI C, Assistant Professor/IT, GCT 187
ASWINI C, Assistant Professor/IT, GCT 188
Appending Data
ASWINI C, Assistant Professor/IT, GCT 189
Writing and Reading Numeric
Data
 convert them into strings and then use
the write method to write them to the
file.
 to read the numbers back correctly,
separate them with whitespace
characters, such as " " or n.
ASWINI C, Assistant Professor/IT, GCT 190
ASWINI C, Assistant Professor/IT, GCT 191
File Dialogs
 tkinter.filedialog module
◦ askopenfilename
◦ Asksaveasfilename
 Both functions return a filename. If
cancelled by the user, the function
returns None.
ASWINI C, Assistant Professor/IT, GCT 192
Exception Handling
 Exception handling enables a program
to deal with exceptions and continue
its normal execution.
 error that occurs at runtime is also
called an exception.
ASWINI C, Assistant Professor/IT, GCT 193
ASWINI C, Assistant Professor/IT, GCT 194
ASWINI C, Assistant Professor/IT, GCT 195
 The try/except block works as follows:
 ■ First, the statements in between try and except
are executed.
 ■ If no exception occurs
◦ except clause is skipped. And break statement is
executed to exit the while loop.
 If an exception occurs
◦ the rest of the clause is skipped.
◦ ■ If an exception occurs and it does not match the
exception name in the except clause, the exception
is passed on to the caller of this function; if no
handler is found, it is an unhandled exception and
execution stops with an error message displayed.
ASWINI C, Assistant Professor/IT, GCT 196
ASWINI C, Assistant Professor/IT, GCT 197
 try statement can have more than one except clause to handle
different exceptions.
 try statement may have an optional
◦ else clause, which is executed if no exception is raised in the
try body and
◦ finally clause, which is intended to define cleanup actions that
must be performed under all circumstances.
ASWINI C, Assistant Professor/IT, GCT 198
ASWINI C, Assistant Professor/IT, GCT 199
Raising Exceptions
 Exceptions are wrapped in objects,
and objects are created from classes.
 An exception is raised from a function.
◦ raise ExceptionClass("Something is
wrong")
 ex = RuntimeError("Wrong
argument")
 raise ex
ASWINI C, Assistant Professor/IT, GCT 200
 enables a function to throw an exception to
its caller.
 Without this capability, the called function
itself must handle the exception or
terminate the program.
 Here, library function can detect the error,
but only the caller knows what needs to be
done when an error occurs.
 to separate the detection of an error (done
in a called function) from the handling of an
error (done in the calling method).
ASWINI C, Assistant Professor/IT, GCT 201
ASWINI C, Assistant Professor/IT, GCT 202
Processing Exceptions Using Exception
Objects
 You can access an exception object in the
except clause.
ASWINI C, Assistant Professor/IT, GCT 203
Defining Custom Exception
Classes
 define a custom exception class by
extending BaseException or a subclass
of BaseException.
 The order in which exceptions are specified
in except blocks is important, because
Python finds a handler in this order.
 If an except block for a superclass type
appears before an except block for a
subclass type, the except block for the
subclass type will never be
 executed.
ASWINI C, Assistant Professor/IT, GCT 204
 Thus, it would be wrong to write the code as
follows:
ASWINI C, Assistant Professor/IT, GCT 205
References:
1. Y. Daniel Liang “Introduction to
Programming Using Python” ,Pearson,
2013
2.Charles Dierbach ,”Introduction to
Computer Science Using Python: A
Computational Problem-Solving
Focus”, Wiley Publications, 2012.
ASWINI C, Assistant Professor/IT, GCT 206
THANK YOU
ASWINI C, Assistant Professor/IT, GCT 207
ASWINI C, Assistant Professor/IT, GCT 208

Weitere ähnliche Inhalte

Was ist angesagt?

Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Languagesatvirsandhu9
 
C++ programming intro
C++ programming introC++ programming intro
C++ programming intromarklaloo
 
C++ Programming Language Training in Ambala ! Batra Computer Centre
C++ Programming Language Training in Ambala ! Batra Computer CentreC++ Programming Language Training in Ambala ! Batra Computer Centre
C++ Programming Language Training in Ambala ! Batra Computer Centrejatin batra
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in PythonSumit Satam
 
introduction to python
 introduction to python introduction to python
introduction to pythonJincy Nelson
 
45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambala45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambalajatin batra
 
Introduction to Python Part-1
Introduction to Python Part-1Introduction to Python Part-1
Introduction to Python Part-1Devashish Kumar
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming LanguageTahani Al-Manie
 
Introduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIMLIntroduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIMLVijaySharma802
 
Lesson 03 python statement, indentation and comments
Lesson 03   python statement, indentation and commentsLesson 03   python statement, indentation and comments
Lesson 03 python statement, indentation and commentsNilimesh Halder
 

Was ist angesagt? (20)

Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Language
 
Welcome to python workshop
Welcome to python workshopWelcome to python workshop
Welcome to python workshop
 
C++ programming intro
C++ programming introC++ programming intro
C++ programming intro
 
C++ Programming Language Training in Ambala ! Batra Computer Centre
C++ Programming Language Training in Ambala ! Batra Computer CentreC++ Programming Language Training in Ambala ! Batra Computer Centre
C++ Programming Language Training in Ambala ! Batra Computer Centre
 
C++ How to program
C++ How to programC++ How to program
C++ How to program
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
introduction to python
 introduction to python introduction to python
introduction to python
 
45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambala45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambala
 
Python second ppt
Python second pptPython second ppt
Python second ppt
 
Introduction to Python Part-1
Introduction to Python Part-1Introduction to Python Part-1
Introduction to Python Part-1
 
Data Handling
Data HandlingData Handling
Data Handling
 
Python revision tour i
Python revision tour iPython revision tour i
Python revision tour i
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
 
Basics of c++
Basics of c++Basics of c++
Basics of c++
 
Python Tutorial
Python TutorialPython Tutorial
Python Tutorial
 
Python basics
Python basicsPython basics
Python basics
 
Introduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIMLIntroduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIML
 
Python basics
Python basicsPython basics
Python basics
 
Lesson 03 python statement, indentation and comments
Lesson 03   python statement, indentation and commentsLesson 03   python statement, indentation and comments
Lesson 03 python statement, indentation and comments
 

Ähnlich wie Introduction to Python

Ähnlich wie Introduction to Python (20)

Introduction to r
Introduction to rIntroduction to r
Introduction to r
 
Unit i intro-operators
Unit   i intro-operatorsUnit   i intro-operators
Unit i intro-operators
 
additional.pptx
additional.pptxadditional.pptx
additional.pptx
 
3Arrays, Declarations, Expressions, Statements, Symbolic constant.pptx
3Arrays, Declarations, Expressions, Statements, Symbolic constant.pptx3Arrays, Declarations, Expressions, Statements, Symbolic constant.pptx
3Arrays, Declarations, Expressions, Statements, Symbolic constant.pptx
 
C PROGRAMMING BASICS- COMPUTER PROGRAMMING UNIT II
C PROGRAMMING BASICS- COMPUTER PROGRAMMING UNIT IIC PROGRAMMING BASICS- COMPUTER PROGRAMMING UNIT II
C PROGRAMMING BASICS- COMPUTER PROGRAMMING UNIT II
 
Unit ii ppt
Unit ii pptUnit ii ppt
Unit ii ppt
 
Numerical analysis
Numerical analysisNumerical analysis
Numerical analysis
 
C programing Tutorial
C programing TutorialC programing Tutorial
C programing Tutorial
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
C- Programming Assignment 3
C- Programming Assignment 3C- Programming Assignment 3
C- Programming Assignment 3
 
Unit-IV Strings.pptx
Unit-IV Strings.pptxUnit-IV Strings.pptx
Unit-IV Strings.pptx
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++
 
Mcs 011 solved assignment 2015-16
Mcs 011 solved assignment 2015-16Mcs 011 solved assignment 2015-16
Mcs 011 solved assignment 2015-16
 
Python For Machine Learning
Python For Machine LearningPython For Machine Learning
Python For Machine Learning
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic
 
Introduction to programming c and data structures
Introduction to programming c and data structuresIntroduction to programming c and data structures
Introduction to programming c and data structures
 
C Programming Unit-4
C Programming Unit-4C Programming Unit-4
C Programming Unit-4
 
Lecture 1 mte 407
Lecture 1 mte 407Lecture 1 mte 407
Lecture 1 mte 407
 

Kürzlich hochgeladen

Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...
Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...
Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...amrabdallah9
 
nvidia AI-gtc 2024 partial slide deck.pptx
nvidia AI-gtc 2024 partial slide deck.pptxnvidia AI-gtc 2024 partial slide deck.pptx
nvidia AI-gtc 2024 partial slide deck.pptxjasonsedano2
 
Dev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & LoggingDev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & LoggingMarian Marinov
 
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptxVertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptxLMW Machine Tool Division
 
UNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptxUNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptxrealme6igamerr
 
The relationship between iot and communication technology
The relationship between iot and communication technologyThe relationship between iot and communication technology
The relationship between iot and communication technologyabdulkadirmukarram03
 
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratory
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratoryدليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratory
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide LaboratoryBahzad5
 
EPE3163_Hydro power stations_Unit2_Lect2.pptx
EPE3163_Hydro power stations_Unit2_Lect2.pptxEPE3163_Hydro power stations_Unit2_Lect2.pptx
EPE3163_Hydro power stations_Unit2_Lect2.pptxJoseeMusabyimana
 
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...Amil baba
 
Power System electrical and electronics .pptx
Power System electrical and electronics .pptxPower System electrical and electronics .pptx
Power System electrical and electronics .pptxMUKULKUMAR210
 
Test of Significance of Large Samples for Mean = µ.pptx
Test of Significance of Large Samples for Mean = µ.pptxTest of Significance of Large Samples for Mean = µ.pptx
Test of Significance of Large Samples for Mean = µ.pptxHome
 
Modelling Guide for Timber Structures - FPInnovations
Modelling Guide for Timber Structures - FPInnovationsModelling Guide for Timber Structures - FPInnovations
Modelling Guide for Timber Structures - FPInnovationsYusuf Yıldız
 
Lecture 1: Basics of trigonometry (surveying)
Lecture 1: Basics of trigonometry (surveying)Lecture 1: Basics of trigonometry (surveying)
Lecture 1: Basics of trigonometry (surveying)Bahzad5
 
GENERAL CONDITIONS FOR CONTRACTS OF CIVIL ENGINEERING WORKS
GENERAL CONDITIONS  FOR  CONTRACTS OF CIVIL ENGINEERING WORKS GENERAL CONDITIONS  FOR  CONTRACTS OF CIVIL ENGINEERING WORKS
GENERAL CONDITIONS FOR CONTRACTS OF CIVIL ENGINEERING WORKS Bahzad5
 
Phase noise transfer functions.pptx
Phase noise transfer      functions.pptxPhase noise transfer      functions.pptx
Phase noise transfer functions.pptxSaiGouthamSunkara
 
Nodal seismic construction requirements.pptx
Nodal seismic construction requirements.pptxNodal seismic construction requirements.pptx
Nodal seismic construction requirements.pptxwendy cai
 
solar wireless electric vechicle charging system
solar wireless electric vechicle charging systemsolar wireless electric vechicle charging system
solar wireless electric vechicle charging systemgokuldongala
 

Kürzlich hochgeladen (20)

Lecture 2 .pdf
Lecture 2                           .pdfLecture 2                           .pdf
Lecture 2 .pdf
 
Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...
Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...
Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...
 
Lecture 2 .pptx
Lecture 2                            .pptxLecture 2                            .pptx
Lecture 2 .pptx
 
nvidia AI-gtc 2024 partial slide deck.pptx
nvidia AI-gtc 2024 partial slide deck.pptxnvidia AI-gtc 2024 partial slide deck.pptx
nvidia AI-gtc 2024 partial slide deck.pptx
 
Dev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & LoggingDev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & Logging
 
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptxVertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
 
UNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptxUNIT4_ESD_wfffffggggggggggggith_ARM.pptx
UNIT4_ESD_wfffffggggggggggggith_ARM.pptx
 
The relationship between iot and communication technology
The relationship between iot and communication technologyThe relationship between iot and communication technology
The relationship between iot and communication technology
 
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratory
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratoryدليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratory
دليل تجارب الاسفلت المختبرية - Asphalt Experiments Guide Laboratory
 
EPE3163_Hydro power stations_Unit2_Lect2.pptx
EPE3163_Hydro power stations_Unit2_Lect2.pptxEPE3163_Hydro power stations_Unit2_Lect2.pptx
EPE3163_Hydro power stations_Unit2_Lect2.pptx
 
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
 
Power System electrical and electronics .pptx
Power System electrical and electronics .pptxPower System electrical and electronics .pptx
Power System electrical and electronics .pptx
 
Test of Significance of Large Samples for Mean = µ.pptx
Test of Significance of Large Samples for Mean = µ.pptxTest of Significance of Large Samples for Mean = µ.pptx
Test of Significance of Large Samples for Mean = µ.pptx
 
Modelling Guide for Timber Structures - FPInnovations
Modelling Guide for Timber Structures - FPInnovationsModelling Guide for Timber Structures - FPInnovations
Modelling Guide for Timber Structures - FPInnovations
 
Lecture 1: Basics of trigonometry (surveying)
Lecture 1: Basics of trigonometry (surveying)Lecture 1: Basics of trigonometry (surveying)
Lecture 1: Basics of trigonometry (surveying)
 
GENERAL CONDITIONS FOR CONTRACTS OF CIVIL ENGINEERING WORKS
GENERAL CONDITIONS  FOR  CONTRACTS OF CIVIL ENGINEERING WORKS GENERAL CONDITIONS  FOR  CONTRACTS OF CIVIL ENGINEERING WORKS
GENERAL CONDITIONS FOR CONTRACTS OF CIVIL ENGINEERING WORKS
 
Lecture 4 .pdf
Lecture 4                              .pdfLecture 4                              .pdf
Lecture 4 .pdf
 
Phase noise transfer functions.pptx
Phase noise transfer      functions.pptxPhase noise transfer      functions.pptx
Phase noise transfer functions.pptx
 
Nodal seismic construction requirements.pptx
Nodal seismic construction requirements.pptxNodal seismic construction requirements.pptx
Nodal seismic construction requirements.pptx
 
solar wireless electric vechicle charging system
solar wireless electric vechicle charging systemsolar wireless electric vechicle charging system
solar wireless electric vechicle charging system
 

Introduction to Python

  • 1. INTRODUCTION TO PYTHON PROGRAMMING ASWINI C, Assistant Professor/IT, GCT 1
  • 2. Course Outcomes:  Use various data types.  Use control statements and functions.  Analyze the arrangement of data elements in Lists, tuples, sets and Dictionary.  Develop application using object oriented programming and GUI.  Handle exceptions and perform file operations. ASWINI C, Assistant Professor/IT, GCT 2
  • 3. Reading Input from the Console  Accept input from the user.  Use the input function to ask the user to input a value for the radius.  variable = input("Enter a value: ")  Use the function eval to evaluate and convert it to a numeric value Or use type converters  Python also supports simultaneous assignment in syntax like this:  var1, var2, ..., varn = exp1, exp2, ..., expn ASWINI C, Assistant Professor/IT, GCT 3
  • 4. Operators ASWINI C, Assistant Professor/IT, GCT 4
  • 5. ASWINI C, Assistant Professor/IT, GCT 5
  • 6. Operator Precedence  following operator precedence rule is used to determine the order of evaluation.  ■ Exponentiation (**) is applied first.  ■ Multiplication (*), float division (/), integer division (//) , and remainder operators (%) are applied next.  ■ Addition (+) and subtraction (-) operators are applied last.  Hint: If an expression contains several addition, subtraction multiplication, division, and remainder operators, they are applied from left to right. ASWINI C, Assistant Professor/IT, GCT 6
  • 7. Operator Precedence Example ASWINI C, Assistant Professor/IT, GCT 7
  • 8. ASWINI C, Assistant Professor/IT, GCT Nov 10, 2017 AD c 2018 8 Python Strings 1 Introduction to Strings 2. String Operations 8
  • 9. ASWINI C, Assistant Professor/IT, GCT AD c 2018 9 Strings are a collection of characters contained within quote marks. Introduction to Strings The following are examples of strings... "Anne was here" "Anne was here on Friday 31st October 2008" "9396633" "A" "7" 9
  • 10. ASWINI C, Assistant Professor/IT, GCT Nov 10, 2017 AD c 2018 10 Strings are a collection of characters contained within quote marks. Strings are composed of characters Each character has a numeric code and belongs to a set of characters known as the Unicode character set. 10
  • 11. ASWINI C, Assistant Professor/IT, GCT Nov 10, 2017 AD c 2018 11 The Unicode character set The Unicode character set includes the characters A - Z, the numbers 0 - 9, punctuation marks, the space character, as well as many other characters... 11
  • 12. ASWINI C, Assistant Professor/IT, GCT AD c 2018 12 Strings are a collection of characters contained within quote marks. Strings are contained within quote marks Strings can be contained within single, double or triple quote marks... 12
  • 13. ASWINI C, Assistant Professor/IT, GCT AD c 2018 13 An example program using strings Strings can be contained within single, double or triple quote marks... 'Anne was here' '''Anne was here on Saturday 30th October 2004''' “9396633" 13
  • 14. ASWINI C, Assistant Professor/IT, GCT AD c 2018 14 If you want to print a double quote mark (") within a string, contain the string in single quote marks (')... print ('Here is a double quote ", and "more" ') Printing double quote marks within a string 14
  • 15. ASWINI C, Assistant Professor/IT, GCT AD c 2018 15 If you want to print an apostrophe (or a single quote mark) within a string, contain the string in double quotes... print ("This is Anne's spam") Printing a string which contains an apostrophe 15
  • 16. ASWINI C, Assistant Professor/IT, GCT Nov 10, 2017 AD c 2018 16 Python Strings 1 Introduction to String 2 String Operations 16
  • 17. ASWINI C, Assistant Professor/IT, GCT Nov 10, 2017 AD c 2018 17 Within a string, (i.e. contained in quote marks), a number is treated as a character. Numbers can be treated as characters You cannot perform regular arithmetic on numbers stored as characters... 17
  • 18. ASWINI C, Assistant Professor/IT, GCT AD c 2018 18 Repeating (multiplying) strings using * You cannot perform regular arithmetic on numbers stored as characters, but... you can "multiply" (repeat) strings: "3" * 4 results in "3333" 18
  • 19. ASWINI C, Assistant Professor/IT, GCT AD c 2018 19 Joining strings together using the + symbol is a process known as concatenation. Strings can be joined together using the + symbol "Anne " + "was " + ("here " * 3) results in "Anne was here here here " 19
  • 20. ASWINI C, Assistant Professor/IT, GCT AD c 2018 20 Any element (character) of a string can be accessed by indexing. Indexing strings using the [] operator s1 = "Anne Dawson" print (s1[0], s1[5]) prints A D 20
  • 21. ASWINI C, Assistant Professor/IT, GCT AD c 2018 21 Any substring of a string can be obtained by using the [] operator. Slicing strings using the [ ] operator s1 = "Anne Dawson" print (s1[0:1],s1[5:7]) print (s1[6:9]) prints A Da aws 21
  • 22. ASWINI C, Assistant Professor/IT, GCT AD c 2018 22 The length of any string can be determined using the len method. Finding the length of a string using len s1 = "Anne" s2 = "Dawson" s3 = "" print (len(s1), end=" ") print (len(s2), end=" ") print (len(s3)) prints 4 6 0 22
  • 23. ASWINI C, Assistant Professor/IT, GCT AD c 2018 23 Printing strings and numbers d = 10 c = 75 print ('Total is: ', d, 'dollars and', c, ' cents ') We can print string values and number values from the same print statement by separating them with commas: >>> Total is: 10 dollars and 75 cents 23
  • 24. ASWINI C, Assistant Professor/IT, GCT Nov 10, 2017 AD c 2018 24 Numbers can be printed from within a single string by using a special method known as string formatting. 24
  • 25. ASWINI C, Assistant Professor/IT, GCT AD c 2018 25 String Formatting and % In string formatting, we use the % symbol. The % operator can also be used for a different purpose as the modulus operator (finding the remainder after an integer division). The % symbol is said to be overloaded. 25
  • 26. ASWINI C, Assistant Professor/IT, GCT Nov 10, 2017 AD c 2018 26 String Formatting and % In the following example we see the % operator being used to specify how a string should be printed (i.e. string formatting). An overloaded operator behaves differently depending on the context. 26
  • 27. ASWINI C, Assistant Professor/IT, GCT AD c 2018 27 Printing integers within a string x = 20 y = 75 print ('The sum of %d and %d is %d' % (x, y, x + y)) >>> The sum of 20 and 75 is 95 The three %d formatting codes represent where the decimal integers shown in brackets after the % symbol should be printed. 27
  • 28. ASWINI C, Assistant Professor/IT, GCT AD c 2018 28 Printing floats within a string x = 20.512 y = 15.269 print ('The sum of %f and %f is %f' % (x, y, x + y)) >>> The sum of 20.512000 and 15.269000 is 35.781000 The three %f represent where the float values shown in brackets after the % symbol should be printed. 28
  • 29. ASWINI C, Assistant Professor/IT, GCT AD c 2018 29 Specifying the number of decimal places x = 20.512 y = 15.269 print ('The sum of %0.2f and %0.2f is %0.2f' % (x, y, x + y)) >>> The sum of 20.51 and 15.27 is 35.78 The three %0.2f represent where the float values (to 2 decimal places) shown in brackets after the % symbol should be printed. 29
  • 30. ASWINI C, Assistant Professor/IT, GCT AD c 2018 30 %s is the formatting code which represents a string.print ('Python is a %s language.' % 'great') >>> Python is a great language. String formatting code %s The %s represents where the string value (shown after the % symbol) should be printed. 30
  • 31. ASWINI C, Assistant Professor/IT, GCT AD c 2018 31 The string method find is used to locate the position of one string within another. s1 = 'spamandeggs' x = s1.find('and') print (x) >>> 4 Finding a string within a string The output: 31
  • 32. ASWINI C, Assistant Professor/IT, GCT AD c 2018 32 The string method replace is used to replace text within a string with new text. s1 = 'spam and eggs' s2 = s1.replace('and','without') print (s2) >>> spam without eggs Replacing text within a string The output: 32
  • 33. ASWINI C, Assistant Professor/IT, GCT Nov 10, 2017 AD c 2018 33 An escape sequence is a backslash () followed by one or more characters, which is inserted into a string to perform a special task. E.g. n generates a new line and t generates a tab within the string. . . Escape Sequences 33
  • 34. ASWINI C, Assistant Professor/IT, GCT AD c 2018 34 The following example shows a string with two escape sequences: s = 'onentwotthree' print (s) >>> one two three A string containing escape sequences The output: 34
  • 35. ASWINI C, Assistant Professor/IT, GCT AD c 2018 35 The following example shows that each escape sequence counts as one character: s = 'onentwotthree' print (s) print (len(s)) >>> one two three 13 An escape sequence counts as one character The output: 35
  • 36. ASWINI C, Assistant Professor/IT, GCT AD c 2018 36 The following example shows that you can iterate over strings in loops using for statements and test for membership with the in expression operator: s = 'Anne was here' for c in s: print (c, end=" ") print ('w' in s, end=" ") print (' ' in s, end=" ") print ('x' in s) >>> A n n e w a s h e r e True True False String iteration and membership The output: 36
  • 37. ASWINI C, Assistant Professor/IT, GCT Nov 10, 2017 AD c 2018 37 Most real-world Python programs contain strings. Strings Strings allow you to collect characters, so that you can treat them as a group. Strings have left-to-right positional ordering, with index capability. Strings are immutable which means that they cannot be changed. But new string objects can be created from existing string objects. Strings are homogeneous in that they consist only of characters. 37
  • 38. Control structures  Sequential control vs selection control vs iterative control  A control statement is a statement that determines the control flow of a set of statements.  A control structure is a set of statements and the control statements controlling their execution. ◦ Three fundamental forms of control in programming are  Sequential  Selection  Iteration.
  • 39. Simple decisions  For example, if n < 1: print("Your input number is too low.") if n > 10000: print("Your input number is too large.")  A relational statement gives either True or False (Python's keywords)  Try ◦ print(int(True)) ◦ print(int(False))
  • 40. To do or not to do The Python if statement is used to implement the decision. if <condition>: <body> The body is a sequence of one or more statements indented under the if heading. The body is executed if condition is evaluated to True. The body is skipped if condition is evaluated to False.
  • 42. Boolean Expressions (Conditions) The Boolean data type contains two Boolean values, denoted as True and False in Python. A Boolean expression is an expression that evaluates to a Boolean value. Need a relational operator to evaluate a boolean expression. The relational operators on the next slide can be applied to any set of values that has an ordering. ◦ Number comparison ◦ Lexicographical ordering for string comparison
  • 43. Relational Operators Python Mathematics Meaning < < Less than <= ≤ Less than or equal to == = Equal to >= ≥ Greater than or equal to > > Greater than != ≠ Not equal to
  • 44. Two other membership operators The in operator is used to determine if a specific value is in a given list, returning True if found, and False otherwise. The not in operator returns the opposite result. Try  10 in [10, 20, 30, 40]  10 not in [10, 20, 30, 40]  "blue" in ["red", "yellow", "black"]  "blue" not in ["red", "yellow", "black"]  "o" in "peter paul and mary"
  • 45. Boolean Operators Source: Charles Dierbach. 2013. Introduction to Computer Science Using Python. Wiley.
  • 46. Operator Precedence Source: Charles Dierbach. 2013. Introduction to Computer Science Using Python. Wiley.
  • 47. Two-Way Decisions  In Python, a two-way decision can be implemented by attaching an else clause onto an if clause.  This is called an if-else statement: if <condition>: <statements> else: <statements>  E.g., if 1 <= n and n <= 10000: print("Your input number is ", str(n)+ ".") else: print("Your input must be between 1 and 1000.")
  • 48. Multi-Way Decisions • Use nested if-else statement to implement multi-way decisions. • if <condition1>: <case1 statements> • else: if <condition2>: <case2 statements> else: if <condition3>: <case3 statements> else: <default statements>
  • 49. Multi-Way Decisions using elif • In Python, else-if can be combined into elif: if <condition1>: <case1 statements> elif <condition2>: <case2 statements> elif <condition3>: <case3 statements> else: <default statements> The else is optional. If there is no else, it is possible that no indented block would be executed.
  • 50. For Loops: A Quick Review The for statement allows us to iterate through a sequence of values. for <var> in <sequence>: <body> The loop index variable var takes on each successive value in the sequence, and the statements in the body of the loop are executed once for each value. For example, ◦ for num in range(0, 10): print(num)
  • 51. Indefinite Loops  The for loop is a definite loop, meaning that the number of iterations is determined when the loop starts.  We can’t use a definite loop unless we know the number of iterations ahead of time.  The indefinite or conditional loop keeps iterating until certain conditions are met.
  • 52. Indefinite Loops  while <condition>: <body>  condition is a Boolean expression, just like in if statements. The body is a sequence of one or more statements.  Semantically, the body of the loop executes repeatedly as long as the condition remains true. When the condition is false, the loop terminates.
  • 54. An example  Here’s an example of using a while loop to print out range(10). i = 0 while i <= 9: print(i) i = i + 1  The code has the same output as this for loop: for i in range(10): print i
  • 55. Interactive Loops # average2.py # A program to average a set of numbers # Illustrates interactive loop with two accumulators moredata = "yes" sum = 0.0 count = 0 while moredata[0] == 'y': x = int(input("Enter a number >> ")) sum = sum + x count = count + 1 moredata = input("Do you have more numbers (yes or no)? ") print ("nThe average of the numbers is", sum / count)
  • 56. Sentinel Loops  A sentinel loop continues to process data until reaching a special value that signals the end.  This special value is called the sentinel.  The sentinel must be distinguishable from the data since it is not processed as part of the data. get the first data item while item is not the sentinel process the item get the next data item
  • 57. Nested Loops • Consider the following code in A4 def main(): for i in range(1, 6): for j in range(1, 6): print("*", end=""); print() main() • What is the aim of it?
  • 58. Designing Nested Loops  Break the problem into two parts.  The first is to process line by line (outer loop).  The second is to process the items on each line (inner loop).  Note that the two parts are not inter- dependent.
  • 59. Post-Test Loop  Say we want to write a program that is supposed to get a nonnegative number from the user.  If the user types an incorrect input, the program asks for another value.  This process continues until a valid value has been entered.  This process is input validation.
  • 60. Post-Test Loop repeat get a number from the user until number is >= 0
  • 61. Post-Test Loop  Python doesn’t have a built-in statement to do this, but we can do it with a slightly modified while loop.  We could simulate a post-test loop by number = -1 while number < 0: number = eval(input("Enter a positive number: "))
  • 62. Using a break • Some programmers prefer to simulate a post-test loop by using the Python break statement. • Executing break causes Python to immediately exit the enclosing loop. • For example, while True: number = eval(input("Enter a positive number: ")) if number >= 0: break # Exit loop if number is valid  Avoid using break often within loops, because the logic of a loop is hard to follow when there are multiple exits.
  • 63. Functions ASWINI C, Assistant Professor/IT, GCT 63
  • 64. Some Built –in Functions ASWINI C, Assistant Professor/IT, GCT 64
  • 65. ASWINI C, Assistant Professor/IT, GCT 65
  • 66.  function is a named sequence of statements that belong together.  to help us organize programs into chunks that match how we think about the problem. def <NAME>( <PARAMETERS> ): <STATEMENTS>  1. A header line which begins with a keyword and ends with a colon.  2. A body consisting of one or more Python statements, each indented the same amount— the Python style guide ASWINI C, Assistant Professor/IT, GCT 66
  • 67. • any names we want for the functions we create • except a name that is a Python keyword, • names must follow the rules for legal identifiers. • There can be any number of statements inside the function, but they have to be indented from the def. • keyword in the header is def, which is followed by the name of the function and some parameters enclosed in parentheses. • The parameter list may be empty, or it may contain any number of parameters separated from one another by commas. • In either case, the parentheses are required. • The parameters specifies what information, if any, we have to provide in order to use the new function. ASWINI C, Assistant Professor/IT, GCT 67
  • 68. Positional and Keyword Arguments  There are two kinds of arguments: ◦ Using positional arguments requires that the arguments be passed in the same order as their respective parameters in the function header. ◦ nPrintln(“hi”, 4) ◦ Prints the message “Hi” 4 times ASWINI C, Assistant Professor/IT, GCT 68
  • 69.  keyword arguments, passing each argument in the form name value.  nPrintln(n = 5, message = "good") passes 5 to n and "good" to message.  Message “good” is printed 5 times  The arguments can appear in any order using keyword arguments. ASWINI C, Assistant Professor/IT, GCT 69
  • 70.  It is possible to mix positional arguments with keyword arguments, but the positional arguments cannot appear after any keyword arguments. ASWINI C, Assistant Professor/IT, GCT 70
  • 71. ASWINI C, Assistant Professor/IT, GCT 71
  • 72. This function is named draw_square. It has two parameters: one to tell the function which turtle to move around, and the other to tell it the size of the square we want drawn. Make sure you know where the body of the function ends — it depends on the indentation, and the blank lines don’t count for this purpose! ASWINI C, Assistant Professor/IT, GCT 72
  • 73. Docstrings for documentation • If the first thing after the function header is a string, it is treated as a docstring and gets special treatment in Python and in some programming tools. • Docstrings are the key way to document our functions in Python and the documentation part is important. • Docstrings are usually formed using triple-quoted strings as they allow us to easily expand the docstring • Just to differentiate from comments, a string at the start of a function (a docstring) is retrievable by Python tools at runtime. • By contrast, comments are completely eliminated when the program is parsed. ASWINI C, Assistant Professor/IT, GCT 73
  • 74.  Function definition – how it should work  Function call. Eg: built-in functions like print, range and int. Function calls contain the name of the function being executed followed by a list of values, called arguments, which are assigned to the parameters in the function definition. ASWINI C, Assistant Professor/IT, GCT 74
  • 75. ASWINI C, Assistant Professor/IT, GCT 75
  • 76. Functions can call other functions • Functions can call other functions. • So far, it may not be clear why it is worth the trouble to create all of these new functions. Actually, there are a lot of reasons, but this example demonstrates two: • 1. Creating a new function gives us an opportunity to name a group of statements. Functions can simplify a • program by hiding a complex computation behind a single command. • 2. Creating a new function can make a program smaller by eliminating repetitive code. , create a function before we can execute it. ASWINI C, Assistant Professor/IT, GCT 76
  • 77. Flow of execution • to ensure that a function is defined before its first use, we have to know the order in which statements are executed, which is called the flow of execution. • Execution always begins at the first statement of the program. • Statements are executed one at a time, in order from top to bottom. • Function definitions do not alter the flow of execution of the program, but remember that statements inside the function are not executed until the function is called. • we can define one function inside another. • In this case, the inner definition isn’t executed until the outer function is called. • Instead of going to the next statement, the flow jumps to the first line of the called function, executes all the statements there, and then comes back to pick up where it left off. ASWINI C, Assistant Professor/IT, GCT 77
  • 78. Functions that require arguments  Most functions require arguments: the arguments provide for generalization. Eg: abs(-5) = 5  Some functions take more than one argument. Eg:pow(2,3)=8 takes two arguments, the base and the exponent.  Inside the function, the values that are passed get assigned to variables called parameters. ASWINI C, Assistant Professor/IT, GCT 78
  • 79. Functions that return values ASWINI C, Assistant Professor/IT, GCT 79
  • 80. Recursion 80ASWINI C, Assistant Professor/IT, GCT
  • 81. • Recursion means “defining something in terms of itself” • smaller scale, perhaps multiple times, to achieve your objective. • Programming languages generally support recursion, which means that, in order to solve a problem, functions can call themselves to solve smaller subproblems. • Any problem that can be solved iteratively (with a for or while loop) can also be solved recursively. 81ASWINI C, Assistant Professor/IT, GCT
  • 82. Drawing Fractals  fractal is a drawing which also has self-similar structure, where it can be defined in terms of itself.  This is a typical example of a problem which is recursive in nature. 82ASWINI C, Assistant Professor/IT, GCT
  • 83. Recursive data structures • Lists and tuples can also be nested, providing many possibilities for organizing data. • The organization of data for the purpose of making it easier to use is called a data structure. • Eg:Votes arriving from individual wards, precincts, municipalities, counties, and states are sometimes reported as a sum total of votes and sometimes as a list of subtotals of votes. • A nested number list is a list whose elements are either: – numbers – nested number lists 83ASWINI C, Assistant Professor/IT, GCT
  • 84. • recursive data structures that are partially composed of smaller and simpler instances of themselves. • The definition is not circular, since at some point we will reach a list that does not have any lists as elements. • Now suppose our job is to write a function that will sum all of the values in a nested number list. • >>> sum([1, 2, 8]) • 11 • >>> sum([1, 2, [11, 13], 8]) • Traceback (most recent call last): • File "<interactive input>", line 1, in <module> • TypeError: unsupported operand type(s) for +: 'int' and 'list' • the third element of this list, [11, 13], is itself a list, so it cannot just be added to 1, 2, and 8. 84ASWINI C, Assistant Professor/IT, GCT
  • 85. Processing recursive number lists • To sum all the numbers in our recursive nested number list we need to –traverse the list, –visiting each of the elements within its nested structure, –adding any numeric elements to our sum –recursively repeating the summing process • with any elements which are themselves sub-lists. 85ASWINI C, Assistant Professor/IT, GCT
  • 86. Mutual Recursion  also possible to make multiple functions that call eachother.  This is rarely really usefull, but it can be used to make state machines 86ASWINI C, Assistant Professor/IT, GCT
  • 87. stack diagram  A graphical representation of a stack of functions, their variables, and the values to which they refer.  track of which variables can be used where, it is sometimes useful to draw a stack diagram. 87ASWINI C, Assistant Professor/IT, GCT
  • 88. def cat_twice(part1, part2): cat = part1 + part2 print_twice(cat) def print_twice(bruce): print(bruce) print(bruce) line1 = 'Bing tiddle ‘ line2 = 'tiddle bang.‘ cat_twice(line1, line2)  Cat_twice function takes two arguments, concatenates them, and prints the result twice.  >>> Bing tiddle tiddle bang.  Bing tiddle tiddle bang.  When cat_twice terminates, the variable cat is destroyed. If we try to print it, we get an exception 88ASWINI C, Assistant Professor/IT, GCT
  • 89. Fruitful functions and void functions  functions, such as the math functions, return results; for lack of a better name, which are fruitful functions. ◦ x = math.cos(radians) ◦ golden = (math.sqrt(5) + 1) / 2  perform an action but don’t return a value. are called void functions. ◦ print_twice 89ASWINI C, Assistant Professor/IT, GCT
  • 90. Map, filter and reduce  To add up all the numbers in a list, you can use a loop like this: def add_all(t): total = 0 for x in t: total += x return total  The += operator provides a short way to update a variable. This augmented assignment statement,  As the loop runs, total accumulates the sum of the elements; a variable used this way is sometimes called an accumulator. 90ASWINI C, Assistant Professor/IT, GCT
  • 91.  Adding up the elements of a list using built- in function, sum:  >>> t = [1, 2, 3]  >>> sum(t)  6  An operation like this that combines a sequence of elements into a single value is sometimes called reduce.  Sometimes you want to traverse one list while building another. For example, the following  function takes a list of strings and returns a new list that contains capitalized strings: 91ASWINI C, Assistant Professor/IT, GCT
  • 92.  res is initialized with an empty list; each time through the loop, we append the next element.  So res is another kind of accumulator.  capitalize_all is sometimes called a map because it “maps” a function (in this case the method capitalize) onto each of the elements in a sequence. 92ASWINI C, Assistant Professor/IT, GCT
  • 93.  Another common operation is to select some of the elements from a list and return a sublist.  isupper is a string method that returns True if the string contains only upper case letters.  An operation like only_upper is called a filter because it selects some of the elements and filters out the others. 93ASWINI C, Assistant Professor/IT, GCT
  • 94. Python lambda (Anonymous Functions)  In Python, anonymous function means that a function is without a name.  lambda keyword is used to create anonymous functions. It has the following syntax:  lambda arguments: expression 94ASWINI C, Assistant Professor/IT, GCT
  • 95.  have any number of arguments but only one expression, which is evaluated and returned.  use lambda functions wherever function objects are required.  lambda functions are syntactically restricted to a single expression.  It has various uses in particular fields of programming besides other types of expressions in functions. 95ASWINI C, Assistant Professor/IT, GCT
  • 96. def cube(y): return y*y*y; g = lambda x: x*x*x print(g(7)) print(cube(5)) Output: 343 125 96ASWINI C, Assistant Professor/IT, GCT
  • 97. Use of lambda() with filter()  filter out all the elements of a sequence “sequence”, for which the function returns True.  program that returns the odd numbers from an input list:  li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]  final_list = list(filter(lambda x: (x%2 != 0) , li))  print(final_list)  Output:  [5, 7, 97, 77, 23, 73, 61 97ASWINI C, Assistant Professor/IT, GCT
  • 98. Use of lambda() with reduce()  with a lambda function and a list and a new reduced result is returned.  This performs a repetitive operation over the pairs of the list.  from functools import reduce  li = [5, 8, 10, 20, 50, 100]  sum = reduce((lambda x, y: x + y), li)  print (sum)  Output:  193 98ASWINI C, Assistant Professor/IT, GCT
  • 99. Use of lambda() with map()  with a lambda function and a list and a new list is returned which contains all the lambda modified items returned by that function for each item. Example:  li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]  final_list = list(map(lambda x: x*2 , li))  print(final_list)  Output:  [10, 14, 44, 194, 108, 124, 154, 46, 146, 122] 99ASWINI C, Assistant Professor/IT, GCT
  • 100. my_list = [12, 65, 54, 39, 102, 339, 221, 50, 70, ] result = list(filter(lambda x: (x % 13 == 0), my_list)) print(result) 100ASWINI C, Assistant Professor/IT, GCT
  • 101. my_list = ["geeks", "geeg", "keek", "practice", "aa"] result = list(filter(lambda x: (x == "".join(reversed(x))), my_list)) print(result) 101ASWINI C, Assistant Professor/IT, GCT
  • 102. from collections import Counter my_list = ["geeks", "geeg", "keegs", "practice", "aa"] str = "eegsk“ result = list(filter(lambda x: (Counter(str) == Counter(x)), my_list)) print(result) 102ASWINI C, Assistant Professor/IT, GCT
  • 103. LISTS ASWINI C, Assistant Professor/IT, GCT 103
  • 104.  How lists are useful in programming  How to create lists- Create lists by using list comprehension  Common operations for sequences  Use the len, min, max, sum, and random.shuffle functions with a list  Access list elements by using indexed variables  Obtain a sublist from a larger list by using the slicing operator [start : end]  Use the + (concatenation), * (repetition), and in/not in operators on lists  Traverse elements in a list using a for loop  Compare the contents of two lists by using comparison operators  Invoke a list’s append, count, extend, index, insert, pop, remove, reverse, sort methods  Split a string into a list using the str’s split method  Read data from the console into a list.  Use lists in application development  Copy the contents of one list to another  Develop and invoke functions that include list arguments and return lists  Search elements using the linear or binary search algorithm.  Sort a list by using the selection sort, Insertion sort  Develop a bouncing ball animation by using a list ASWINI C, Assistant Professor/IT, GCT 104
  • 105. Why lists? • list can store a collection of data of any size. • type called a list stores a sequential collection of elements • read 100 numbers, compute their average, and then find out how many of the numbers are ASWINI C, Assistant Professor/IT, GCT 105
  • 106. Why can’t we use array? • Many programming languages, a type called an array to store a sequence of data. • An array has a fixed size. • A Python list’s size is flexible. • It can grow and shrink on demand. • A list is a sequence defined by the list class. • It contains the methods for creating, manipulating, and processing lists. • Elements in a list can be accessed through an index. ASWINI C, Assistant Professor/IT, GCT 106
  • 107. Creating Lists  Using List constructor  elements in a list are separated by commas and are enclosed by a pair of brackets ([]). ASWINI C, Assistant Professor/IT, GCT 107
  • 108.  A list can contain the elements of the same type or mixed types. For example, the following  list4 = [2, "three", 4]  List comprehensions provide a concise way to create a sequential list of elements.  A list comprehension consists of brackets containing an expression followed by a ◦ for clause  then zero or more for or if clauses. ASWINI C, Assistant Professor/IT, GCT 108
  • 109. ASWINI C, Assistant Professor/IT, GCT 109
  • 110. List Is a Sequence Type  Strings and lists are sequence types.  String is a sequence of characters, while a list is a sequence of any elements.  x in s True if element x is in sequence s.  x not in s True if element x is not in sequence s.  len(s) Length of sequence s, i.e., the number of elements in s.  min(s) Smallest element in sequence s.  max(s) Largest element in sequence s.  sum(s) Sum of all numbers in sequence s.  for loop Traverses elements from left to right in a for loop. ◦ >>>for u in myList: ◦ >>>…….print(u) # prints all elements in myList ◦ for i in range(0, len(myList), 2): ◦ print(myList[i]) # print elements in index position at 0 to 9 with interval 2  <, <=, >, >=, =, != Compares two sequences.  shuffle function in the random module to shuffle the elements randomly in the list.  s1 + s2 Concatenates two sequences s1 and s2. (Concatenation operator)  s * n, n * s n copies of sequence s concatenated. (Repetition Operator) ASWINI C, Assistant Professor/IT, GCT 110
  • 111. Index Operator []  range from 0 to len(myList)-1 ◦ s[i] ith element in sequence s. ◦ myList[index] can be used just like a variable, so it is also known as an indexed variable. >>>myList = [5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123] >>>myList[2] = myList[0] + myList[1] #adds index 0 and 1 value to 2 >>>myList [5.6, 4.5, 10.1, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123]  The following loop assigns 0 to myList[0], 1 to myList[1], ..., and 9 to myList[9]:  >>>for i in range(len(myList)): myList[i] = I >>>myLIst [0,1,2,3,4,5,6,7,8,9]  list1[-1] is same as list1[-1 + len(list1)], which gives the last element in the list.  list1[-3] is same as list1[-3 + len(list1)], which gives the third last element in the list. • s[i : j] Slice of sequence s from index i to j - 1., I refers to start index j to end index • negative index in slicing is also allowed • >>>list1 = [2, 3, 5, 2, 33, 21] >>>list1[-4 : -2] #prints [5,2]ASWINI C, Assistant Professor/IT, GCT 111
  • 112. Comparing List  two lists must contain the same type of elements  Uses lexicographical ordering:  the first two elements are compared, and if they differ this determines the outcome of the comparison;  if they are equal, the next two elements are compared, and so on ASWINI C, Assistant Professor/IT, GCT 112
  • 113. List methods ASWINI C, Assistant Professor/IT, GCT 113
  • 114. ASWINI C, Assistant Professor/IT, GCT 114
  • 115. ASWINI C, Assistant Professor/IT, GCT 115
  • 116. Splitting a String into a List  str class contains the split method, which is useful for splitting items in a string into a list.  items = "Jane John Peter Susan".split()  >>>items[2] #prints ‘peter’  >>>items = "09/20/2012".split("/")  >>>items[2] # prints ‘2012’ ASWINI C, Assistant Professor/IT, GCT 116
  • 117. Inputting Lists ASWINI C, Assistant Professor/IT, GCT 117
  • 118. Copying LIsts  To copy the data in one list to another list, you have to copy individual elements from the source list to the target list.  does not copy the contents of the list referenced by list1 to list2  copies the reference value from list1 to list2. After this, list1 and list2 refer to the same list,  The list previously referenced by list2 is no longer referenced; it becomes garbage.  The memory space occupied by list2 will be automatically collected and reused by the Python interpreter. ASWINI C, Assistant Professor/IT, GCT 118
  • 119. Passing Lists to Functions  When passing a list to a function, the contents of the list may change after the function call, since a list is a mutable object.  just like passing an object to a function  Last statement creates a list and passes it to the function.  There is no explicit reference variable for the list. Such a list is called an anonymous list. ASWINI C, Assistant Professor/IT, GCT 119
  • 120. passlist argument.py ASWINI C, Assistant Professor/IT, GCT 120
  • 121. DefaultlistArgument.py Default Arguments ASWINI C, Assistant Professor/IT, GCT 121
  • 122. No default Argument- ASWINI C, Assistant Professor/IT, GCT 122
  • 123. Returning a List from a Function  When a function returns a list, the list’s reference value is returned.  You can pass list arguments when invoking a function.  A function can also return a list. ASWINI C, Assistant Professor/IT, GCT 123
  • 124. MULTIDIMENSIONAL LIST ASWINI C, Assistant Professor/IT, GCT 124
  • 125.  Data in a table or a matrix can be stored in a two-dimensional list.  value in a 2D list can be accessed through a row and column index.  matrix can be accessed using matrix[i][j], where i and j are the row and column indexes. ASWINI C, Assistant Professor/IT, GCT 125
  • 126.  2D list consists of a list of 1D lists and a 3D list consists of a list of 2D lists.  create n-dimensional lists for any integer n.  For example, you can use a three- dimensional list to store exam scores for a class of six students with five exams, and each exam has two parts ASWINI C, Assistant Professor/IT, GCT 126
  • 127.  scores[0][1][0] refers to the multiple-choice score for the first student’s second exam, which is 11.0. scores[0][1][1] refers to the essay score for the first student’s second exam, which is 22.5. ASWINI C, Assistant Professor/IT, GCT 127
  • 128. ASWINI C, Assistant Professor/IT, GCT 128
  • 129. DATA STRUCTURES  Eg: No-fly list for aircraft  a tuple for storing a fixed list of elements, a set for storing and quickly accessing nonduplicate elements, and a dictionary for storing key/value pairs and for accessing elements quickly using the keys. ASWINI C, Assistant Professor/IT, GCT 129
  • 130. Tuples  Tuples are like lists, but their elements are fixed; that is, once a tuple is created,  cannot add new elements, delete elements, replace elements, or reorder the elements ◦ t1 = () # Create an empty tuple ◦ t2 = (1, 3, 5) # Create a tuple with three elements ◦ t3 = tuple([2 * x for x in range(1, 5)]) # Create a tuple from a list ◦ t4 = tuple("abac") # t4 is ['a', 'b', 'a', 'c'] # Create a tuple from a string ASWINI C, Assistant Professor/IT, GCT 130
  • 131. ASWINI C, Assistant Professor/IT, GCT 131
  • 132. Sets  Sets are like lists for storing a collection of elements.  But, elements in a set are nonduplicates and are not placed in any particular order.  can contain the elements of the same type or mixed types. For example, s {1, 2, 3, "one", "two", "three"} ◦ Each element in a set must be hashable. ◦ Each object in Python has a hash value and an object is hashable if its hash value never changes during its lifetime. ◦ All types of objects introduced so far except lists areASWINI C, Assistant Professor/IT, GCT 132
  • 133.  s1 = set() # Create an empty set  s2 = {1, 3, 5} # Create a set with three elements  s3 = set([1, 3, 5]) # Create a set from a tuple  s4 = set([x * 2 for x in range(1, 10)]) # Create a set from a list  s5 = set("abac") # s5 is {'a', 'b', 'c'} # Create a set from a string ASWINI C, Assistant Professor/IT, GCT 133
  • 134.  Manipulating and Accessing Sets  remove(e) method will throw a KeyError exception if the element to be removed is not in the set. ASWINI C, Assistant Professor/IT, GCT 134
  • 135.  Subset and Superset ASWINI C, Assistant Professor/IT, GCT 135
  • 136.  Equality Test ASWINI C, Assistant Professor/IT, GCT 136
  • 137.  Set Operations ASWINI C, Assistant Professor/IT, GCT 137
  • 138.  Comparing the Performance of Sets and Lists ◦ Sets are more efficient than lists for the in and not in operator and for the remove method. ◦ sets do not support the index operator, because the elements in a set are unordered. ◦ Sets are implemented using hash tables. ◦ add an object to a set, the position within the memory of the set object is determined using the hash of the object to be added. ◦ when searching data have to look if the object is at the position determined by its hash, so the speed of this operation does not depend on the size of the set. ◦ For lists, in contrast, the whole list needs to be searched, which will become slower as the list grows. ◦ sets do not preserve the order of the objects you add. ◦ sets aren't faster than lists in general -- membership test is faster for sets, and so is removing an element. ASWINI C, Assistant Professor/IT, GCT 138
  • 139. Dictionaries  A dictionary is a container object that stores a collection of key/value pairs.  To enable fast retrieval, deletion, and updating of the value by using the key.  keys are like an index operator, but In a list, the indexes are integers.  In a dictionary, the key must be a hashable object.  A dictionary cannot contain duplicate keys. Each key maps to one value.  A key and its corresponding value form an item (or entry) stored in a dictionary  A dictionary is also known as a map, which maps each key to a value. ASWINI C, Assistant Professor/IT, GCT 139
  • 140.  Creating a Dictionary ◦ students = {"111-34-3434":"John", "132-56-6290":"Peter"} ◦ students = {} # Create an empty dictionary  Adding, Modifying, and Retrieving Values ◦ students["234-56-9010"] = "Susan“  retrieve a value, using dictionaryName[key]. • If the key is in the dictionary, the value for the key is returned. Otherwise, a KeyError exception is raised.  del students["234-56-9010"] ASWINI C, Assistant Professor/IT, GCT 140
  • 141.  Looping  len(students) Equality Test ASWINI C, Assistant Professor/IT, GCT 141
  • 142. Dictionary Methods ASWINI C, Assistant Professor/IT, GCT 142
  • 143. Classes and Objects ASWINI C, Assistant Professor/IT, GCT 143
  • 144. Defining Classes for Objects • OOP enables to develop large-scale software and GUIs effectively. • Python automatically assigns each object a unique id for identifying the object at runtime. • An object’s state (also known as its properties or attributes) is represented by variables, called data fields. • Python uses methods to define an object’s behavior (also known as its actions). methods are defined as functions. • You make an object perform an action by invoking a method on that object. ASWINI C, Assistant Professor/IT, GCT 144
  • 145.  An object is an instance of a class, and you can create many instances of a class.  Creating an instance of a class is referred to as instantiation. ASWINI C, Assistant Professor/IT, GCT 145
  • 146. Defining Classes • class provides a special method, __init__, known as an initializer, is invoked to initialize a new object’s state when it is created. • An initializer can perform any action, but initializers are designed to perform initializing actions, such as creating an object’s data fields with initial values. • The class name is preceded by the keyword class and followed by a colon (:). • The initializer is always named __init__ (line 5), which is a special method. ASWINI C, Assistant Professor/IT, GCT 146
  • 147. ASWINI C, Assistant Professor/IT, GCT 147
  • 148. Constructing Objects  create objects from the class with a constructor, which does two things: eg:ClassName(arguments) ◦ creates an object in the memory for the class. ◦ invokes the class’s __init__ method to initialize the object.  All methods, including the initializer, have the first parameter self.  self parameter in the __init__ method is automatically set to reference the object that was just created.  can specify any name for this parameter, but by convention self is usually used.ASWINI C, Assistant Professor/IT, GCT 148
  • 149. ASWINI C, Assistant Professor/IT, GCT 149
  • 150. Accessing Members of Objects  Data fields are also called instance variables,  To access an object’s data fields and invoke an object’s methods, assign the object to a variable :  objectRefVar = ClassName(arguments)  For example, c1 = Circle(5) c2 = Circle() ASWINI C, Assistant Professor/IT, GCT 150
  • 151.  Methods are also called instance methods  Invoke methods by using the dot operator (.), als known as the object member access operator.  objectRefVar.datafield  objectRefVar.method(args) ASWINI C, Assistant Professor/IT, GCT 151
  • 152. self Parameter  self is a parameter that references the object itself.  Using self, you can access object’s members in a class definition.  For example, you can use the syntax self.x to access the instance variable x and syntax self.m1() to invoke the instance method m1 for the object self in a class, ASWINI C, Assistant Professor/IT, GCT 152
  • 153. ASWINI C, Assistant Professor/IT, GCT 153
  • 154. Hiding Data Fields  Making data fields private protects data and makes the class easy to maintain.  You can access data fields via instance variables directly from an object. ASWINI C, Assistant Professor/IT, GCT 154
  • 155.  direct access of a data field in an object is not a good practice—for two reasons: First, data may be tampered with.  ■ Second, the class becomes difficult to maintain and vulnerable to bugs. ASWINI C, Assistant Professor/IT, GCT 155
  • 156. GUI Programming Using Tkinter ASWINI C, Assistant Professor/IT, GCT 156
  • 157.  Tkinter enables you to develop GUI programs and is an excellent pedagogical tool for learning object- oriented programming.  Tkinter (pronounced T-K-Inter) is short for “Tk interface.”  Tk is a GUI library used by many programming languages for developing GUI programs on Windows, Mac, and UNIX. ASWINI C, Assistant Professor/IT, GCT 157
  • 158.  The tkinter module contains the classes for creating GUIs.  The Tk class creates a window for holding GUI widgets  The first argument of a widget class is always the parent container (i.e., the container in which the widget will be placed). ASWINI C, Assistant Professor/IT, GCT 158
  • 159. ASWINI C, Assistant Professor/IT, GCT 159
  • 160. Pack Manager  pack manager can place widgets on top of each other or place them side by side. You can  also use the fill option to make a widget fill its entire container. ASWINI C, Assistant Professor/IT, GCT 160
  • 161. ASWINI C, Assistant Professor/IT, GCT 161
  • 162.  These three labels are packed on top of each other.  The red label uses the option fill with value BOTH and expand with value 1.  The fill option uses named constants X, Y, or BOTH to fill horizontally, vertically, or both ways.  The expand option tells the pack manager to assign additional space to the widget ASWINI C, Assistant Professor/IT, GCT 162
  • 163. ASWINI C, Assistant Professor/IT, GCT 163
  • 164.  Developing a GUI application involves the major steps in writing the program:  1. Design the user interface (UI) by drawing a sketch, You can use the grid manager to position them in the window.  2. Process the event. When the button is clicked, the program invokes a callback function ASWINI C, Assistant Professor/IT, GCT 164
  • 165. ASWINI C, Assistant Professor/IT, GCT 165
  • 166. ASWINI C, Assistant Professor/IT, GCT 166
  • 167. ASWINI C, Assistant Professor/IT, GCT 167
  • 168. Geometry Managers  to place widgets inside a container.  Tkinter supports three geometry managers: ◦ grid manager- places widgets into the cells of an invisible grid in a container. use the rowspan and columnspan parameters to place a widget in multiple rows and columns, ◦ sticky option can be S, N, E, and W, or NW, NE, SW, and SE. ◦ padx and pady options pad the optional horizontal and vertical space in a cell ◦ ipadx and ipady inside the widget borders. ASWINI C, Assistant Professor/IT, GCT 168
  • 169.  pack manager ◦ pack manager can place widgets on top of each other or place them side by side. You can  also use the fill option to make a widget fill its entire container.  place manager ◦ place manager places widgets in absolute positions ASWINI C, Assistant Professor/IT, GCT 169
  • 170. ASWINI C, Assistant Professor/IT, GCT 170
  • 171.  use Tkinter to create menus, popup menus, and toolbars ASWINI C, Assistant Professor/IT, GCT 171
  • 172. FILES ASWINI C, Assistant Professor/IT, GCT 172
  • 173. Why Files?  Data used in a program is temporary; if it is not saved,  lost when the program terminates.  To permanently store save it in a file on a disk or some other permanent storage device. ASWINI C, Assistant Professor/IT, GCT 173
  • 174. Why Exception Handling?  if your program tries to read data from a file but the file does not exist?  program will be abruptly terminated.  how to write the program to handle this exception so the program can continue to execute. ASWINI C, Assistant Professor/IT, GCT 174
  • 175. Text Input and Output • To read data from or to a file, use the open function to create a file object • To write use the object’s read and write methods to read and write data. • An absolute filename contains a filename with its complete path and drive letter. Eg: /home/liang/pybook/Scores.txt, relative filename is relative to its current working directory. Eg: Scores.py ASWINI C, Assistant Professor/IT, GCT 175
  • 176. Text & Binary File • A file that can be processed using a text editor such as Notepad on Windows or vi on UNIX is called a text file. • All the other files are called binary files. • For example, Python source programs are stored in text files and can be processed by a text editor, but Microsoft Word files are stored in binary files and are processed by the Microsoft Word program. • Although it is not technically precise and correct, you can envision a text file as consisting of a sequence of characters and a binary file as consisting of a sequence of bits. ASWINI C, Assistant Professor/IT, GCT 176
  • 177. Opening a File  first create a file object that is associated with a physical file. This is called opening a file.  Syntax : fileVariable = open(filename, mode) ASWINI C, Assistant Professor/IT, GCT 177
  • 178.  in the current directory: input = open("Scores.txt", "r")  the absolute filename to open the file in Windows, as follows: input = open(r"c:pybookScores.txt", "r")  r prefix before the absolute filename specifies that the string is a raw string, which causes the  Python interpreter to treat backslash characters as literal backslashes.  Without the r prefix, have to write the statement using an escape sequence as: input = open("c:pybookScores.txt", "r")ASWINI C, Assistant Professor/IT, GCT 178
  • 179. Writing Data  open function creates a file object, which is an instance of the _io.TextIOWrapper class.  This class contains the methods for reading and writing data and for closing the file ASWINI C, Assistant Professor/IT, GCT 179
  • 180.  If the file already exists, the contents of the file will be overwritten with new data.  When a file is opened for writing or reading, a special marker called a file pointer is positioned internally in the file. ASWINI C, Assistant Professor/IT, GCT 180
  • 181.  invoke print(str), the function automatically inserts the newline character n after displaying the string.  However, the write function does not automatically insert the newline character. ASWINI C, Assistant Professor/IT, GCT 181
  • 182. Testing a File’s Existence  import os.path if os.path.isfile("Presidents.txt"): print("Presidents.txt exists") ASWINI C, Assistant Professor/IT, GCT 182
  • 183. Reading Data  the read method to read a specified number of characters or all characters from the file and return them as a string,  the readline() method to read the next line, and the readlines() method to read all the lines into a list of strings. ASWINI C, Assistant Professor/IT, GCT 183
  • 184. ASWINI C, Assistant Professor/IT, GCT 184
  • 185. ASWINI C, Assistant Professor/IT, GCT 185
  • 186. Reading All Data from a File  2 approaches  read() - read all data from the file and return it as one string.  readlines() - read all data and return it as a list of strings.  if the file is so large that its contents cannot be stored in the memory. ASWINI C, Assistant Professor/IT, GCT 186
  • 187.  loop to read one line at a time, process it, and continue reading the next line until it reaches the end of the file: ASWINI C, Assistant Professor/IT, GCT 187
  • 188. ASWINI C, Assistant Professor/IT, GCT 188
  • 189. Appending Data ASWINI C, Assistant Professor/IT, GCT 189
  • 190. Writing and Reading Numeric Data  convert them into strings and then use the write method to write them to the file.  to read the numbers back correctly, separate them with whitespace characters, such as " " or n. ASWINI C, Assistant Professor/IT, GCT 190
  • 191. ASWINI C, Assistant Professor/IT, GCT 191
  • 192. File Dialogs  tkinter.filedialog module ◦ askopenfilename ◦ Asksaveasfilename  Both functions return a filename. If cancelled by the user, the function returns None. ASWINI C, Assistant Professor/IT, GCT 192
  • 193. Exception Handling  Exception handling enables a program to deal with exceptions and continue its normal execution.  error that occurs at runtime is also called an exception. ASWINI C, Assistant Professor/IT, GCT 193
  • 194. ASWINI C, Assistant Professor/IT, GCT 194
  • 195. ASWINI C, Assistant Professor/IT, GCT 195
  • 196.  The try/except block works as follows:  ■ First, the statements in between try and except are executed.  ■ If no exception occurs ◦ except clause is skipped. And break statement is executed to exit the while loop.  If an exception occurs ◦ the rest of the clause is skipped. ◦ ■ If an exception occurs and it does not match the exception name in the except clause, the exception is passed on to the caller of this function; if no handler is found, it is an unhandled exception and execution stops with an error message displayed. ASWINI C, Assistant Professor/IT, GCT 196
  • 197. ASWINI C, Assistant Professor/IT, GCT 197
  • 198.  try statement can have more than one except clause to handle different exceptions.  try statement may have an optional ◦ else clause, which is executed if no exception is raised in the try body and ◦ finally clause, which is intended to define cleanup actions that must be performed under all circumstances. ASWINI C, Assistant Professor/IT, GCT 198
  • 199. ASWINI C, Assistant Professor/IT, GCT 199
  • 200. Raising Exceptions  Exceptions are wrapped in objects, and objects are created from classes.  An exception is raised from a function. ◦ raise ExceptionClass("Something is wrong")  ex = RuntimeError("Wrong argument")  raise ex ASWINI C, Assistant Professor/IT, GCT 200
  • 201.  enables a function to throw an exception to its caller.  Without this capability, the called function itself must handle the exception or terminate the program.  Here, library function can detect the error, but only the caller knows what needs to be done when an error occurs.  to separate the detection of an error (done in a called function) from the handling of an error (done in the calling method). ASWINI C, Assistant Professor/IT, GCT 201
  • 202. ASWINI C, Assistant Professor/IT, GCT 202
  • 203. Processing Exceptions Using Exception Objects  You can access an exception object in the except clause. ASWINI C, Assistant Professor/IT, GCT 203
  • 204. Defining Custom Exception Classes  define a custom exception class by extending BaseException or a subclass of BaseException.  The order in which exceptions are specified in except blocks is important, because Python finds a handler in this order.  If an except block for a superclass type appears before an except block for a subclass type, the except block for the subclass type will never be  executed. ASWINI C, Assistant Professor/IT, GCT 204
  • 205.  Thus, it would be wrong to write the code as follows: ASWINI C, Assistant Professor/IT, GCT 205
  • 206. References: 1. Y. Daniel Liang “Introduction to Programming Using Python” ,Pearson, 2013 2.Charles Dierbach ,”Introduction to Computer Science Using Python: A Computational Problem-Solving Focus”, Wiley Publications, 2012. ASWINI C, Assistant Professor/IT, GCT 206
  • 207. THANK YOU ASWINI C, Assistant Professor/IT, GCT 207
  • 208. ASWINI C, Assistant Professor/IT, GCT 208