Professional Documents
Culture Documents
INTRODUCTION
Do We Really Need To Program?
• Computers are built for one purpose - to do things for us
✓ Yes we do ☺ ☺ ☺
Do We Really Need To Program?
• “Mushroom effect”
• “Bottleneck problem”
✓ Yes we do ☺
• Competitive advantage
• Algorithm
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
• When you make a mistake, the computer throws a syntax error (analogous to
grammatical error) message at you
• 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
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
x = 2 Assignment statement
x = x + 2 Assignment with expression
print(x) Print function
• Most programs are much longer, so we type them into a file and tell
Python to run the commands/instructions in the file.
• 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
x=2 Program:
Output:
print(x) x = 2
print(x) 2
x=x+2 x = x + 2 4
print(x)
print(x)
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
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')
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
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
• Case Sensitive
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 (=)
x = 3.9 * x * ( 1 - x ) (Expression)
0.6 0.6
x = 3.9 * x * ( 1 - x )
0.4
0.4
** 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
x = 1 + 2 * 3 - 4 / 5 ** 6
Operator Precedence Rules
Highest precedence rule to lowest precedence rule:
• 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
• String (str)
• Characters (texts or letters, digits, symbols, etc)
>>> 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.
• Why comment?
- Etc
# Get the name of the file and open it
name = input('Enter file:')
handle = open(name, 'r')
# All done
print(bigword, bigcount) # display results
Summary
• Operator precedence
Exercise 1
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
• 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)
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
• Maintain indent to indicate the scope of the block (which lines are
affected by the if (same for loops))
• 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')
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')
x=4
x = 4
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
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.
print('All Done')
The try / except Structure
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
• 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
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!')
• 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).
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
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
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
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!
print('Searching')
for name in ['Akua', 'Yaw', 'Esi', 'Efe', 'Ama']: Searching
if name == 'Esi':
print(‘Name found:', name) Name found: Esi
print('Finished!')
Finished
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
•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