You are on page 1of 164

DIS-UG

Programming of Information Centre


Applications
(INFS 429 )
Course Lecturer:
Dr. Awudu Karim
Email: kawudu@ug.edu.gh
Tel: 0507142013
Objectives for this lecture

• Introduce general ideas about computer programming


• Alley fears of computer programming
• Whip up interest in computer programming
• Introduce the Python programming language
COMPUTER PROGRAMMING

INTRODUCTION
Do We Really Need To Program?
• Computers are built for one purpose - to do things for us

• But we need to speak their language to describe what we want done

• Programmers/Developers create the programs (instructions) put into the


computers and users just use them.

• Isn’t it better to have our independence, security, privacy, efficiency and


flexibility back in our own hands? Of course, it is! ☺ ☺ ☺

✓ Yes we do ☺ ☺ ☺
Do We Really Need To Program?

• Relatively smaller number of developers as against users (entities)

• “Mushroom effect”

• “Bottleneck problem”

✓ Yes we do ☺

✓ Parallel development is the way to go!


Programming For Information Experts
• Efficient information applications/software

• Cheaper and faster development of information apps

• Both users and developers

• Control, authority and ownership

• Competitive advantage

• Research and development

• Patents, copyrights – intellectual property in ISs


What is Code? Program? Software?
• A sequence of stored instructions that are executed by the computer

- It is a little piece of our intelligence in the computer

- Writing instructions for the computer to execute is called programming

• A piece of creative art - particularly when we do a good job on user


experience

• An implementation of an algorithm in a programming language

• Algorithm

- Plan, step-by-step way of solving a problem/performing a task.


Program/Software Development

• Major components of a program/software

➢ User interface: GUI, UI/UX


➢ Arithmetic, logical and control code: main code
➢ Input and output: I/Os, visualizations, etc
➢ Resources: files/database, internet/network, etc
Programming versus Natural Language

•Natural languages are spoken by human beings, while programming


languages are intended for computers/digital machines.

•Natural languages are used for communication between human beings


while programming languages enable human beings to interact with the
computers/digital machines.

•Both languages share similarities, such as grammar (natural


language)/syntax (programming language), and the existence of a basic
structure.
Examples of Programming Languages

Python, C, C++, C#, Java, Visual Basic, VB.Net, Pascal, Ruby, Html,
CSS, JavaScript, PHP, Perl, SQL, R, Fortran, Cobol, Swift, BASIC,
ASP, GO, Kotlin, NoSQL, Rust, Scala, TypeScript, etc
The Python Programming Language
Getting Started with Python
Installing Python
•Any version of Python 3 is acceptable for this course. Macintosh computers
already have Python preinstalled so you should be able to use it.

•For Windows OS, you may download and install Python 3.x from:

•http://www.python.org/download/

•During Python installation, make sure to check the "Add Python 3.x to PATH"
so that you can type python at the command line/prompt to run Python.

•Atom Text Editor - Please download and install Atom from this site:

•http://atom.io
After Installing Python

Testing python: chevron prompt >>>


test script …
Python is an interpreted and high level
computer programming language. Python
programmers are known as Pythonistas. The
language was initially developed by Guido van
Rossum.
Syntax Errors
• We need to learn the grammar of Python language (syntax) so we can
communicate our instructions to Python. In the beginning we will make lots of
mistakes.

• When you make a mistake, the computer throws a syntax error (analogous to
grammatical error) message at you

• A syntax error in Python is also called traceback.

• You must remember that you are more intelligent and can learn. The computer is
simple and very fast, but cannot “learn”. So it is easier for you to learn Python
than for the computer to learn English, hahaha ☺☺☺.
Talking to the Computer in Python

• 2 ways: interactive mode and scripts


Interactive: through cmd/chevron prompt, shell or terminal

Script: through text editors such as Python IDLE, Atom, PyCharm, etc
Python Interactive Mode
csev$ python3
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2020, 21:12:44) [GCC
4.2.1 (Apple Inc. build 5666) (dot 3)] on darwinType "help",
"copyright", "credits" or "license" for more information.
>>>
Chevron prompt Mac

C:\Users\Karim>python
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC
v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
Chevron prompt
Windows
Python Interactive Mode
C:\Users\Karim>python
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924
64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> x = 1
>>> print(x)
1
>>> x = x + 1 This is a good test to make sure that you have
Python correctly installed. Note that quit() also
>>> print(x)
ends the interactive session when used.
2
>>> exit()
Python Scripts

What Do We Write?
Elements of Python

• Vocabulary / Words – Variables (storage spaces), constants, data


types, data structures and Reserved words etc

• Sentence structure - syntax (grammatical) patterns


• Story structure - writing a program for a purpose
Reserved Words
You cannot use reserved words as variable names / identifiers

False class return is finally


None if for lambda continue
True def from while nonlocal
and del global not with
as elif try or yield
assert else import pass
break except in raise
Lines of Code

x = 2 Assignment statement
x = x + 2 Assignment with expression
print(x) Print function

Variable Operator Value/Constant Function


Python Scripts
• Interactive Python is good for experiments and programs of 3-4 lines
long.

• Most programs are much longer, so we type them into a file and tell
Python to run the commands/instructions in the file.

• In a sense, we are “giving Python a script”.

• As a convention, we add “.py” as the suffix at the end of these file


names to indicate they contain Python codes.
Interactive versus Script
• Interactive
- You type instructions or commands directly to Python one line at a
time and it responds back

• Script
- You enter a sequence of statements (lines) into a file using a text
editor and tell Python to execute the statements/instructions in the file
after it has been saved
Program Flow

• A program is a sequence of steps to be done in order.


• Some steps are conditional - they may be skipped.
• Sometimes a step or group of steps is/are to be repeated
(loop/iteration).

• Sometimes we store a set of steps to be used over and over as


needed at several places throughout the program (functions).
Sequential Steps

x=2 Program:
Output:
print(x) x = 2
print(x) 2
x=x+2 x = x + 2 4
print(x)
print(x)

When a program is running, it flows from one step to the next. As


programmers, we set up “paths” for the program to follow.
Conditional Steps
x=5

Yes
x < 10 ?

print('Smaller') Program:
No Output:
x = 5
Yes if x < 10: Smaller
x > 20 ? print('Smaller') Done
if x > 20:
print('Bigger') print('Bigger')
No
print(‘Done')

print(‘Done')
Repeated Steps
n=5

Yes Output:
No
n>0? Program:
5
print(n) n = 5 4
while n > 0 :
print(n)
3
n = n -1 n = n – 1 2
print('Blastoff!') 1
Blastoff!
Loops (repeated steps) have iteration variables that
print('Blastoff')
change each time through a loop.
Example of a Python Program for creating random passwords
import random

def passcode(): # create the function


chars =
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789@!$%^#&*(_)
'
length = input('\n\n\n please enter length of password needed: ')
length = int(length)

for p in range(1):
password = ''
for c in range(length):
password += random.choice(chars)
print('\n Your new password is: '+password)
print('*********************************************\n\n')

passcode() # call the function


The End of This Lecture

Thank you ☺☺
Variables, Expressions,
Comments, Data types and
User inputs
Lecture 2
Constants
• Fixed values are called “constants”. There are 2 kinds:
1. Numeric constants (numbers) are written without quotation marks
2. String constants (letters, words) are written in single quotes (‘ ‘) or double
quotes (“ “).
X = 123 #numeric constant >>> print(X)
Print(x) 123
>>> print(Y)
Y = 98.6 #numeric constant 98.6
Print(y) >>> print(Z)
Hello world
Z = ‘Hello world’ #string constant
Print(z)
Variables
• A variable is a named location in memory where a program(mer) can store data
and later retrieve using the variable “name” when the program is running.

System Unit
Input Central
Devices Processing
Unit
Secondary
Memory

Output Main Variable (stores data in memory)


Devices Memory
Variables
• A variable is a named location in memory where a program(mer) can store data
and later retrieve using the variable “name” when the program is running

• Programmers get to choose (define) the names of the variables

• You can change the contents of a variable in a later statement

x = 12.2 x 12.2
y = 14
y 14
Variables
• A variable is a named location in memory where a program(mer) can store data
and later retrieve using the variable “name” when the program is running

• Programmers get to choose (define) the names of the variables

• You can change the contents of a variable in a later statement

x = 12.2 x 12.2 100


y = 14
x = 100 y 14
Python Variable Name Rules
• Must start with a letter or underscore ( _ )

• Could consist of letters, numbers, and underscores

• Case Sensitive

Good: spam eggs spam23 _speed

Bad: 23spam #sign var.12 etc.

Not same: spam Spam SPAM etc.


Mnemonic Variable Names

• Since we programmers are given the choice to choose our


variable names, there is a bit of “best practice” to it.
• We name variables to help us remember what we intend to store
in them (“mnemonic” = “memory aid”)
• Mnemonic variable names are clearer and easy to reference
Examples of Mnemonic Variable Names
1
x1q3z9ocd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd
print(x1q3p9afd)

What is this piece


of code doing?
Examples of Mnemonic Variable Names
1 2
x1q3z9ocd = 35.0 a = 35.0
x1q3z9afd = 12.50 b = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd c = a * b
print(x1q3p9afd) print(c)

What are these pieces


of code doing?
Examples of Mnemonic Variable Names
1 2
x1q3z9ocd = 35.0 a = 35.0
x1q3z9afd = 12.50 b = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd c = a * b
print(x1q3p9afd) print(c)

3
hours = 35.0
What are these pieces rate = 12.50
of code doing? pay = hours * rate
print(pay)
Mnemonic variable names make
codes easy to understand
Statements
Parts of a Line of Code (Statement)
•A line of code may consist of:
1. Variable, Operator and Constant/value (Assignment)
2. Variables, Operators and Constants/values (Expression)
3. Function (Call)
Remember: both functions and expressions can be assigned to variables

Examples:
1. x = 2
Variable Operator Constant/value
2. x = x + 2
Variable Operator Variable Operator Constant/value
3. print(x)
Function
Assignment Statements
• We assign something to a variable using the assignment operator (=)

• An assignment statement consists of a value or function or an


expression on the right-hand side and a variable to store the result on
the left hand side

x = ‘My name is Ama’ (Value)

x = 3.9 * x * ( 1 - x ) (Expression)

x = input(‘Please enter name’) (Function)


X = 0.6
A variable is a memory location
x 0.6
used to store a value (0.6)

0.6 0.6
x = 3.9 * x * ( 1 - x )

0.4

The right side is an expression.


0.936
Once the expression is evaluated, the
result is placed in (assigned to) x.
A variable is a memory location used to
store a value. The value stored in a x 0.6 0.936
variable can be updated by replacing the
old value (0.6) with a new value (0.936).
0.6 0.6
x = 3.9 * x * ( 1 - x )

0.4

Variables are replaceable/changeable! 0.936


Reserved Words

Remember you cannot use reserved words as variable names

False class return is finally


None if for lambda continue
True def from while nonlocal
and del global not with
as elif try or yield
assert else import pass
break except in raise
Expressions…
Numeric Expressions

• Because of the lack of typical Operator Operation


mathematical symbols on computer + Addition
keyboards - we use “keyboard-
equivalent symbols” to express the - Subtraction
classic math operations * Multiplication

• Asterisks is multiplication / Division

** Power
• Exponentiation (raising to a power)
looks different than in math % Remainder
Numeric Expressions

>>> x = 2 >>> j = 23
>>> x = x + 2 >>> k = j % 5 Operator Operation
>>> print(x) >>> print(k)
+ Addition
4 3
>>> y = 440 * 12 >>> print(4 ** 3) - Subtraction
>>> print(y) 64
* Multiplication
5280
>>> z = y / 1000 4 R3 / Division
>>> print(z) 5 20 ** Power
5.28 3 % Remainder

3
Order of Evaluation

• When we put operators together - Python must know which one to


do first

• This is called “operator precedence”

• Which operator “takes precedence” over the others?

x = 1 + 2 * 3 - 4 / 5 ** 6
Operator Precedence Rules
Highest precedence rule to lowest precedence rule:

• Parentheses are always respected


Parenthesis
• Exponentiation (raise to a power) Power
Multiplication
• Multiplication, Division
Addition/Subtraction
• Division, and Remainder Left to Right
• Addition and Subtraction

• Left to right
1 + 2 ** 3 / 4 * 5
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print(x)
11.0 1 + 8 / 4 * 5
>>>
1 + 2 * 5
Parenthesis
Power
Multiplication
1 + 10
Division
Addition
Left to Right 11
Operator Precedence
Parenthesis
Power
• Remember the rules from top to bottom Multiplication
Division
Addition
• When writing code - use parentheses
Left to Right
• When writing code - keep mathematical expressions simple enough
that they are easy to understand

• Break long series of mathematical operations up to make them


more clear
Data Types
What Does “Type” Mean?

• In Python variables and constants


have a “type” >>> d = 1 + 4
>>> print(d)
• Python knows the difference between 5
an integer number and a string >>> e = 'hello ' + 'there'
>>> print(e)
• For example “+” means “addition” if hello there
something is a number and
“concatenate” if something is a string
concatenate = put together
Basic Data Types in Python

• String (str)
• Characters (texts or letters, digits, symbols, etc)

• Number (int, float)


• Integer numbers (whole numbers without the decimal points, eg. 12)
• Floating numbers (numbers with the decimal points, eg. 12.50)
For Example - Type Matters

>>> e = 'hello ' + 'there'


• Python knows what “type” means >>> e = e + 1
Traceback (most recent call last):
• Some operations are prohibited File "<stdin>", line 1, in
<module>TypeError: Can't convert
• Eg. you cannot add a number to 'int' object to str implicitly
>>> type(e)
a string <class'str'>
>>> type('hello')
• We can ask Python what type <class'str'>
something is by using the type() >>> type(1)
<class'int'>
function >>>
Types of Numbers

>>> xx = 1
• Numbers have two main types >>> type (xx)
<class 'int'>
- Integers are whole numbers:
>>> temp = 98.6
-14, -2, 0, 1, 100, 401233 >>> type(temp)
<class'float'>
- Floating Point Numbers have
>>> type(1)
decimal parts: -2.5 , 0.0, 98.6, 14.0 <class 'int'>
>>> type(1.0)
• There are other number types - they
<class'float'>
are variations on float and integer
>>>
Type Conversions
>>> print(99.0 + 100)
199.0
• When you put an integer and >>> i = 42
floating point in an >>> type(i)
expression, the integer is <class'int'>
implicitly converted to a float >>> f = float(i)
>>> print(f)
• You can explicitly control this 42.0
>>> type(f)
with the built-in functions int()
<class'float'>
and float()
>>>
Integer Division

>>> print(10 / 2)
5.0
>>> print(9 / 2)
Integer division produces a floating 4.5
point result >>> print(99 / 100)
0.99
>>> print(10.0 / 2.0)
5.0
>>> print(99.0 / 100.0)
0.99
This was different in Python 2.x
>>> example = '123'
>>> type(example)
<class 'str'>
String Conversions >>> print(example + 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object
• You can also use int() and to str implicitly
>>> example = int(example)
float() to convert between >>> type(example)
strings and integers <class 'int'>
>>> print(example + 1)
• You will get an error if you try to 124
>>> n = 'hello bob'
convert the string containing a >>> n = int(n)
mixture of numeric and Traceback (most recent call last):
File "<stdin>", line 1, in <module>
characters ValueError: invalid literal for int()
with base 10: 'x'
Practice 1 & 2 (Interactive mode)
1. Declare 3 variables, one each to store 567, 1004.58 and
My first practice. Display the output on the screen.

2. Write a program to calculate the result of 2 x 5 / 2 x 3 - 4.


User Inputs
User Input

• We can instruct Python to


nam = input('Who are you? ')
pause and read data from print('Welcome', nam)
the user using the input()
function
• The input() function
returns a string Who are you? Karim
Welcome Karim
Converting User Input

• If we want to read an input as a number from the user, we must


first convert it from a string to a number using a type conversion
function

inp = input(‘Enter Year of birth')


yob = int(inp)
yob = 2022 - yob
print(‘You are',yob, ‘years old')
Practice 3 (Interactive mode)

1. Write a simple program to prompt a user to enter the


number of books he/she reads in a month. Output the
total number of books he/she reads in a year with a sweet
message.

Hints: input() function handles user data as string☺


Comments in Python
• Anything after a # is ignored by Python, can be inserted before, or
at the beginning, or ending, of a line of code.

• Why comment?

- Describe what is going to happen in a line or sequence of code

- Document who wrote the code or other ancillary information

- Turn off a line of code - perhaps temporarily

- Etc
# Get the name of the file and open it
name = input('Enter file:')
handle = open(name, 'r')

# Count word frequency


counts = dict()# create a dictionary
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word,0) + 1

# Find the most common word


bigcount = None
bigword = None
for word,count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
# this line of code is ignored. print(word, count)

# All done
print(bigword, bigcount) # display results
Summary

• Type • Integer Division

• Statements • Conversion between types

• Variables (mnemonic) • User input

• Operators • Comments (#)

• Operator precedence
Exercise 1

Write a small program to prompt a librarian for hours worked


and rate per hour to compute their bonus pay in interactive
mode. Comment your lines of code.

Hints:
Use 35 hours worked, at the rate of 2.75.
The bonus due would be 96.25.
The End of the Lecture ☺

Thanks
Conditional Statements
Lecture 3
Conditional Statements (Decision)
• Conditionals or Conditional statements – Are used at a point in coding where
decisions (either this or that) are to be made

• The general structure of conditional statements is:


Conditional keyword
Logical test (expression)
• if condition : Colon
do this instruction if true,
• else:
do that instruction if false
Conditional (Decision) Statements

• Example:
• if age >= 18:
print(‘Please you’re eligible to vote’)
• else:
print(‘Sorry you cannot vote’)
• Conditionals/decisions are used to let the program execute specific instructions (in
other words do or skip some instructions/lines)

• Controls the flow of program (how the program should proceed)

• The condition in a conditional statement is created with comparison/logical operators


Comparison (Logical) Operators

• Comparison (Logical) expressions Operator Meaning


ask a question and produce either < Less than
Yes or No result which we use to
control program flow <= Less than or Equal to
== Equal (Equivalent) to
• Boolean expressions also evaluate to >= Greater than or Equal to
True or False (single-way decisions)
> Greater than
• Comparison operators look at values != Not equal (equivalent) to
of variables but do not change them

Remember: “=” is used for arithmetic assignment, it


is not a logical operator when used alone.
Examples of Conditionals
x = 5 OUTPUTS
if x == 5: Equal to 5
print('Equal to 5')
if x > 4: Greater than 4
print('Greater than 4')
if x >= 5:
print('Greater than or Equals 5') Greater than or Equals 5
if x < 6:
Less than 6
print('Less than 6')
if x <= 5:
print('Less than or Equal to 5')
if x != 6 : Less than or Equal to 5
print('Not equal to 6') Not equal to 6
x=5
Conditional Statements

Yes
x < 10 ?
Program:
No print('Smaller') Output:
x = 5
if x < 10: Smaller
Yes print('Smaller')
x > 20 ? Hurray
if x > 20:
No print('Bigger') print('Bigger')
else:
print(‘Hurray') print(‘Hurray')
Statement or Line Indentation

• Increase indent by 4 spaces after an if condition or loop statement (after


the colon before adding instructions to perform if the condition is true )

• Maintain indent to indicate the scope of the block (which lines are
affected by the if (same for loops))

• Remove indent back to the level of the if statement or loop statement to


indicate the end of the block

• Blank lines are ignored - they are not affected by indentation

• Comments are not affected by indentation


Warning: Do Not Use Tabs!!
• Atom automatically uses spaces for files with ".py" extension (nice!)

• Most programming text editors can turn tabs into spaces either
automatically or by settings- make sure to enable this feature if you need
to

• Python cares a *lot* about how far a line is indented. If you mix tabs and
spaces, you may get “indentation errors” even if everything looks fine

• Do not use the Tab key to create indent; instead use the spacebar to
create indent. It will save you unnecessary ‘headaches’ and tracebacks.
Indent after the if – else statement and
remove indent to indicate end of block. Example below:

x = 5
if x > 2:
print('Bigger than 2')
print('Still bigger')
else:
print('Done with 2')
print('All Done')
Think About Blocks (as begin-end)

x = 5
if x > 2:
print('Bigger than 2')
print('Still bigger')

else:
print('Done with 2')

print('All Done')
Visualizing Blocks
x=4

x = 4 else yes
x>2
if x > 2:
print('Bigger') print(‘Smaller') print('Bigger')
else:
print('Smaller')

print('All done') print('All done')


One-Way Decisions x=5

x = 5 Yes
x == 5 ?
print('Before 5') Before 5
if x == 5 : No print('Is 5’)
print('Is 5') Is 5 print('Still 5')
print('Is Still 5') print(‘And 5')
Is Still 5
print(‘And 5')
print('After 5')
And 5
After 5 Yes
print('Before 6') x == 6 ?
if x == 6 : Before 6 No print('Is 6’)
print('Is 6') print('Still 6')
print('Is Still 6')
print(‘And 6') print(‘And 6')
print('After 6') After 6
print(‘Afterwards 6’)
Two-way Decisions

x=4

• Sometimes we want to do
one thing if a logical no yes
x>2
expression is true and
something else if the
expression is false print('Not bigger') print('Bigger')

• It is like a junction on the


road - we must choose one
or the other path but not both print('All Done')
at the same time
Two-way Decisions with if else

x=4
x = 4

if x > 2: else yes


x>2
print('Bigger')
else:
print('Smaller') print(‘Smaller') print('Bigger')

print('All done')

print('All done')
Multi-way (Connected) Conditional Statements
x=5

x = 5 yes
x<2 print('small')
if x < 2:
print('small') elif
elif x < 10: yes
x < 10 print('Medium')
print('Medium')
else: else
print('LARGE') print('LARGE')
print('All done')

print('All Done')
Multi-way Statements x=0

yes
x<2 print('small')
x = 0
if x < 2: elif
print('small') yes
elif x < 10: x < 10 print('Medium')
print('Medium') else
else:
print('LARGE')
print('LARGE')
print('All done')
print('All Done')
Multi-way Statements x=5

yes
x<2 print('small')
x = 5
if x < 2 : else
print('small') yes
elif x < 10 : x < 10 print('Medium')
print('Medium') else
else :
print('LARGE')
print('LARGE')
print('All done')
print('All Done')
Multi-way Statements x = 20

yes
x<2 print('small')
x = 20
if x < 2 : elif
print('small') yes
elif x < 10 : x < 10 print('Medium')
print('Medium') else
else : print('LARGE')
print('LARGE')
print('All done')
print('All Done')
Multi-way Statements

if x < 2:
print('Small')
x = 5 elif x <= 10:
if x < 2: print('Medium')
print('Small') elif x <= 20:
elif x < 10: print('Big')
print('Medium') elif x <= 40:
else: print('Large')
print(‘Large’) elif x <= 100:
print('Huge')
print('All done') else:
print('Gargantuan')
Multi-way Puzzles

Which statements will never run regardless of the value for x?

if x < 2: if x < 2:
print('Below 2') print('Below 2')
elif x >= 2: elif x < 20:
print('Two or more') print('Below 20')
else: elif x < 10:
print('Something else') print('Below 10')
else:
print('Something else')
Assignment 1
Write a simple school grading program to accept a
student name, course and score, then outputs the
student’s name, course and grade.
Hint: Remember the input() function returns user data
as string.

Sample code for this program provided!


Rewrite the code in assignment 1 with your own variable
names and output messages.
x = 42
Nested Decisions
yes
x>1

no print('More than one’)


x = 42
if x > 1 : yes
print('More than one') x < 100
if x < 100 :
no
print('Less than 100') print('Less than 100')
print('All done')

print('All Done')
The try / except Structure

• You surround a dangerous section of code with try and except


• If the code in the try works - the except is skipped
• If the code in the try fails - it jumps to the except section
Traceback (most recent call last):
Val_1 = 'Hello Bob'
File "C:/Users/Karim/Desktop/exp3.py",
Val_2 = int(val_1) line 3, in <module>
print('First', val_2) istr = int(astr)
astr = '123' ValueError: invalid literal for int() with base
anum = int(astr) 10: 'Hello Bob'
print('Second', anum) >>>

All
Done
Traceback (most recent call last):
File "C:/Users/Karim/Desktop/exp3.py",
line 3, in <module>
istr = int(astr)
ValueError: invalid literal for int() with base
The 10: 'Hello Bob'
program >>>
stops
here Val_1 = 'Hello Bob' All
Val_2 = int(val_1) Done
print('First', istr)
astr = '123'
istr = int(astr)
print('Second', istr)
When the first conversion fails - it
astr = 'Hello Kofi'
just drops into the except: clause
try:
and the program continues.
istr = int(astr)
print(istr)
except:
anum = -1 Conv. error in first
print('Conv. error in first statement statement -1
',anum) Second 123
>>>
astr2 = '123'
try:
isnum = int(astr2)
except:
anum2 = -1
When the second conversion
print('Conv. error in second
succeeds - it just skips the except:
statement',anum2)
clause and the program continues.
print('Second statement is fine', isnum)
astr = 'Bob'
try / except try
print('Hello')
astr = 'Bob'
try:
print('Hello') istr = int(astr)
istr = int(astr)
print('There')
except: print('There')
istr = -1 except
istr = -1
print('Done', istr)

print('Done', istr)
Sample try / except

rawstr = input('Enter a number:')


try: OUTPUT
ival = int(rawstr)
except: Enter a number:42
ival = -1 Nice work
Enter a number:forty-two
if ival > 0 : Not a number
print('Nice work')
else:
print('Not a number')
Summary
• Comparison operators • Nested Decisions
== <= >= > < !=
• Multi-way decisions using elif
• Indentation
• try / except to compensate for
• One-way Decisions errors
• Two-way decisions:
if: and else:
Exercise 3

Write a small program to prompt a librarian for number of


hours worked and the rate per hour to compute her/his pay.

Use 350 hours, at the rate of 20.75.


Hints: Pay would be 7262.5

Sample code for this program provided!


Rewrite the code in exercise 3 with your own
variable names and output messages
Exercise 4

Rewrite your pay program to give the employee


1.5 times the hourly rate for hours worked above
40 hours.
Sample code for this
Hints: Enter Hours: 45 program provided!
Enter Rate: 10
Rewrite the code in
Pay: 475.0 exercise 4 with your
own variable names
475 = (40 * 10 ) + (5 * (1.5*10)) and output messages
Exercise 5

Rewrite your pay program using try and except so


that your program handles non-numeric input
gracefully.

Hints: Enter Hours: 20


Enter Rate: nine
Error, please enter a numeric value

Enter Hours: forty


Error, please enter a numeric value
The end of the lecture ☺
Flow Control
(Loops and Iterations)
Lecture 4
Loops
• A Loop is a repetition of a set or group of instructions in a cyclical
manner. Often it has an iteration variable (ivar) that control how many
times the loop will run. The iteration variable decrements or
increments until a condition evaluates to false (or true depending on
the scenario) in order to end the loop.

• In Python there are 2 main loops; the while and for loops.
The While Loop
• While loops are called “indefinite loops” because they keep going until
a logical condition becomes false

• The while loop structure:

while a condition is true:


1. do the instructions
2. decrement/increment the iteration variable
3. repeat these steps 1 and 2 until the condition becomes false and
then end the loop
The While Loop
n=5
condition
False while True
n>0 instruction to do
print(n) while condition is
true

n = n -1 Iteration variable

print('Blastoff')
The While Loop
Output:
Program:
5
n=5
while condition 4
while n > 0:
while true 3
instruction print(n)
2
iteration variable n=n–1
1
print('Blastoff!')
while false Blastoff!
n=5 An Infinite while Loop
False while True
n>0 n=5
while n > 0:
print('Lather')
print('Lather')
print('Rinse')
print('Rinse') print('Dry off!')

print('Dry off!') What is wrong with this loop?


n=0 Another while Loop
False while True
n>0 n=0
print('Lather') while n > 0:
print('Lather')
print('Rinse')
print('Rinse')
print('Do nothing!')

print('Do nothing!') What is this loop doing?


Breaking Out of a Loop
• The break statement ends the current loop and jumps to the
statement immediately following the loop

• It is like a loop test that can happen anywhere in the body of the
loop

while True:
words = input('Enter something') > hello there
if words == 'stop': hello there
break > you’re cool
print(words) you‘re cool
> stop
print('Done!')
Done!
Exiting Out of an infinite While Loop (While
loop without an Iteration variable)
• The break statement exits the current loop and jumps to the next
statement immediately following the loop body

• It is like a loop test that can happen anywhere in the body of the
loop
while True:
line = input(‘Enter something to continue >>> hello there
or stop to end') hello there
if line == ‘stop': >>> you’re cool
break you‘re cool
print(line) >>> stop
print('Done!') Done!
Yes
True ?

words = Input(' ‘)
while True:
words = input(' Enter Yes
words==‘stop’ break
something ')
if words == ‘stop' : No
break
print(words) Print(words)
print('Done!')

print('Done')
Restarting an Iteration with continue

The continue statement ends the current iteration and jumps to the
top of the loop and starts the next iteration
while True:
words = input(' ') >>> hello there
if words[0] == '#': hello there
continue >>> # don't print this
>>> print this!
if line == 'stop':
print this!
break >>> stop
print(line) Done!
print('Done!')
Restarting an Iteration with continue

The continue statement ends the current iteration and jumps to the
top of the loop and starts the next iteration
while True:
line = input('') > hello there
if line[0] == '#': hello there
continue > # don't print this
> print this!
if line == 'stop':
print this!
break > stop
print(line) Done!
print('Done!')
The For Loops

• The For loops are called “definite loops” because they run for an exact
number of times (ie. They iterate over a finite set of items or sequence).

• The For loop structure:

for iteration variable on a finite set of items/range of set:


1. do the instructions for each item in the set
A Simple For Loop

for ivar in [5, 4, 3, 2, 1] :


print(ivar)
print('Blastoff!') Yes No
Done? next item (ivar)

Output print(ivar)
5
4
3
2
1 print('Blast off!')
Blastoff!
A For Loop with Range function
0
1
for ivar in range(6):
print(ivar) 2
3 Yes No
print('Blastoff!') Done? next item (ivar)
4
5
Blastoff! print(ivar)
1
for ivar in range(1, 6): 2
print(ivar)
3
print('Blastoff!') 4 print('Blast off!')
5
Blastoff!
A Simple password countdown using For
Loop and the Range function
#A basic password countdown

for ivar in range(4): # A for-loop with the range function


passw = input("Please enter password \n")
if passw != "ask":
print('locked')
else:
print('Unlocked')
break
A Simple For Loop
for ivar in 'friends':
print(ivar) Yes No
print('Blastoff!') Done? next item (ivar)
Output
f print(ivar)
r
i
e
n
d print('Blastoff!')
s
Blastoff
A Simple For Loop ivar = 5

for ivar in [5, 4, 3, 2, 1]: print(ivar) 5


print(ivar) ivar = 4
print(ivar) 4
No ivar = 3
Yes
Done? next i item
print(ivar) 3

print(i) ivar = 2
print(ivar) 2
ivar = 1
print(ivar) 1
A Simple For Loop
Iteration
variable Set of items to iterate over
5
for ivar in [5, 4, 3, 2, 1]: 4
print(ivar) 3
print('Blastoff!') 2
1
Blastoff!
A For Loop with Strings

friends = ['Joseph', 'Ama', 'Sally']


for each_friend in friends : Happy New Year: Joseph
print('Happy New Year:', each_friend) Happy New Year: Ama
print('Done!') Happy New Year: Sally
Done!
Looking at the For loop
• The iteration variable
“iterates” through the set / sequence of
sequence (set) items
Iteration variable
• The block (body) of code is
executed once for each
value in the sequence for ivar in [5, 4, 3, 2, 1]:
print(i)
• The iteration variable moves
through all of the values in
the sequence
Looking at the For loop
No
Yes
Done? Move i ahead • The iteration variable “iterates”
through the sequence (set)

print(i) • The block (body) of code is


executed once for each value in
the sequence

• The iteration variable moves


through all of the values in the
for ivar in [5, 4, 3, 2, 1]:
sequence
print(ivar)
Loop Idioms:
What We Do in Loops

Note: Even though these examples are simple,


the patterns apply to all kinds of loops
Looping Through a Set

Before
print('Before') 9
for each_thing in [9, 41, 12, 3, 74, 15]: 41
print(each_thing) 12
print('After') 3
74
15
After
What is the Largest Number?
What is the Largest Number?

3
What is the Largest Number?

41
What is the Largest Number?

12
What is the Largest Number?

9
What is the Largest Number?

74
What is the Largest Number?

15
What is the Largest Number?
What is the Largest Number?

3 41 12 9 74 15
What is the Largest Number?

largest_so_far -1
What is the Largest Number?

largest_so_far 3
What is the Largest Number?

41

largest_so_far 41
What is the Largest Number?

12

largest_so_far 41
What is the Largest Number?

largest_so_far 41
What is the Largest Number?

74

largest_so_far 74
What is the Largest Number?

15

74
What is the Largest Number?

3 41 12 9 74 15

74
Finding the Largest Value

Before: -1
largest_so_far = -1 9
print('Before:', largest_so_far) 41
for a_number in [9, 41, 12, 3, 74, 15]: 41
if a_number > largest_so_far : 41
largest_so_far = a_number 74
print(largest_so_far) 74
print('After everything:', largest_so_far) After everything:
74
We make a variable that contains the largest value we have seen so far. If the current
number we are looking at is larger, then it is the new largest value we have seen so far.
More Loop Patterns…
Counting in a Loop

Before counting: 0
count = 0 19
print('Before counting:', count) 2 41
for value in [9, 41, 12, 3, 74, 15]: 3 12
count = count + 1 43
print(count, value) 5 74
print('After counting:', count) 6 15
After counting: 6
To count how many times we execute a loop, we introduce a counter variable
that starts at 0 and we add one to it each time the loop runs.
Summing in a Loop
Start: 0
sum = 0 9
print(‘Start:', sum) 50
for value in [9, 41, 12, 3, 74, 15]: 62
sum = sum + value 65
print(sum) 139
print('After everything:’, sum) 154
After everything:
154
To add up a value we encounter in a loop, we introduce a sum variable that
starts at 0 and we add the value to the sum each time through the loop.
Finding the Average in a Loop
count = 0
sum = 0
average = 0 Start: 0 0
print(‘Start:', count, sum) 199
for value in [9, 41, 12, 3, 74, 15] : 2 50 41
count = count + 1 3 62 12
sum = sum + value 4 65 3
average = sum / count 5 139 74
print(count, sum, value) 6 154 15
print('Average is:', average) Average is: 25.666

An average just divides sum by count when the loop is done.


Filtering in a Loop

print(‘Starting')
for value in [9, 41, 12, 3, 74, 15]: Starting
if value > 20: Large number 41
print('Large number',value) Large number 74
print(‘Finished!') Finished!

We use an if statement in the loop to catch / filter the


values we are looking for.
Filtering in a Loop

print('Searching')
for name in ['Akua', 'Yaw', 'Esi', 'Efe', 'Ama']: Searching
if name == 'Esi':
print(‘Name found:', name) Name found: Esi
print('Finished!')
Finished

We use an if statement in the loop to catch / filter the


values/string we are looking for.
Search Using a Boolean Variable

found = False
print('Found:', found)
Found: False
for name in ['Akua','Yaw','Esi','Efe','Ama']:
if name == 'Esi':
Found: True
found = True
print('Found:’, found)
Finished
print('Finished')

If we just want to search and know if a value was found, we use a variable that
starts at False and is set to True as soon as we find what we are looking for.
Finding the Smallest Value in Data set

min_val = 5
#print(‘Starting:', smallest_so_far)
for value in [9, 41, 12, 3, 74, 15]:
if value < min_val:
min_val = value
print(‘Minimum value:', min_val)
Finding the Smallest Value in Data set

min_val = 5
#print('Before', smallest_so_far)
for value in [9, 41, 12, 3, 74, 15]: Output
if value < min_val:
min_val = value Minimum value: 3
print(‘Minimum value:',min_val)
Finding the Smallest Value (Better way)

smallest = None 9
for value in [9, 41, 12, 3, 74, 15]: 9
if smallest is None: 9
smallest = value 3
elif value < smallest: 3
smallest = value 3
print(smallest) Smallest is
print(‘Smallest is', smallest) 3
The first time through the loop smallest is None, so we take the first value to be
the smallest. After that compare current value with the next item sequentially
The is and is not Operators

smallest = None • Python has an is operator


print('Before') that can be used in logical
for value in [3, 41, 12, 9, 74, 15]: expressions
if smallest is None:
• Implies “is the same as”
smallest = value
elif value < smallest: • Similar to, but stronger than
smallest = value ==
print(smallest, value)
• is not also is a logical
print('After', smallest) operator similar to !=
Practical applications of loop in real world
solutions
•The ATM software uses a loop to process transactions until the user
chooses to end the session

• Password software for smart phones for instance allows a user to


unlock the phone with a certain number of password attempts, after
which the phone is locked if attempts are unsuccessful

• Playing a favorite song(s) or video(s) on repeat

•Counting the books or taking inventory in the library

•Searching for a particular item from a set/list of information

•etc
Practice

1. Develop a simple program to search for the word “Gallery” from an archive
containing the following set of items [‘Sports’, ’Arts’, ‘Science’, ‘Music’,
‘Culture’, ‘Tourism’, ‘Gallery’, ‘Food’, ‘Agriculture’, ‘Education’].

2. Write a simple program to find the maximum value in the following set of
data [100, 1010, 1011, 101, 1001, 110 ]
Practice

3. Write a simple program to find the minimum value in the following set of
data [100, 1010, 1011, 101, 1001, 110 ]

4. Write a simple program to find the average value of the following set of data
[100, 1010, 1011, 101, 1001, 110 ]
Summary
• While loops (indefinite) • For loops (definite)
• Infinite loops • Iteration variables
• Using break • Loop idioms
• Using continue • Largest or smallest
• None constants and variables
The End Of The Lecture

You might also like