Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 77

Python-Module-II

Decision Making & Function


Aaditya Desai
Prachi Janrao
Tahera Shaikh
Topics covered
• Control Structures
• if statement
• if...else Statement
• if...elif...else Statement
• Nested if statements
• While loop
• For loop
• Break-continue statement
• Function
• Filter, Map and reduce
Indentation in Python
• Python uses offside rule notation for coding
• Uses indentation for blocks, instead of curly
brackets
• The delimiter followed in python is colon(:) and
indented space or tabs
Python if Statement
• Syntax
Python if Statement
• Flowchart
Exercise
• If the number is positive, we print an appropriate
message
• Expected output
Python if...else
• Syntax
Python if...else
• Flowchart
Exercise
• Write a python program to check if the number is
positive or negative and displays an appropriate
message.
• Expected Output:
Python if...elif...else
• Syntax
Python if...elif...else
• Flowchart
Exercise
• Write a python program to check if the number is
positive or negative or zero and displays an
appropriate message.
• Expected Output:
Exercise
What is the output of the code???
num1=100
num2=200
num3=6
if(5>=num3):
if(num1>100 or num2>150):
print("1")
elif(num1>=100 and num2>150):
print("2") •1
else: print("3") •2
•3
Assignment-1
• Find the largest of the given set of elements
• For input 6, 9, 2
• Expected out
• The largest number is 9.
Python nested if Exercise
• Write a python program to check if the number is
positive or negative or zero and displays an
appropriate message. This time we use nested if
• Expected Output:
Python while loop
• used to iterate over a block of code as long as the
test expression (condition) is true
• used when we don't know beforehand, the
number of times to iterate
Python while loop
• Syntax

(Python interprets any non-zero value as True. None and 0 are


interpreted as False.)
Python while loop
• Flowchart
Exercise
• Write a python program to add natural numbers
sum = 1+2+3….
• Expected Output:
Exercise
• Python program to illustrate the use of else
statement with while loop
• Expected Output:
Assigngment-2
• Write a Python program to get the Fibonacci series between
0 to 50.
• Note : The Fibonacci Sequence is the series of numbers :
0, 1, 1, 2, 3, 5, 8, 13, 21, ....
Every next number is found by adding up the two numbers
before it.
Expected Output
1
1
2
3
5
8
13
21
34
Python for loop
• used to iterate over a sequence (list, tuple, string) or
other iterable objects
• Iterating over a sequence- traversal
• Syntax

(‘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 hello(): Program:

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

>>> big = max('Hello world') A function is some stored code


>>> print big'w' that we use. A function takes
some input and produces an
output.

“Hello world”
(a string)
max() ‘w’
(a string)
function
Building our Own Functions

• We create a new function using the def keyword


followed by optional parameters in parenthesis.
• We indent the body of the function
• This defines the function but does not execute the
body of the function

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

• Python program to demonstrate the user defined


function to print Hello world
Arguments
• An argument is a value we pass into the function
as its input when we call the function
• We use arguments so we can direct the function
to do different kinds of work when we call it at
different times
• We put the arguments in parenthesis after the
name of the function

big = max('Hello world')


Argument
Parameters
• A parameter is a variable >>> def greet(lang):
which we use in the ... if lang == 'es':
function definition that is a ... print 'Hola’
... elif lang == 'fr':
“handle” that allows the ... print 'Bonjour’
code in the function to ... else:
access the arguments for a ... print 'Hello’
particular function ...
>>> greet('en')Hello
invocation. >>> greet('es')Hola
>>> greet('fr')Bonjour
>>>
Return Values
• Often a function will take its arguments, do some
computation and return a value to be used as the
value of the function call in the calling expression.
The return keyword is used for this.

def greet(): Hello


return "Hello”
Glenn
print greet(), "Glenn” Hello
print greet(), "Sally" Sally
Return Value
>>> def greet(lang):
• A “fruitful” function ... if lang == 'es':
is one that produces ... return 'Hola’
a result (or return ... elif lang == 'fr':
value) ... return 'Bonjour’
• The return ... else:
statement ends the ... return 'Hello’
function execution ... >>> print greet('en'),'Glenn’
and “sends back” Hello Glenn
the result of the >>> print greet('es'),'Sally’
function
Hola Sally
>>> print greet('fr'),'Michael’
Bonjour Michael
>>>
Multiple Parameters / Arguments

• We can define more


than one parameter
in the function
definition def addtwo(a, b):
added = a + b
• We simply add return added
more arguments x = addtwo(3, 5)
when we call the print x
function
• We match the
number and order
of arguments and
parameters
To function or not to function...
• Organize your code into “paragraphs” - capture a
complete thought and “name it”
• Don’t repeat - make it work once and then reuse
it
• If something gets too long or complex, break up
logical chunks and put those chunks in functions
• Make a library of common stuff that you do over
and over
Assignment-4
• Write a Python function that takes a number as a
parameter and check the number is prime or not.
• Expected output:
• Input 5
• Output : It is a prime number
Higher Order Functions
Higher-Order Functions

• A function that takes another function as a


parameter
• They are “higher-order” because it’s a function of a
function
• Examples
–Map
–Reduce
–Filter
• Lambda works great as a parameter to higher-order
functions if you can deal with its limitations
Map

map(function, iterable, ...)

• Map applies function to each element of iterable


and creates a list of the results
• can optionally provide more iterables as parameters
to map and it will place tuples in the result list
• Map returns an iterator which can be cast to list
Map
Example

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]]

Goal: given a list of lists containing answers to an


algebra exam, filter out those that did not submit a
response for one of the questions, denoted by NaN
Reduce

reduce(function, iterable[,initializer])

• Reduce will apply function to each element in iterable along


with the sum so far and create a cumulative sum of the
results
• function must take two parameters
• If initializer is provided, initializer will stand as the first
argument in the sum
• Unfortunately in python 3 reduce() requires an import
statement
• from functools import reduce
Exercise
• Input: nums = [1, 2, 3, 4, 5, 6, 7,
8]
• Expected Output: (((((((1, 2), 3), 4),
5), 6), 7), 8)
Assignment - 7

Goal: given a list of numbers I want to find the average of those


numbers in a few lines using reduce()

For Loop Method:


- sum up every element of the list
- divide the sum by the length of the list
Thank You !

You might also like