ESD - PythonModule-II
ESD - PythonModule-II
(‘val’ is the variable that takes the value of the item inside
the sequence on each iteration. Loop continues till last
item in the sequence. The body of for loop is separated
from the rest of the code using indentation.)
Python for loop
• Flowchart
Exercise
• Program to find the sum of all elements in a list
• List of numbers = [6, 5, 3, 8, 4,2,5,4, 11]
• Expected output
Python range () function
• generates a sequence of numbers
• range(10) : generate numbers from 0 to 9 (10
numbers)
• range(start, stop, stepsize)
• Default Step size - 1
• Does not store all the values in memory
• remembers the start, stop, step size and generates
the next number on the go
Exercise
• Example
Exercise
• Program to iterate a list using indexing
• Expected output:
Exercise
• Python for with else
• Expected output
Python break and continue
• can alter the flow of a normal loop
• Can be used when we wish to terminate the current
iteration or even the whole loop without checking
test expression
Python break statement
• Terminates the loop containing it
• Control of the program flows to the statement
immediately after the body of the loop.
• If break statement is inside a nested loop (loop
inside another loop), break will terminate the
innermost loop
• Syntax
Python break statement
• Flowchart
Python break statement
• Example
Python break statement
• Output
Python continue statement
• used to skip the rest of the code inside a loop
for the current iteration only
• Loop does not terminate but continues on with
the next iteration
• Syntax
Python continue statement
• Flowchart
Exercise
• Use of Python break statement
• Use of Python continue statement
Predict the output ……
What should be the value of the
variables num1 and num2 in the code
below if the output expected is 4?
Assignment-3
• Python program to print Even Numbers in given
range
• Expected Output
Enter the start of range: 4
Enter the end of range: 10
4 6 8 10
Python Data Structures
• Lists
• Tuples
• Sets
• Dictionaries
Lists
• An ordered group of items
• Does not need to be the same type
• Could put numbers, strings or donkeys in the same list
• List notation
• A = [1,”This is a list”, c, Donkey(“kong”)]
Methods of Lists
• List.append(x)
• adds an item to the end of the list
• List.extend(L)
• Extend the list by appending all in the given list L
• List.insert(I,x)
• Inserts an item at index I
• List.remove(x)
• Removes the first item from the list whose value is x
Tuples
• Tuple
• A number of values separated by commas
• Immutable
• Cannot assign values to individual items of a tuple
• However tuples can contain mutable objects such as lists
• Single items must be defined using a comma
• Singleton = ‘hello’,
Sets
• An unordered collection with no duplicate
elements
• Basket = [‘apple’, ‘orange’, ‘apple’, ‘pear’]
• Fruit = set(basket)
• Fruit
• Set([‘orange’, ‘apple’, ‘pear’])
Dictionaries
• Indexed by keys
• This can be any immutable type (strings, numbers…)
• Tuples can be used if they contain only immutable
objects
Exercise
• Write a python program to demonstrate
• List
• Sets
• Tuples
Functions
Functions
Stored (and reused) Steps
def thing():
print ‘Zip' print 'Hello’
Output:
print 'Fun’
Hello
hello() thing() Fun
print 'Zip’ Zip
thing() Hello
print “Zip” Fun
hello()
We call these reusable pieces of code “functions”.
Python Functions
• There are two kinds of functions in Python.
• Built-in functions that are provided as part of Python -
raw_input(), type(), float(), int() ...
• Functions that we define ourselves and then use
• We treat the built-in function names as "new"
reserved words (i.e. we avoid them as variable
names)
Function Definition
• In Python a function is some reusable code that
takes arguments(s) as input does some
computation and then returns a result or results
• define a function using the def reserved word
• call/invoke the function by using the function
name, parenthesis and arguments in an
expression
Max Function
“Hello world”
(a string)
max() ‘w’
(a string)
function
Building our Own Functions
def print_lyrics():
print "I'm jack, and I'm okay.”
print 'I sleep all night and I work all day.'
Definitions and Uses
• Once we have defined a function, we can call (or
invoke) it as many times as we like
• This is the store and reuse pattern
Exercise
my_pets = [‘tommy',’sammy',’scru',‘ka']
uppered_pets = []
for pet in my_pets:
pet_ = pet.upper()
uppered_pets.append(pet_)
print(uppered_pets)
Map
Example
my_pets =[‘tommy',’sammy',’scru',‘ka']
uppered_pets = list(map(str.upper,
my_pets))
print(uppered_pets)
Map Example
• Apply mod 5 to all the elements in the list
• Input [0, 4, 7, 2, 1, 0 , 9 , 3, 5,
6, 8, 0, 3]
• Expected Output: [0, 4, 2, 2, 1, 0, 4,
3, 0, 1, 3, 0, 3]
Assignment - 5
Goal: given a list of three dimensional points in the form of tuples, create
a new list consisting of the distances of each point from the origin
Loop Method:
- distance(x, y, z) = sqrt(x**2 + y**2 + z**2)
- loop through the list and add results to a new list
Filter
• filter(function, iterable)
• The filter runs through each element of iterable (any
iterable object such as a List or another collection)
• It applies function to each element of iterable
• If function returns True for that element then the
element is put into a List
• This list is returned from filter in versions of python
under 3
• In python 3, filter returns an iterator which must be cast
to type list with list()
Filter out those who passed with scores more
than 75...using filter.
scores = [66, 90, 68, 59, 76, 60, 88, 74, 81, 65]
def is_A_student(score):
return score > 75
over_75 = list(filter(is_A_student, scores))
print(over_75)
Exercise
• Find the elements in the list which are not equal to
zero.
• Input: nums = [0, 4, 7, 2, 1, 0 , 9 ,
3, 5, 6, 8, 0, 3]
• Expected Output: [4, 7, 2, 1, 9, 3, 5,
6, 8, 3]
Assignment - 6
NaN = float("nan")
scores = [[NaN, 12, .5, 78, math.pi],
[2, 13, .5, .7, math.pi / 2],
[2, NaN, .5, 78, math.pi],
[2, 14, .5, 39, 1 - math.pi]]
reduce(function, iterable[,initializer])