0% found this document useful (0 votes)
13 views143 pages

Lecture02 Spring2024

Uploaded by

mtahariaz1
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)
13 views143 pages

Lecture02 Spring2024

Uploaded by

mtahariaz1
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/ 143

PROGRAMMING FOR FINANCE

FIN-460, Spring-2024

ADNAN HAIDER

Professor of Business Economics and Analytics


Department of Finance
School of Business Studies
Institute of Business Administration, Karachi, Pakistan.

January 29, 2024

Instructor: Adnan Haider Week-02 January 29, 2024 1


Python Programming Basics

Functions and Control Structures

Instructor: Adnan Haider Week-02 January 29, 2024 2


Python Programming Basics

User-Defined Functions
in Python

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

The indentation matters…


First line with less
indentation is considered to be The keyword ‘return’ indicates the
outside of the function definition. value to be sent back to the caller.

No header file or declaration of types of function or arguments


Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

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 >>>
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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.

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Parameters and Data Type


• Dynamic typing: Python determines the data types of variable bindings in
a program automatically
• Strong typing: But Python’s not casual about types, it enforces the types
of objects
• For example, you can’t just append an integer
to a string, but must first convert it to a string

x = “the answer is ” # x bound to a string


y = 23 # y bound to an integer.
print x + y # Python will complain!

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Parameters with Default Values


Function overloading? No.
• There is no function overloading in Python
• Unlike C++, a Python function is specified by its name alone
The number, order, names, or types of arguments cannot be used to distinguish between two functions
with the same name
• Two different functions can’t have the same name, even if they have
different arguments
• But: see operator overloading in later slides
(Note: van Rossum playing with function overloading for the future)

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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 20 10 100 ERROR

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Parameters with Default Values


• You can provide default values for a function’s arguments
• These arguments are optional when the function is called

>>> def myfun(b, c=3, d=“hello”):


return b + c
>>> myfun(5,3,”hello”)
>>> myfun(5,3)
>>> myfun(5)

All of the above function calls return 8

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

Functions are first-class objects


Functions can be used as any other datatype, eg:
• Arguments to function
• Return values of functions
• Assigned to variables
• Parts of tuples, lists, etc

>>> def square(x): return x*x

>>> def applier(q, x): return q(x)

>>> applier(square, 7)
49
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

Functions without returns

• 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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Modularity and Maintenance


• 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 singFred():
print("Happy birthday to you!") happy()
happy()
Can we write this program with print("Happy birthday, dear Fred")
ONLY two prints? happy()

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

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?

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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!

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Functions and Scope of Variables


• 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>
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

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
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

Global Variables
• Consider the following code
#global scope
x = 100

def func2(): Run 100


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()

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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()
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

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(…)


Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

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()
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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()
???
>>>

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

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
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

Functions are first-class objects


Functions can be used as any other datatype, eg:
• Arguments to function
• Return values of functions
• Assigned to variables
• Parts of tuples, lists, etc

>>> def square(x): return x*x

>>> def applier(q, x): return q(x)

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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Functional programming

• Python supports functional programming idioms


• Builtins for map, reduce, filter, closures, continuations, etc.
• These are often used with lambda

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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]

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

map, filter, reduce


>>> def add1(x): return x+1 >>> map(add,[1,2,3,4],[100,200,300,400])
>>> def odd(x): return x%2 == 1 [101, 202, 303, 404]
>>> def add(x,y): return x + y >>> reduce(add, [1,2,3,4])
>>> map(add1, [1,2,3,4]) 10
[2, 3, 4, 5] >>> filter(odd, [1,2,3,4])
>>> map(+,[1,2,3,4],[100,200,300,400]) [1, 3]
map(+,[1,2,3,4],[100,200,300,400])
^
SyntaxError: invalid syntax The map, filter and reduce functions
are also at risk 

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

More on the Print Function


• There are different forms of the print function
1) print(), which produces a blank line of output

>>> print()

>>>

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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!

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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)

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Example
• Solution:
3) Design:
• Pseudocode:

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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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!

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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 𝑎𝑥 2 + 𝑏𝑥 + 𝑐 = 0

• Such an equation has two solutions:

−𝑏 ± 𝑏 2 − 4𝑎𝑐
𝑥=
2𝑎
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

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: "))

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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()

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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):
s_root_val = math.sqrt(b*b - 4 * a * c)
ValueError: math domain error

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Using the Math Library: An Example


• The problem is that 𝑏 2 − 4𝑎𝑐 < 0
• The sqrt function is unable to compute the square root of a
negative number

• Next week, 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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Control and Decision Structures


in Python

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

• Sequencing is a fundamental concept of programming, but alone it is not


sufficient to solve every problem

• Often it is necessary to alter the sequential flow of a program to suit the


needs of a particular situation

• We will study decision structures, which are statements that allow a


program to execute different sequences of instructions for different cases
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

Example: Temperature Warnings


• Let us consider again our Celsius to Fahrenheit temperature program
def main():
celsius = eval(input("What is the Celsius temperature? "))
fahrenheit = 9/5 * celsius + 32
print("The temperature is", fahrenheit, "degrees Fahrenheit")

main()

• How can we enhance this program to print a suitable warning when


the temperature is extreme (say, over 90 degrees F, it deserves a heat
warning, and under 30 it deserves a cold warning)?

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Example: Temperature Warnings


• Enhanced Celsius to Fahrenheit temperature program
def main():
celsius = eval(input("What is the Celsius temperature? "))
fahrenheit = 9/5 * celsius + 32
print("The temperature is", fahrenheit, "degrees Fahrenheit")
if fahrenheit > 90:
print(“It is really hot outside. Be careful!”)
if fahrenehit < 30:
print(“Brrrrr. Be sure to dress warmly!”)

main()

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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?

• <body> is just a sequence of one or more statements No


indented under the if heading <statement>

<statement>
• Simple <condition> compares values of two expressions
using a comparison operator as follows: <statement>

<expr> <comp> <expr>


Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

Comparison (Relational) Operators


• There are six comparison (or relational) operators in Python

Python Mathematics Meaning


< < Less than
<= ≤ Less than or equal to
== = Equal to
>= ≥ Greater than or equal to
> > Greater than
!= ≠ Not equal to

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Conditions and Booleans


• Conditions may compare either numbers or strings

• Strings are compared lexicographically, meaning that they are


compared character by character according to their Unicode values
• E.g., “Bbbb” is less than “aaaa” since “B” precedes “a” (all uppercase Latin
letters come before lowercase equivalents)

• A condition is actually a Boolean expression, which produces a value of


either True (the condition holds) or False (the condition does not hold)

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Conditions and Booleans


• Here are few interactive examples:
>>> "a" < "b" >>> "a" == "a"
True True
>>> "aa" < "a" >>> type("a" == "a")
False <class 'bool'>
>>> "a" < "A" >>> 3 < 4
False True
>>> "Hello" < "hello" >>> 3 * 4 < 3 + 4
True False
>>> >>>

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Chaining Comparison Operators


• Comparison operators can be chained
>>> 1 < 2 < 3 >>> 3 < x < 2
True False
>>> x = 2 >>> 2 == x < 4
>>> 1 < x < 2 True
False >>> y = 4
>>> 1 < x < 2 < 3 < 4 < 5 >>> 1 < x <= 2 < y
False True
>>> 1 < x <= 2 >> 1 != 2
True True

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

x and y Evaluates to True if both, x and y are True


x or y Evaluates to True if either x is True or y is True

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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)

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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)

x not in Evaluates to True if x is NOT found in the given


sequence sequence (e.g., string)

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

x is not y Evaluates to True if x and y do not point to the same object

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Membership Operators
• True or False?

>>> x = "cmu"
>>> y = "cmu"
>>> x is y
True
>>> z = x
>>> z is y
True
>>>

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Membership Operators
• True or False?

>>> x = "cmu"
>>> y = "cmu"
>>> x is y
True
>>> z = x
>>> z is y
True
>>>

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Membership Operators
• True or False?

>>> x = "cmu" >>> a = 5


>>> y = "cmu" >>> if (type(a) is int):
>>> x is y ... print("true")
True ... else:
>>> z = x ... print("false")
>>> z is y ...
True true
>>> >>>

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Membership Operators
• True or False?

>>> x = "cmu" >>> a = 5 >>> b = 5.4


>>> y = "cmu" >>> if (type(a) is int): >>> if (type(b) is not int):
>>> x is y ... print("true") ... print("true")
True ... else: ... else:
>>> z = x ... print("false") ... print("false")
>>> z is y ... ...
True true true
>>> >>> >>>

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Membership Operators
• True or False?

>>> x = "cmu" >>> a = 5 >>> b = 5.4


>>> y = "cmu" >>> if (type(a) is int): >>> if (type(b) is not int):
>>> x is y ... print("true") ... print("true")
True ... else: ... else:
>>> z = x ... print("false") ... print("false")
>>> z is y ... ...
True true true
>>> >>> >>>

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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>

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Revisiting Our Quadratic Equation Solver


#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: "))

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Revisiting Our Quadratic Equation Solver


#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()

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Revisiting Our Quadratic Equation Solver


• A 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):
s_root_val = math.sqrt(b*b - 4 * a * c)
ValueError: math domain error

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Revisiting Our Quadratic Equation Solver


• The problem is that 𝑏 2 − 4𝑎𝑐 < 0
• The sqrt function is unable to compute the square root of a
negative number

• How can we avoid this problem?


• We can first compute the discriminant 𝑏 2 − 4𝑎𝑐 < 0
• Then, we can check if it is negative (via using the if statement)
• If it is negative, we can print out that the equation has no real roots
• Otherwise (via using the else clause), we can compute the solutions and
print them out

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

A Refined Quadratic Equation Solver


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: "))

discriminant = b * b – 4 * a * c

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

A Refined Quadratic Equation Solver


if discriminant < 0:
print(“The equation has no real roots!”)
else:
s_root_val = math.sqrt(discriminant)
root1 = (-b + s_root_val)/(2*a)
root2 = (-b - s_root_val)/(2*a)

print(“\nThe solutions are: ", root1, root2)

rootsQEq()

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Revisiting Our Quadratic Equation Solver


• A sample run:

This program finds the real solutions to a quadratic.

Enter the value of coefficient a: 1


Enter the value of coefficient b: 2
Enter the value of coefficient c: 3
The equation has no real roots!

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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.

Enter the value of coefficient a: 1 A double root at -1.0; printed


Enter the value of coefficient b: 2 twice, thus might seem confusing
Enter the value of coefficient c: 1 to some people (a styling issue)!

The solutions are: -1.0 -1.0

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

The Need for a Three-Way Decision


• Let us start with the double-root situation, which occurs when the
discriminant is exactly 0
• If we want to catch this special case, our quadratic equation solver
needs a three-way decision
• Here is a quick sketch of what we need:

Check the value of the discriminant
when < 0: handle the case of no roots
when = 0: handle the case of a double root
when > 0: handle the case of two distinct roots

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

A Three-Way Decision Via Two if-else Statements


• One way to code this algorithm is to use two if-else statements

if discriminant < 0:
print(“Equation has no real roots”)
else:
if discriminant == 0:
root = -b / (2 * a)
print(“There is a double root at”, root)
else:
#Do stuff for two roots…
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

Digging Deeper…
• If we trace this code carefully, we will observe that there are exactly
three possible paths
Yes Discriminant No
<0?

Print “no roots” Yes Discriminant No


== 0 ?

Do Double Roots Do Unique Roots

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Multi-Way Decisions
• We managed to finesse a 3-way decision by using 2 2-way decisions

• What happens if we needed to make a 5-way decision using this


technique?
• The if-else structures would nest four levels deep, and the Python
code would march off the right-hand edge of the page

• Is there any other way in Python to write multi-way decisions?


• Yes, by using if-elif-else statements

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

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

Revisiting Our Quadratic Equation Solver


import math

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

a, b, c = eval(input("Please enter the coefficients (a, b, c): "))

discriminant = b * b – 4 * a * c

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Revisiting Our Quadratic Equation Solver


if discriminant < 0:
print("The equation has no real roots!")
elif discriminant == 0:
root = -b/(2*a)
print("\nThere is a double root at", root)
else:
s_root_val = math.sqrt(discriminant)
root1 = (-b + s_root_val)/(2*a)
root2 = (-b - s_root_val)/(2*a)
print("\nThe solutions are: ", root1, root2)

rootsQEq()

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Three Sample Runs


This program finds the real solutions to a quadratic.
When discriminant < 0
Please enter the coefficients (a, b, c): 1, 2, 3
The equation has no real roots!

This program finds the real solutions to a quadratic.


When discriminant == 0
Please enter the coefficients (a, b, c): 1, 2, 1

There is a double root at -1.0

This program finds the real solutions to a quadratic.


When discriminant < 0
Please enter the coefficients (a, b, c): 3, 4, -2

The solutions are: 0.38742588672279316 -1.7207592200561266

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Avoid Dividing By Zero


• Let us now handle the case of avoiding a division by zero
import math

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

a, b, c = eval(input("Please enter the coefficients (a, b, c): "))

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

Avoid Dividing By Zero


• Let us now handle the case of avoiding a division by zero
elif discriminant < 0:
print("The equation has no real roots!")
elif discriminant == 0:
root = -b/(2*a)
print("\nThere is a double root at", root)
else:
s_root_val = math.sqrt(discriminant)
root1 = (-b + s_root_val)/(2*a)
root2 = (-b - s_root_val)/(2*a)
print("\nThe solutions are: ", root1, root2)
rootsQEq()
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

Avoid Dividing By Zero


• Let us try to divide by zero:
This program finds the real solutions to a quadratic.

Please enter the coefficients (a, b, c): 0, 1, 2


Cannot divide by zero 

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Study in Design: Max of Three Numbers (v1)


def main():
x1, x2, x3 = eval(input("Please enter three values: "))

if x1 >= x2 and x1 >= x3: Difficult to scale the


max = x1 program to more
elif x2 > x1 and x2 > x3: numbers (say, 10, 100,
max = x2
or even more)– i.e.,
else:
max = x3 following this strategy This program uses a
will make the code strategy that can be
print("The largest value is", max) very long, complex, referred to as
and prone to errors! “compare each to all”
main()

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Study in Design: Max of Three Numbers (v2)


def main():
x1, x2, x3 = eval(input("Please enter three values: "))

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()

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Study in Design: Max of Three Numbers (v2)


Yes No
x1 >= x2

Yes No Yes No
X1 >= x3 X2 >= x3

max = x1 max = x3 max = x2 max = 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

Study in Design: Max of Three Numbers (v3)


def main():
x1, x2, x3 = eval(input("Please enter three values: "))
max = x1
if x2 > max:
max = x2

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()

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Study in Design: Max of Three Numbers (v3)


• Interestingly, this version (i.e., v3) of the program allows us to scale to
larger problems

• In particular, we can easily write a program that computes the largest


of n numbers by folding our algorithm into a loop
• A loop is a device that tells a program to do the same thing over
and over again! (more on this next lecture)

for i in range(10):
print(“Hello”) This will print Hello ten times!

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Study in Design: Max of Three Numbers (v3)


def main():
n = eval(input("How many numbers are there? "))

#set max to be the first value; we can involve conditions here to


#ensure that n is greater than or equal to 1
max = eval(input("Enter a number >> "))

#Now compare the n-1 successive values


for i in range(n-1):
x = eval(input("Enter a number >> ")) This is a more general
if x > max: solution!
max = x

print("The largest value is", max)


main()

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Study in Design: Max of Three Numbers (v4)


• We can even go green!

def main():
x1, x2, x3 = eval(input("Please enter three values: "))

print("The largest value is", max(x1, x2, x3))


This program uses a
main() strategy that can be
referred to as
“use Python”!

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Study in Design: Lessons Learned


• There is typically more than 1 way to solve a problem!

• 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

• Generality is good – we arrived at the best solution to the max of three


problem by considering the more general max of n numbers problem

• Do not reinvent the wheel– you can use Python’s existing libraries!
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

Control and Decision Structures


in Python

Recursive Statements: Loops and Recursion


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

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

The for Loop


• A Python for loop has this general form:
for <var> in <sequence>:
<body>
• The <body> of the loop can be any sequence of Python statements

• <var> is called the loop index, which takes on each successive value in
<sequence>, and <body> is executed once for each value

• The <sequence> portion consists of a list of values


• E.g., range(n) is a built-in function in Python that generates “on the fly” a
sequence of numbers that starts at 0 and ends at n-1

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

The Flowchart of a for Loop

More items in No
<sequence>
Yes
<var> = Next item

<body>

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Example 1: Average of a Series of Numbers


• Suppose we want to write a program that can compute the average of
a series of numbers entered by the user

• Here is an algorithm to do so:


Input the count of the numbers, n
Initialize sum to 0
Loop n times
Input a number, x
Add x to sum
Output average as sum/n

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Example 1: Average of a Series of Numbers


• We can easily translate this algorithm into a Python implementation
def main():
n = eval(input("How many numbers do you have? "))
sum = 0.0

for i in range(n):
x = eval(input("Enter a number >> "))
sum = sum + x

print("\nThe average of the numbers is", sum/n)

main()

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Example 2: Printing Odd Numbers


• Suppose we want to write a program that prints odd numbers from 0
to n (inclusive), which can be input by a user

• Here is how the program can look like:

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

Example 2: Printing Odd Numbers


• What if we want to print odd numbers from 1 (NOT 0) to n (inclusive),
which can be input by a user?
n = eval(input("Enter n: "))
for i in range(n+1):
if i == 0:
pass
else:
if i % 2 == 1:
print(i, end = " ")

print()
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

Example 2: Printing Odd Numbers


• What if we want to print odd numbers from 2 (NOT 1) to n (inclusive),
which can be input by a user?
n = eval(input("Enter n: "))
for i in range(n+1):
if i < 2:
pass
else:
if i % 2 == 1:
print(i, end = " ")

print()
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

Example 2: Printing Odd Numbers


• What if we want to print odd numbers from 3 (NOT 2) to n (inclusive),
which can be input by a user
n = eval(input("Enter n: "))
for i in range(n+1):
if i < 3:
pass
else:
if i % 2 == 1:
print(i, end = " ")

print()
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

Example 2: Printing Odd Numbers


• Is there a better way for doing this?
• Yes, we can use another version of range, namely, range(start, end)

s = eval(input("Enter the starting number: "))


e = eval(input("Enter the ending number: "))

for i in range(s, e+1):


if i % 2 == 1:
print(i, end = " ")

print()
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

Yet, Another Version of Range(.)


• We can even specify a different increment in the range(…) function
via including a third argument to it (i.e., range(start, end, step))

start = eval(input("Enter a starting number: "))


end = eval(input("Enter an ending number: "))
step = eval(input("Enter the step: "))

for i in range(start, end, step):


print(i, end = " ")

print()
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

Example 3: Fibonacci Sequence


• Suppose we want to write a program that computes and outputs the
nth Fibonacci number, where n is a value entered by a user

• The Fibonacci sequence starts with 0 and 1

• After these first two numbers, each number in the sequence is


computed as simply the sum of the previous two numbers
• E.g., 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Example 3: Fibonacci Sequence


def fibonacci(n):
f_i = 0
f_j = 1

print(f_i, f_j, end = " ")

for k in range(2, n+1):


f_new = f_i + f_j
print(f_new, end = " ")
f_i = f_j
f_j = f_new
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

Example 3: Fibonacci Sequence


n = eval(input("Enter a number that is larger than 1 >> "))
if n < 2:
print("You can only enter a number that is larger than 1!")
else:
fibonacci(n)

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Example 4: A Rectangle of Stars


• How can we write a program that draws the following shape of stars
using only 1 for loop and 1 if-else statement?
* * * * * * * * *
* *
* *
* *
* *
* *
* *
* *
* * * * * * * * *
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

Example 4: A Rectangle of Stars


• How can we write a program that draws the following shape of stars
using only 1 for loop and 1 if-else statement?

for i in range(9):
if i == 0 or i == 8:
x = "*********"
else:
x = "* *"

print(x)

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Recap: Fibonacci Sequence


• Suppose we want to write a program that computes and outputs the
nth Fibonacci number, where n is a value entered by a user

• The Fibonacci sequence starts with 0 and 1

• After these first two numbers, each number in the sequence is


computed as simply the sum of the previous two numbers
• E.g., 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Recap: Fibonacci Sequence


def fibonacci(n):
f_i = 0
f_j = 1

print(f_i, f_j, end = " ")

for k in range(2, n+1):


f_new = f_i + f_j
print(f_new, end = " ")
f_i = f_j
f_j = f_new
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

Recap: Fibonacci Sequence


n = eval(input("Enter a number that is larger than 1 >> "))
if n < 2:
print("You can only enter a number that is larger than 1!")
else:
fibonacci(n)

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Definite Loops vs. Indefinite Loops


• So far, we have considered only the case where the number of
iterations is determined before the loop starts
• This kind of loops is called definite loops and for is used in Python
to write definite loops

• But, what if we want to write loops, wherein we do not know the


number of iterations beforehand?
• This kind of loops is denoted as indefinite loops

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

The While Statement


• In Python, an indefinite loop is implemented using a while statement

while <condition>:
<body>

• <condition> is a Boolean expression, just like in if statements

• <body> is, as usual, a sequence of one or more statements

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

The Flowchart of a While Loop

Is <condition> No
True?

Yes

<body>

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Revisiting Average of a Series of Numbers


• Here is how we have done it before:
def main():
n = eval(input("How many numbers do you have? "))
sum = 0.0

for i in range(n):
x = eval(input("Enter a number >> "))
sum = sum + x

print("\nThe average of the numbers is", sum/n)

main()
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

Revisiting Average of a Series of Numbers


• Here is how we can do it now using a while statement:
sum = 0.0
n = eval(input("How many numbers do you have? "))
count = 0
while count < n:
x = eval(input("Enter a number >> "))
sum = sum + x
count = count + 1

print("The average of the " + str(n) + " numbers you entered is ", sum/n)

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Revisiting Average of a Series of Numbers


• Here is also another version that assumes no prior knowledge about
the quantity of numbers the user will input
sum = 0.0
count = 0
moreData = "yes"
while moreData == "yes":
x = eval(input("Enter a number >> "))
sum = sum + x
count = count + 1
moreData = input("Do you have more numbers (yes or no)? ")

print("The average of the " + str(count) + " numbers you entered is ", sum/count)

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Printing Odd Numbers With Input Validation


• Suppose we want to print the odd numbers between two user-input
numbers (inclusive), say, start and end

• 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!

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Printing Odd Numbers With Input Validation


1. while True:
2. start = eval(input("Enter start number: "))
3. end = eval(input("Enter end number: "))
4. if start >=0 and end >= 0 and end > start:
5. break It breaks the loop; execution continues at line 8.
6. else:
7. print("Please enter positive numbers, with end being greater than start")
8.
9. for i in range(start, end + 1):
10. if i % 2 == 0:
It skips one iteration in the loop; execution
11. continue
continues back at line 9.
12. print(i, end = " ")
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

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

The Rhombus Example


• One way (not necessarily the best way!) to think about this problem is to
assume that the stars are within a matrix with equal rows and columns
1 2 3 4 5 6 7 8 9
1 *
2 * *
3 * * Can you figure
4 * * out the different
5 * * relationships
6 * * between rows
7 * * and columns?
8 * *
9 *

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

The Rhombus Example


• One way (not necessarily the best way!) to think about this problem is to
assume that the stars are within a matrix with equal rows and columns
1 2 3 4 5 6 7 8 9
1 *
2 * * Print a star when:
3 * * 1) Row + Column == 6
4 * * 2) Row + Column == 14
5 * * 3) Row – Column == 4
6 * * 4) Column – Row == 4
7 * *
8 * *
9 *

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

The Rhombus Example


• Here is one way of writing the program in Python
for i in range(1, 10):
for j in range(1, 10):
if ((i+j== 6) or (j-i==4) or (i+j == 14) or (i-j==4)):
print("*", end = "")
else:
print(" ", end = "")
print()

Can you generalize this code?


Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

The Rhombus Example


• What are 6, 14, 4, and 4 below?
1 2 3 4 5 6 7 8 9
1 *
2 * *
Print a star when:
3 * *
4 * *
1) Row + Column == 6
5 * *
2) Row + Column == 14
6 * * 3) Row – Column == 4
7 * * 4) Column – Row == 4
8 * *
9 *
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

The Rhombus Example


• What are 6, 14, 4, and 4 below?
1 2 3 4 5 6 7 8 9
1 *
2 * *
Print a star when:
3 * *
4 * *
1) Row + Column == 6 (i.e., Columns/2 +2)
5 * *
2) Row + Column == 14 (i.e., Columns + 𝑹𝒐𝒘𝒔/𝟐 )
6 * * 3) Row – Column == 4 (i.e., Columns/2)
7 * * 4) Column – Row == 4 (i.e., Columns/2)
8 * *
9 *
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

The Rhombus Example: A More General Version


while True:
rows = eval(input("Enter number of rows: "))
columns = eval(input("Enter number of columns: "))

if rows != columns or rows % 2 != 1 or columns % 2 != 1:


print("Please enter odd and equal rows and columns")
else:
break

rows = abs(rows)
columns = abs(columns)
Instructor: Adnan Haider Week-02 January 29, 2024
Python Programming Basics

The Rhombus Example: A More General Version


for i in range(1, rows+1):
for j in range(1, columns+1):
if ((i+j== (columns//2 +2)) or (j-i==(columns//2)) or (i+j ==
(columns+ math.ceil(rows/2))) or (i-j==(columns//2))):
print("*", end = "")
else:
print(" ", end = "")
print()

Instructor: Adnan Haider Week-02 January 29, 2024


Python Programming Basics

Instructor: Adnan Haider Week-02 January 29, 2024

You might also like