Computer Programming (EGR2313) : Amir A. Bature Nabila Ahmad Rufa'i
Computer Programming (EGR2313) : Amir A. Bature Nabila Ahmad Rufa'i
(EGR2313)
LECTURE week 3: Control Flows and Functions
Amir A. Bature
[email protected]
Nabila Ahmad Rufa’i
[email protected]
Department of Electrical Engineering
Bayero University, Kano
2021
1
Week 3 Lecture:
Control Flow and Functions
1. More on Variables
2. Conditional Statements
3. Loops
4. Functions
2
More on Variables
TYPES OF OBJECTS
Variables and expressions
int
float
bool
string
… and others we will see later
3
More on Variables
VARIABLES
Need a way to refer to computed values abstractly –give
them a “name”
Name
descriptive
meaningful
helps you re-read code
should not be keywords
Value
information stored
can be updated
9/
4
More on Variables
STRINGS (RECAP)
• Made up from letters, special characters, spaces, digits
• Think of as a sequenceof case sensitive characters
• Enclose in quotation marks or single quotes
• today = 'Monday'
• Concatenatestrings
this = "it is"
what = this + today
what = this + " " + today
Do some operations on a string as defined in Python docs
announce = "It's " + today * 3
9/
5
More on Variables
OPERATOR OVERLOAD
Same operator used on different object types
+ operator
E.g. Between two numbers: adds
E.g. Between two strings: concatenates
* Operator
E.g. Between two numbers: multiplies
E.g. Between a number and a string: repeats the string
9/9/
6
More on Variables
STRING OPERATIONS
Can compare strings with ==, >, < etc.
len()is a function used to retrieve the length of the string in the parentheses
s = "abc"
len(s) →evaluates to 3
6.0001 LECTURE
Square brackets used to perform indexing into a string to get the value at a
certain index/position
s = "abc"
s[0] →evaluates to "a"
s[1] →evaluates to "b"
s[2] →evaluates to "c"
s[3] →trying to index out of bounds, error
s[-1] →evaluates to "c"
s[-2] →evaluates to "b"
s[-3] →evaluates to "a"
6.0001 LECTURE
7
More on Variables
STRINGS
• Can slice strings using [start:stop:step]
• If give two numbers, [start:stop], step=1by default
• Get characters at start until stop-1
• You can also omit numbers and leave just colons
s = "abcdefgh"
s[3:6] → evaluates to "def", same as s[3:6:1]
s[3:6:2] → evaluates to "df"
s[::] → evaluates to "abcdefgh", same as s[0:len(s):1]
s[::-1] → evaluates to "hgfedbca", same as
s[-1:-(len(s)+1):-1]
s[4:1:-2]→ evaluates to "ec"
8
More on Variables
BOOLS
Boolean values
True
False
9
If statements
Format 1
Format 3
Format 2
10
If statements
Flowchart of if statements
11
If statements
Logic Operators to use in if statements
12
If statements
INDENTATION
Matters in Python
How you denote blocks of code
13
Control Flow
while LOOPS
while<condition>:
<expression>
<expression>
...
14
Control Flow
while LOOPS
Example 1:
where = input("You're Lost. Go left or right? ")
while where == "right":
where = input("You're Lost. Go left or right? ")
print("You got out of the Lost Forest!")
Example 2:
Iterate through numbers in a sequence
# more complicated with while loop
n = 0
while n < 5:
print(n)
n = n+1 #Increment loop variable inside while loop
15
Control Flow
for LOOPS
for <variable> in range(<some_num>):
<expression>
<expression>
...
16
Control Flow
for Loops:
range(start,stop,step)
• Default values are start = 0 and step = 1 and
optional
• Loop until value reaches stop -1
Examples:
mysum= 0
for i in range(7, 10):
mysum+= i
print(mysum)
mysum= 0
for i in range(5, 11, 2):
mysum+= i
print(mysum)
9/
17
Control Flow
break STATEMENT
• Immediately exits whatever loop it is in
• Skips remaining expressions in code block
• Exits only innermost loop!
while <condition_1>:
while <condition_2>:
Evaluated when <condition_1> and
<expression_a>
<condition_2> are True
break
<expression_b> Never evaluated
<expression_c>
6.0001 LECTURE 9/9/2019 Evaluated when <condition_1> is True
18
Control Flow
Break STATEMENT
mysum = 0
for i in range(5, 11, 2):
mysum += i
if mysum == 5:
break
mysum += 1
print(mysum)
19
Control Flow
for VS while LOOPS
for loops while loops
• know number of • Unbounded number of
iterations iterations
• can end early via break
• can end early via break
• can use a counter but
• uses a counter must initialize before
• can rewrite a for loop loop and increment it
using a while loop inside loop
• may not be able to
rewrite a while loop
using a for loop
20
Control Flow
STRINGS AND LOOPS
s = "computer programming class 2021"
for index in range(len(s)):
if s[index] == 'i' or s[index] == 'u’:
print("There is an i or u")
s = "computer programming class 2021"
for char in s:
if char == 'i’ or char == 'u’:
print("There is an i or u")
22
Functions
DECOMPOSITION AND ABSTRACTION
▪ Decomposition is about dividing a program into self-
contained parts that can be combined to solve the
problem at hand
• ideally parts can be reused by other programs
23
Functions
24
Functions
25
Functions
in programming, think of a piece of code as a black box
• user cannot see details (in fact, hide tedious coding details)
• user does not need to see details
• user does not want to see details
• coder creates details, and designs interface
26
Functions
▪ in programming, divide code into modules that are:
• self-contained
• used to break up code into logical pieces
• intended to be reusable
• used to keep code organized
• used to keep code coherent (readable and understandable)
▪ in this lecture, achieve decomposition with functions
▪ in a few lectures, achieve decomposition with classes
▪ decomposition relies on abstraction to enable
construction of complex modules from simpler ones
27
Functions
write reusable pieces/chunks of code, called functions
▪ functions are not run until they are “called” or
“invoked” in a program
▪ compare to code in a file that runs as soon as you load it
▪ function characteristics:
• has a name (there is an exception we won’t worry about)
• has (formal) parameters (0 or more)
• has a docstring (optional but recommended)
◦ a comment delineated by “”” (triple quotes) that provides a
specification for the function
• has a body
• returns something (typically)9/15/
28
Functions
Define Function:
def sinc(x):
y = np.sin(x)/x
return y
def is_even( i ):
"""
Input: i, a positive int
Returns True if i is even,
otherwise False
"""
print("inside is_even")
return i%2 == 0
29
Functions
Function name
30
Functions
31
Functions
ENVIRONMENTS
▪ global environment is place where user interacts with
Python interpreter
• contains bindings of variables to values from loading files or
interacting with interpreter
▪ invoking a function creates a new environment (or frame)
• formal parameters bound to values passed in
• body of function evaluated with respect to this frame
• frame inherits bindings from frame in which function called
9/
32
Functions VARIABLE SCOPE
33
Functions
34
Functions
35
Functions
EXERCISE How many total lines of output will
def add(x,y):
return x+y show on the console if you run this
def mult(x,y): code (as a file)?
print(x*y)
A) 0
add(1,2)
print(add(2,3))
B) 2
mult(3,4) C) 4
print(mult(4,5))
D) 5
36
Functions
37
Functions
Positional and keyword arguments
Consider this function:
38
Functions
Positional and keyword arguments
Now consider this function:
def circle(r, x0=0.0, y0=0.0, n=12):
theta = np.linspace(0., 2.*np.pi, n, endpoint=False)
x = r * np.cos(theta)
y = r * np.sin(theta)
return x0+x, y0+y
The default values of the arguments x0, y0, and n are specified in the argument of
the function definition in the def line. Arguments whose default values are
specified in this manner are called keyword arguments, and they can be omitted
from the function call if the user is content using those values.
39
Conclusions
It is a long week (in terms of the notes and
what we covered)
Before answering the HW2 be sure to go over
Chapter 6 and 7 of Introduction to Python
for Science
Read on
◦ 7.1.2 Fast array processing in user-defined functions
np.where function (pg. 119)
◦ 7.1.5 Variable number of arguments (pg. 122)
Try all the examples and exercises given in the end of
each chapter.
40