0% found this document useful (0 votes)
6 views

SDF-Week13

Uploaded by

Douae Charafi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

SDF-Week13

Uploaded by

Douae Charafi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

11/28/23

Software Development Fundamentals


Week 13
Fall 2023
Dr. Loubna Mekouar

Note:
• Some of the slides of the course are based on the material provided
by the College of Technological Information, Zayed University, UAE.
• The copyrighted material belongs to their respective owners.

1
11/28/23

Topics of Discussion
• Functions
• Types of Functions
• Built-in functions
• User-defined functions

Functions
Modular Programs

2
11/28/23

Functions
• A Function is a group of related statements
that perform a single specific task.

• Functions help break our program into smaller


modular chunks.

• As our program grows larger and larger,


functions make it more organized and
manageable.

• It avoids repetition and makes code reusable.

Functions
• f(x) = 15x2 + 4x + 2
• f(3) gives 149

• In the above function:


• f is the name of the function, or function name
• The function does one specific task, (in this case it solves the expression)
• Every time f is called, it does the same thing, i.e. every time the particular
expression has to be evaluated, we just call f. The function is Reusable.
• Here, when we called f we passed a value 3 to the function f, the value is
called the ‘actual parameter’
• The actual parameter 3 is passed to x, and x is called the ‘formal parameter’
• The result of calling f with the actual parameter 3 is 149. The value 149 is the
‘return value’ of the function f and the returned value is of type int.
6

3
11/28/23

Types of Functions
We can divide functions into the following two types:

• Built-in functions -
• Functions that are built into Python.

• User-defined functions -
• Functions defined by the users themselves.

Python Built-in Function


• Python has a number of functions • Example:
that are always available for use.
testList = [1, 2, 3]
These functions are called built-in
functions. print(testList)

• For example: • Output


• print(): Prints the given object to the screen
[1, 2, 3]
• input():Reads and returns a line of string
• len(): Returns length of an Object
• pow(x,y): Returns x to the power of y

4
11/28/23

User-defined Functions
•Functions defined by the users themselves.

•For example:
• A function to find an even number
• isEven()
• A function to find the greatest of 3 numbers
• greatestOfThree()

Syntax of a Python Function


Keyword def marks def function_name (parameters):
the start of function """docstring""" A colon (:) to
header. statement(s) mark the end
return [expression_list] of function
A function_name to header.
uniquely identify it.

Optional documentation Formal Parameters through


string (docstring) to describe which values are passed to
what the function does. a function. (Optional)

Valid python statements that make up


An optional return statement
the function body. All statements must
to return a value from the
have same indentation level (4 spaces).
function. 10

10

5
11/28/23

Example of a function
# Name: greet
# Desc: This Function greets a person
# Parameters: name - string
# Return: None

# Define the function


def greet(name):
print("Hello, " + name + ". Good morning!")

# Call the function


greet(“Amna”)

11

11

Function Call
• Once we have defined a • Function call:
function, we can call it from: greet(“Amna”)
• Another function
• The program
• The Python prompt
• Output
• To call a function: Hello, Amna. Good morning!
• type the function name with
appropriate parameters.

12

12

6
11/28/23

Function Arguments
• A function can have one or more arguments.

# Example Function with 2 arguments


def greet(name, msg):
print("Hello", name + ', ' + msg)

• In the above function, name & msg are the formal arguments
# Function Call
greet("Mariam", "Good morning!")

• Output
Hello Mariam, Good morning!

13

13

Class Work
# Name: sumThreeNums
# Desc: Add 3 numbers
# Parameters: num1 - int, num2 - int, num3 - int
# Return: int

def sumThreeNums(num1, num2, num3):


return num1+num2+num3

# Function Call
print(sumThreeNums(4, 5, 6))
14

14

7
11/28/23

The return statement


• return [expression_list]
• A function will always return a value

• This statement can contain an expression which gets


evaluated and the value is returned.

• If there is no expression in the statement or if there is


no return statement inside a function, then the function will
return the None object.

• The return statement is used to exit a function and return to


the place from where it was called.
15

15

Class Work
# Name: absVal
# Desc: Returns Absolute Value
# Parameters: num - int
# Return: int

def absVal(num):
if num >= 0:
return num
else:
return –num

# Function Call
print(absVal(-5))
print(absVal(-100))
print(absVal(-15))
16

16

8
11/28/23

Class Work
# Name: greatestOfThree
# Desc: Finds greatest of 3 numbers
# Parameters: num1 - int, num2 - int, num3 - int
# Return: int

def greatestOfThree (num1, num2, num3):


if num1>num2>num3:
return num1
elif num2>num3:
return num2
else:
return num3

# Function Call
print(greatestOfThree(4, 5, 6))
print(greatestOfThree(6, 4, 5))
17

17

Class Work
# Name: greatestOfThree
# Desc: Finds greatest of 3 numbers
# Parameters: num1 - int, num2 - int, num3 - int
# Return: int

def greatestOfThree (num1, num2, num3):


if (num1>num2) and (num1>num3):
return num1
elif num2>num3:
return num2
else:
return num3

# Function Call
print(greatestOfThree(6, 4, 5))

18

18

9
11/28/23

Class Work
# Name: isEven # Function Call
# Desc: Finds Even or Not n = int(input("Enter a number: "))
# Parameters: num - int
# Return: Boolean if isEven(n):
print(n, " is even")
else:
def isEven(num): print(n, " is not even")
if num%2 == 0:
return True
else:
return False

19

19

Class Work
• Write a python function sumN() def sumN(n)
that takes an integer N as # Write Loop to add numbers from 1 to n
parameter and returns the sum
of all numbers from 1 to N.

# Function Call
# Name: sumN
result = sumN(10)
# Desc: Adds numbers 1 to n
# Parameters: n - int print(“ The sum of first N nums: “, result)
# Return: int

20

20

10
11/28/23

Scope and Lifetime of Variables


• Scope of a variable is the portion of
a program where the variable is
recognized. # Scope of Variables
• Parameters and variables defined num = 10
inside a function are not visible from
outside. Hence, they have a local at i s th e
scope.
def test(): Wh p u t ?
• Lifetime of a variable:
num = 5 Out
• The period throughout which the print (num)
variable exits in the memory.
• The lifetime of variables inside a test()
s th e
function is as long as the function
executes. print(num) at i
• Variables are destroyed once we return Wh p u t ?
Out
from the function. Hence, a function
does not remember the value of a
variable from its previous calls.

21

21

Class Work
Question 1:
Write a program with a method named
getTotal that accepts two integers as an
argument and return its sum. Call this
method and print the results.

Question 2:
Write a function, reverseDigit, that
takes an integer as a parameter and
returns the number with its digits
reversed. For example, the value of
reverseDigit(12345) is 54321. Also, write
a program to test your method.

22

22

11
11/28/23

Class Work
• Write program that acts as simple # Hints
calculator. def add(x, y):
return()
def subtract(x, y):
• Consider calculation for simple
math operations ( + - * /). return()
def multiply(x, y):
return()
• Write the functions with good def divide(x, y):
documentation return()

• Call the functions to test with


different test cases that could be
erroneous like values with type
conflict.
23

23

Class Work
Write a function dot_product(List1,List2) that takes two Lists of numbers of
the same length. The function returns the sum of the products of the
corresponding elements of each list.

# Function Call
dot_product([1, 2], [1, 4]) # Output: 9

# Dot Product of the above list is calculated as


# (1x1 + 2x4 = 9)

24

24

12
11/28/23

Loop - Factorial of a Number

25

25

Recursion

• Recursion is the process of defining something in terms of itself.

26

26

13
11/28/23

Recursion

27

27

Recursion

28

28

14
11/28/23

Recursion: Advantages & Disadvantages


Advantages
1.Recursive functions make the code look clean and elegant.
2.A complex task can be broken down into simpler sub-problems using
recursion.
3.Sequence generation is easier with recursion than using some nested
iteration.

Disadvantages
1.Sometimes the logic behind recursion is hard to follow through.
2.Recursive calls are expensive (inefficient) as they take up a lot of memory and
time.
3.Recursive functions are hard to debug.

29

29

Summary

-Functions

-Types of Functions
• Built-in functions
• User-defined functions
- Check the following link:
https://www.programiz.com/python-programming/examples

30

30

15

You might also like