Lecture02 Spring2024
Lecture02 Spring2024
FIN-460, Spring-2024
ADNAN HAIDER
User-Defined Functions
in Python
Defining Functions
Function definition begins with “def.” Function name and its arguments.
def get_final_answer(filename):
“““Documentation String”””
line1
line2 Colon.
return total_counter
Invoking Functions
• After defining a function, we can call (or invoke) it by typing its name
followed by parentheses
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
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(“Adnan")
Parameters in Python are Call by Assignment Hello Adnan
Old values for the variables that are parameter
Programming is fun!
names are hidden, and these variables are
simply made to refer to the new values >>>
All assignment in Python, including binding
function parameters, uses reference semantics.
Multiple Parameters
• We can add multiple parameters and not only one
Example 1:
>>> def hello(person, course):
... print("Hello " + person + “ from “ + course) Example 2:
... print("Programming is fun!") >>> def myfun(x, y):
... return x * y
>>> myfun(3, 4)
>>> hello(“Adnan“, “15-110”)
Hello Adnan from 15-110
Programming is fun! 12
>>>
Run
Run
10 20 10 100 ERROR
Keyword Arguments
• Can call a function with some/all of its arguments out of order as long as
you specify their names
>>> def foo(x,y,z): return(2*x,4*y,8*z)
>>> foo(2,3,4)
(4, 12, 32)
>>> foo(z=4, y=2, x=3)
(6, 8, 32)
>>> foo(-2, z=-4, y=-3)
(-4, -12, -32)
• Can be combined with defaults, too
>>> def foo(x=1,y=2,z=3): return(2*x,4*y,8*z)
>>> foo()
(2, 8, 24)
>>> foo(z=100)
(2, 8, 800)
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
>>> applier(square, 7)
49
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
• All functions in Python have a return value, even if no return line inside
the code
• Functions without a return return the special value None
• None is a special constant in the language
• None is used like NULL, void, or nil in other languages
• None is also logically equivalent to False
• The interpreter’s REPL doesn’t print None
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!
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
Local Variables
• Consider the following code
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
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
Global Variables
• Consider the following code
#global scope
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()
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()
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
x = 100
def func4(x):
print(x) 20
Run
100
func4(20)
print(x)
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()
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
>>> 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)
... print(amount)
What will be the result? ...
>>> test()
???
>>>
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)
Why 1000 and NOT ... 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
... rate = 0.05
pass parameters
... addInterest(amount, rate) by value!
... print(amount)
...
>>> test()
1000
>>>
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
x=1 x=1
increment_func(x) x = increment_func(x)
print(x) print(x)
Run
Run
1 2
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
>>> applier(square, 7)
49
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
Lambda Notation
• Python’s lambda creates anonymous
functions
>>> applier(lambda z: z * 42, 7) Another Example:
14
>>> lambda x: x + 1
• Note: only one expression in the lambda <function <lambda> at 0x1004e6ed8>
>>> f = lambda x: x + 1
body; its value is always returned >>> f
• Python supports functional programming <function <lambda> at 0x1004e6f50>
>>> f(100)
idioms: map, filter, closures, continuations, 101
etc.
Lambda Notation
Be careful with the syntax Lambda Notation Limitations
>>> f = lambda x,y : 2 * x + y • Note: only one expression in the
>>> f
lambda body; Its value is always
<function <lambda> at 0x87d30>
returned
>>> f(3, 4)
10 • The lambda expression must fit on
>>> v = lambda x: x*x(100) one line!
>>> v • Lambda will probably be
<function <lambda> at 0x87df0> deprecated in future versions of
>>> v = (lambda x: x*x)(100)
python
>>> v
10000 Guido is not a lambda fanboy
Functional programming
Example: composition
>>> def square(x):
return x*x
>>> def twice(f):
return lambda x: f(f(x))
>>> twice
<function twice at 0x87db0>
>>> quad = twice(square)
>>> quad
<function <lambda> at 0x87d30>
>>> quad(5)
625
Example: closure
>>> def counter(start=0, step=1):
x = [start]
def _inc():
x[0] += step
return x[0]
return _inc
>>> c1 = counter()
>>> c2 = counter(100, -10)
>>> c1()
1
>>> c2()
90
map
• + is an operator, not a function
• We can define a corresponding add function
>>> def add(x, y): return x+y
>>> map(add,[1,2,3,4],[100,200,300,400])
[101, 202, 303, 404]
• Or import the operator module
>>> from operator import *
>>> map(add, [1,2,3,4], [100,200,300,400])
[101, 202, 303, 404]
>>> map(sub, [1,2,3,4], [100,200,300,400])
[-99, -198, -297, -396]
>>> print()
>>>
>>> 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
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
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
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
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 illustrate the use of this math library via computing the roots of
a quadratic equation with the form 𝑎𝑥 2 + 𝑏𝑥 + 𝑐 = 0
−𝑏 ± 𝑏 2 − 4𝑎𝑐
𝑥=
2𝑎
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
def rootsQEq():
print("This program finds the real solutions to a quadratic.")
print()
print()
print("The solutions are: ", root1, root2)
• Next week, we will learn some tools that allow us to fix this problem
Conditional Statements
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
Decision Structures
• So far, we have mostly viewed computer programs as sequences of
instructions that are interpreted one after the other
main()
main()
One-Way Decisions
• We applied the Python if statement to implement a one-way decision,
using the following form:
One-way Condition
if <condition>: Yes
<condition>
<body> true?
<statement>
• Simple <condition> compares values of two expressions
using a comparison operator as follows: <statement>
Logical Operators
• We can also use logical operators with our conditions
Operator Description
not x Evaluates to the opposite- i.e., if x is False, the result
will be True and vice versa
Logical Operators
• True or False?
Statement Result
(3*4 > 10) and (3+4 < 10) True
(3*4 < 10) or (3+4 < 10) True
not ((3*4 < 10) or (3+4 < 10)) False
(3 * 4 > 10) or (5 + 5 > 10) and (4 * 4 > 15) or True
(5 + 4 > 10)
Membership Operators
• We can also use membership operators with conditions
Operator Description
x in sequence Evaluates to True if x is found in the given sequence
(e.g., string)
Membership Operators
• True or False?
Statement Result
“15-110” in “15-110 is a lot of fun!” True
“Java” not in “15-110 uses Python to illustrate True
computing principles”
1 in “15-110” ERROR
“1” in “15-110” True
Identity Operators
• We can also use identity operators with conditions
Operator Description
x is y Evaluates to True if x and y point to the same object
Membership Operators
• True or False?
>>> x = "cmu"
>>> y = "cmu"
>>> x is y
True
>>> z = x
>>> z is y
True
>>>
Membership Operators
• True or False?
>>> x = "cmu"
>>> y = "cmu"
>>> x is y
True
>>> z = x
>>> z is y
True
>>>
Membership Operators
• True or False?
Membership Operators
• True or False?
Membership Operators
• True or False?
Two-Way Decisions
• Notice how we attached an else clause onto an if clause to come up
with what we refer to as a two-way decision
No <condition> Yes
true?
if <condition>:
<statements>
else: <statement> <statement>
<statements>
<statement> <statement>
<statement> <statement>
def rootsQEq():
print("This program finds the real solutions to a quadratic.")
print()
print()
print("The solutions are: ", root1, root2)
def rootsQEq():
print("This program finds the real solutions to a quadratic.")
print()
discriminant = b * b – 4 * a * c
rootsQEq()
Enter the value of coefficient b: 2
Enter the value of coefficient c: 3
The equation has no real roots!
Good, But…
• This new version of the quadratic solver is certainly a big
improvement, but it still has some quirks!
• Let us illustrate that through examples:
This program finds the real solutions to a quadratic.
Good, But…
• Another sample run:
This program finds the real solutions to a quadratic.
Coefficient a
Enter the value of coefficient a: 0 CANNOT be zero
Enter the value of coefficient b: 2 since we cannot
Enter the value of coefficient c: 1
Traceback (most recent call last):
divide by zero
root1 = (-b + s_root_val)/(2*a) (a serious issue)!
ZeroDivisionError: float division by zero
Digging Deeper…
• If we trace this code carefully, we will observe that there are exactly
three possible paths
Yes Discriminant No
<0?
Multi-Way Decisions
• We managed to finesse a 3-way decision by using 2 2-way decisions
Multi-Way Decisions
• Here is how the if-elif-else form looks like:
if <condition1>:
<case1 statements>
elif <condition2>:
<case2 statements>
The else clause is elif <condition3>:
optional; if omitted, it is
<case3 statements>
possible that no
indented statement …
block will be executed! else:
<default statements>
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
def rootsQEq():
print("This program finds the real solutions to a quadratic.")
print()
discriminant = b * b – 4 * a * c
rootsQEq()
def rootsQEq():
print("This program finds the real solutions to a quadratic.")
print()
discriminant = b * b – 4 * a * c
if a == 0:
print("Cannot divide by zero")
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
if x1 >= x2:
if x1 >= x3:
max = x1
else:
max = x3
else:
if x2 >= x3:
max = x2
else:
This program uses a
max = x3 strategy that can be
referred to as
print("The largest value is", max)
“decision tree”
main()
Yes No Yes No
X1 >= x3 X2 >= x3
Still, this strategy (i.e., decision tree) makes it very difficult to scale the program to more
numbers (say, 10, 100, or even more)!
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
if x3 > max:
max = x3 This program uses a
strategy that can be
print("The largest value is", max) referred to as
“sequential processing”
main()
for i in range(10):
print(“Hello”) This will print Hello ten times!
def main():
x1, x2, x3 = eval(input("Please enter three values: "))
• Do not rush to code up the first idea that pops into your head; rather,
think about your design and ask yourself if there is a better way to
solve the problem
• Do not reinvent the wheel– you can use Python’s existing libraries!
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
Towards Loops
• We looked in detail at the Python if statement and its use in
implementing programming patterns such as 1-way, 2-way, and multi-
way decisions
• We will now look at a new structure, known as the control (or loop)
structure, which allows us to iterate through a sequence of values
• We have seen very briefly in the last lecture the Python for statement,
which provides an example of a loop
• <var> is called the loop index, which takes on each successive value in
<sequence>, and <body> is executed once for each value
More items in No
<sequence>
Yes
<var> = Next item
<body>
for i in range(n):
x = eval(input("Enter a number >> "))
sum = sum + x
main()
n = eval(input("Enter n: "))
for i in range(n+1):
if i % 2 == 1:
print(i, end = " ")
print()
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
print()
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
print()
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
print()
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
print()
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
print()
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
for i in range(9):
if i == 0 or i == 8:
x = "*********"
else:
x = "* *"
print(x)
while <condition>:
<body>
Is <condition> No
True?
Yes
<body>
for i in range(n):
x = eval(input("Enter a number >> "))
sum = sum + x
main()
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
print("The average of the " + str(n) + " numbers you entered is ", sum/n)
print("The average of the " + str(count) + " numbers you entered is ", sum/count)
• The program assumes some conditions, whereby the start and end
numbers shall be positive and end should be always greater than start
• Hence, we should continue prompting the user for the correct input
before proceeding with printing the odd numbers
• This process is typically called input validation
• Well-engineered programs should validate inputs whenever possible!
Nested Loops
• Like the if statement, loops can also be nested to produce
sophisticated algorithms
• Example: Write a program that prints the following rhombus shape
*
* *
* *
* *
* *
* *
* *
* *
*
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics
rows = abs(rows)
columns = abs(columns)
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics