You are on page 1of 42

Logic & Algorithm

Lec02a – function in python


Multiple-line Snippets and Functions

• So far, we have been using only one-line snippets in the interactive


mode, but we may want to go beyond that and execute an entire
sequence of statements

• Python allows putting a sequence of statements together to create a


brand-new command or function
>>> def hello():
These indentations are necessary to ...     print("Hello")
indicate that these two statements ...     print("Programming is fun!")
belong to the same block of code, ... 
which belongs to this function >>>
Indentations Are Mandatory

• If indentations are not provided, an error will be generated

>>> def hello():


... print("Hello")
  File "<stdin>", line 2
    print("Hello")
    ^
IndentationError: expected an indented block
>>> 
Invoking Functions

• After defining a function, we can call (or invoke) it by typing its name
followed by parentheses

>>> def hello():


This is how we invoke our
...     print("Hello")
defined function hello(); ...     print("Programming is fun!")
notice that the two print ... 
statements (which form one >>> hello()
code block) were executed Hello
in sequence! Programming is fun!
>>>
Invoking Functions

• Invoking a function without parentheses will NOT generate an error,


but rather the location (address) in computer memory where the
function definition has been stored

>>> def hello():


...     print("Hello")
...     print("Programming is fun!")
... 
>>> hello
<function hello at 0x101f1e268>
>>> 
Parameters

• We can also add parameters (or arguments) to our defined functions

person is a parameter; >>> def hello(person):


it acts as an input to the ...     print("Hello " + person)
function hello(…) ...     print("Programming is fun!")
... 
>>> hello("Mohammad")
Hello Mohammad
Programming is fun!
>>> 
Multiple Parameters

• We can add multiple parameters and not only one

>>> def hello(person, course):


...     print("Hello " + person + “ from “ + course)
...     print("Programming is fun!")
... 
>>> hello("Mohammad“, “15-110”)
Hello Mohammad from 15-110
Programming is fun!
>>> 
Parameters with Default Values

• In addition, parameters can be assigned default values


def print_func(i, j = 100): def print_func(i, j = 100): def print_func(i, j = 100):
        print(i, j)         print(i, j)         print(i, j)

print_func(10, 20) print_func(10) print_func()


Run

Run

Run
10 10 100 ERROR
20
Modularity and Maintenance

• Consider the following code def happy():


        print("Happy birthday to you!")
print("Happy birthday to you!")
print("Happy birthday to you!") def singFred():
print("Happy birthday, dear Fred")         happy()
print("Happy birthday to you!")         happy()
        print("Happy birthday, dear Fred")
Can we write this program with
        happy()
ONLY two prints?
singFred()

More modular & maintainable– changing anything in the lyric “Happy birthday to you!”
requires making a change at only one place in happy(); thanks to the happy function!
Extensibility and Readability

• Consider the following code


print("Happy birthday to you!")
print("Happy birthday to you!") print("Happy birthday to you!")
print("Happy birthday to you!") print("Happy birthday, dear Fred")
print("Happy birthday, dear Fred") print("Happy birthday to you!")
print("Happy birthday to you!") print("Happy birthday to you!")
print("Happy birthday to you!")
What if we want to sing a verse for print("Happy birthday, dear Lucy")
Lucy right after Fred? print("Happy birthday to you!")

What if we utilize functions?


Extensibility and Readability

• Consider the following code


def happy():
        print("Happy birthday to you!")
print("Happy birthday to you!")
print("Happy birthday to you!")
print("Happy birthday, dear Fred") def sing(name):
        happy()
print("Happy birthday to you!")
        happy()
        print("Happy birthday, dear " + name)
What if we want to sing a verse for
        happy()
Lucy right after Fred?
sing("Fred")
sing("Lucy")

Easy to extend, more readable, and necessitates less typing!


Formal Definition of Functions

• Formally, a function can be defined as follows:


def <name>(<formal-parameters>):
<body>
• The <name> of a function should be an identifier and <formal-parameters> is
a (possibly empty) list of variable names (also identifiers)

• <formal-parameters> and all local variables declared in a function are only


accessible in the <body> of this function

• Variables with identical names declared elsewhere in a program are distinct


from <formal-parameters> and local variables inside a function’s <body>
Local Variables

• Consider the following code

def func1(x, y):


#local scope 234
    z=4 Traceback (most recent call last):
        print(x, y, z) Run   File "func1.py", line 6, in <module>
    print(x, y, z)
func1(2, 3) NameError: name 'x' is not defined
print(x, y, z)

x, y, and z belong solely to the scope of func1(...) and can only be accessed inside
func1(…); z is said to be local to func1(…), hence, referred to as a local variable
Global Variables

• Consider the following code


#global scope
x = 100
  
def func2(): 100
Run
        print(x) 100

func2()
print(x)

x is said to be a global variable since it is defined within the global scope of the
program and can be, subsequently, accessed inside and outside func2()
Local vs. Global Variables

• Consider the following code

x = 100
  
def func3():
        x = 20 20
Run
        print(x) 100

func3()
print(x)

The global variable x is distinct from the local variable x inside func3()
Parameters vs. Global Variables

• Consider the following code

x = 100
  
def func4(x):
        print(x) 20
Run
100
func4(20)
print(x)

The global variable x is distinct from the parameter x of func4(…)


The global Keyword

• Consider the following code

def func5():
        global x
        x = 20
        print(x) 20
Run
20
func5()
print(x)

The global keyword binds variable x in the global scope; hence, can be accessed inside
and outside func5()
Getting Results From Functions

• We can get information from a function by having it return a value

>>> def square(x): >>> def cube(x): >>> def power(a, b):
...     return x * x ...     return x * x * x ...     return a ** b
...  ...  ... 
>>> square(3) >>> cube(3) >>> power(2, 3)
9 27 8
>>>  >>>  >>> 
Pass By Value

• Consider the following code


>>> def addInterest(balance, rate):
...     newBalance = balance * (1+rate)
...     return newBalance
... 
>>> def test():
...     amount = 1000
...     rate = 0.05
...     nb = addInterest(amount, rate)
...     print(nb)
... 
>>> test()
1050.0
>>> 
Pass By Value

• Is there a way for a function to communicate back its result without


returning it?
>>> def addInterest(balance, rate):
...     newBalance = balance * rate
...     balance = newBalance
... 
>>> def test():
...     amount = 1000
...     rate = 0.05
...     addInterest(amount, rate)
What will be the result? ...     print(amount)
... 
>>> test()
1000
>>> 
Pass By Value

• Is there a way for a function to communicate back its result without


returning it?
>>> def addInterest(balance, rate):
...     newBalance = balance * rate
...     balance = newBalance
... 
>>> def test():
...     amount = 1000
...     rate = 0.05
Why 1000 and NOT ...     addInterest(amount, rate)
...     print(amount)
1050.0? ... 
>>> test()
1000
>>> 
Pass By Value

• The function only receives the values of the parameters


1000
addInterest(…) gets >>> def addInterest(balance, rate):
...     newBalance = balance * rate
ONLY the value of
...     balance = newBalance
amount (i.e., 1000) ... 
>>> def test(): Python is said to
...     amount = 1000 pass parameters
...     rate = 0.05
...     addInterest(amount, rate) by value!
...     print(amount)
... 
>>> test()
1000
>>> 
Pass By Value vs. Returning a Value

• Consider the following code


def increment_func(x):
def increment_func(x):     x=x+1
    x=x+1         return x

x=1 x=1
increment_func(x) x = increment_func(x)
print(x) print(x)
Run

Run
1 2
More on the Print Function

• There are different forms of the print function


1) print(), which produces a blank line of output

>>> print()

>>> 
More on the Print Function

• There are different forms of the print function


2) print(<expr>, <expr>, …, <expr>), which indicates that the print function can
take a sequence of expressions, separated by commas

>>> print(3+4)
7
>>> print(3, 4, 3+4)
347
>>> print("The answer is ", 3 + 4)
The answer is  7
>>> print("The answer is", 3 + 4)
The answer is 7
More on the Print Function

• There are different forms of the print function


3) print(<expr>, <expr>, …, <expr>, end = “\n”), which indicates that the print
function can be modified to have an ending text other than the default one
(i.e., \n or a new line) after all the supplied expressions are printed

>>> def answer():


Notice how we used the end ...     print("The answer is:", end = " ")
parameter to allow multiple ...     print(3 + 4)
prints to build up a single line ... 
>>> answer()
of output!
The answer is: 7
>>> 
The Software Development Process

• Writing programs requires a systematic approach to problem solving,


which incorporates 7 major steps
1) Problem analysis, which involves studying deeply the problem at hand

2) Program specification, which involves deciding exactly “what” (NOT


“how”) your program will do
• What is the input?
• What is the output?
• What is the relationship between the input and the output?

3) Design, which involves writing an algorithm in pseudocode


• This is where the “how” of the program gets worked out
The Software Development Process

• Writing programs requires a systematic approach to problem solving,


which incorporates 7 major steps
4) Implementation, which involves translating your pseudocode into code
(e.g., using Python)

5) Debugging, which involves finding and fixing errors (or what are often
referred to as bugs) in your program
• Bugs can be of two types, syntax and semantic (or logical) bugs

6) Testing, which involves trying your program with an extensive set of


test cases so as to verify that it works correctly
The Software Development Process

• Writing programs requires a systematic approach to problem solving,


which incorporates 7 major steps
7) Maintenance, which involves keeping your program up-to-date with
technology and the evolving needs of your users
• Most programs are never really finished!
Example

• Problem: Write a program that translates temperatures from degrees


Celsius to Fahrenheit

• Solution:
1) Problem Analysis:
• Pretty clear; some people do not understand temperatures in Celsius;
there is a mathematical formula to convert Celsius to Fahrenheit

2) Program Specification:
• Input: temperature in degrees Celsius (say, C)
• Output: temperature in degrees Fahrenheit (say, F)
Example

• Solution:
2) Program Specification:
• Relationship between input and output:
• We can do some quick figuring, after which we will realize that 0 Celsius
is equal to 32 Fahrenheit and 100 Celsius is equal to 212 Fahrenheit

• With this information, we can compute the ratio of Fahrenheit to


Celsius; I.e., (212 – 32)/(100 - 0) = 9/5

• The conversion formula will then have the form F = 9/5C + k


• Plugging in 0 and 32 for C and F, we can immediately see that k = 32
• Thus, the final formula will be F = 9/5C + 32
Example

• Solution:
3) Design:
• Pseudocode:

Input: C
Calculate F as (9/5) * C + 32
Output: F
Example

• Solution:
4) Implementation:
• Python Code:

def main():
celsius = eval(input("What is the Celsius temperature? "))
fahrenheit = 9/5 * celsius + 32
print("The temperature is", fahrenheit, "degrees Fahrenheit")

main()

Let us run, debug, and test this code together!


Using the Math Library

•  Python provides many useful mathematical functions in a special


math library that we can leverage in our programs
• A library is just a module that contains some useful definitions

• Let us illustrate the use of this math library via computing the roots
of a quadratic equation with the form

• Such an equation has two solutions:


Using the Math Library: An Example

#The following line will make the math library in Python available for us.
import math

def rootsQEq():
print("This program finds the real solutions to a quadratic.")
print()

a = eval(input("Enter the value of coefficient a: "))


b = eval(input("Enter the value of coefficient b: "))
c = eval(input("Enter the value of coefficient c: "))
Using the Math Library: An Example

#To call a function from the math library, we can use the
#dot operator as follows:
s_root_val = math.sqrt(b*b - 4 * a * c)
root1 = (-b + s_root_val)/(2*a)
root2 = (-b - s_root_val)/(2*a)

print()
print("The solutions are: ", root1, root2)

#Call the function rootsQEq()


rootsQEq()
Using the Math Library: An Example

• One sample run:


This program finds the real solutions to a quadratic.

Enter the value of coefficient a: 3


Enter the value of coefficient b: 4
Enter the value of coefficient c: -2

The solutions are: 0.38742588672279316 -1.7207592200561266


Using the Math Library: An Example

• Another sample run:


This program finds the real solutions to a quadratic.

Enter the value of coefficient a: 1 What is the


Enter the value of coefficient b: 2 problem?
Enter the value of coefficient c: 3
Traceback (most recent call last):
File "/Users/mhhammou/Desktop/CMU-Q/Courses/15-
110/Programs/Lecture4/RootsQE.py", line 22, in <module> rootsQEq()
File "/Users/mhhammou/Desktop/CMU-Q/Courses/15-
110/Programs/Lecture4/RootsQE.py", line 14, in rootsQEq
s_root_val = math.sqrt(b*b - 4 * a * c)
ValueError: math domain error
Using the Math Library: An Example

•  The problem is that


• The sqrt function is unable to compute the square root of a
negative number

• Next, we will learn some tools that allow us to fix this problem

• In general, if your program requires a common mathematical


function, the math library is the first place to look at
Some Functions in the Math Library

Python Mathematics English


pi An approximation of pi
e e An approximation of e
sqrt(x) The square root of x
sin(x) sin x The sine of x
cos(x) cos x The cosine of x
tan(x) tan x The tangent of x
asin(x) arcsin x The inverse of sin x
acos(x) arccos x The inverse of cos x
atan(x) arctan x The inverse of tangent x
Some Functions in the Math Library

Python Mathematics English


log(x) ln x The natural (base e) logarithm of x
log10(x) Log10 x The common (base 10) logarithm
of x
exp(x) Ex The exponential of x
ceil(x) The smallest whole number >= x
floor(x) The largest whole number <= x
Logic & Algorithm
Lec02a – function in python

You might also like