Programming our lives…
Solving Problems With
Python
Computers, Hardware and Programming
• Most of us use computers daily / hourly
• creating documents, checking e-mail, playing games, transferring money, etc.
• Computers, smartphones, embedded systems, etc.
• By themselves, just useless hardware
• What makes these devices “work”?
Hardware
CPU
• Refers to the physical devices / components that make up a computer
• Some of the main components:
• ”The Brain” / workhorse
• Various manufacturers
• CPU (Central Processing Unit)
• RAM (Random Access Memory) – AKA “Main Memory”
• ROM (Read-Only Memory) – AKA “Secondary Storage”
• I/O (Input / Output) Devices
• Keyboard, trackpad, mouse, printer, camera, flash drive, monitor, etc.
• Intel, AMD, etc.
• Various models
• Intel i5, Intel i7, Intel i9
• AMD Ryzen 5, AMD Ryzen 7, AMD Ryzen 9
• Various Number of “Cores”
• Ex: AMD Ryzen 9 has a 12-core option, Intel i9 has an 18-core option
• Various Speeds
• Usually measured in GHz (gigahertz) – cycles per second
• 1 GHz is roughly 1 billion cycles per second!
RAM (Main Memory)
ROM (Secondary Storage)
• Storage and “working area” for:
• Larger, more “permanent” storage for programs and data
• Not much can fit in RAM at once, so ROM is where it’s at!
• Running programs
• Data currently being used / manipulated
• Similar to a human’s current working memory
• Stores everything you are thinking about / processing NOW
• Similar to a human’s stored memories
• Your knowledge and memories that you are currently NOT thinking about /
processing right now
I/O Devices
Software / Programs
• Input / Output Devices allow us to interface with the computer
• Output devices let us “see” what is going on
• Input devices allow us to influence a computer’s actions
• Specific / detailed instructions given to the computer in a language it
“understands”
• System Software vs. Application Software
• Humans write programs!
• Implications?
Programming Languages
• AKA “code”
• A set of syntax and semantics that can be easily translated into “action” for
a computer
• Machine Language
• 0’s and 1’s – only language CPU directly understands
• Assembly Language
• Low-level language - Efficient and precise
• Easily translated to machine language
• High-Level Language
• Language easier for humans to write / modify / understand
• Java, C++, Pascal, Visual Basic, C#, Phython….
What Is Data?
Solving Problems With
Python
Data
• Entities that convey meaning
• Digital Data
• Discrete
• Analog Data
• Continuous
• Computers are digital and work only with digital data
Bits
Binary Numbers
• Bit = Binary Digit
• Possible values for a bit: 0 or 1
• Numbers are encoded in a computer using bits
• Bits are a representation of the binary number system
• Think of switches: ”off” or “on”
• Base-2
• [we use base-10 (decimal) on a daily basis]
• Smallest possible element to store or process in/on a computer
Binary Numbers – Example 1
Binary Numbers – Example 2
• Example:
• How would we go the other way around?
• Example:
• What is the binary number 10110 represent in base ten?
• What would 22 (base-10) look like in binary?
0
0
0
1
0
1
1
0
27
26
25
24
23
22
21
20
27
26
25
24
23
22
21
20
128
64
32
16
8
4
2
1
128
64
32
16
8
4
2
1
Binary Numbers – Example 3
Bytes
• How would we go the other way around?
• Example:
• NOT bites….
• 1 Byte = 8 bits
• Here’s a byte:
01001110
• Here’s another byte:
10100110
• How many bytes do you see?
111100010101010111100011
• What would 167 (base-10) look like in binary?
27
26
25
24
23
22
21
20
128
64
32
16
8
4
2
1
Characters
• Character: letters, symbols, etc.
• How does a computer work with these???
• Characters each have a unique number that represents them inside a
computer, each as 1 byte (ASCII)
• Example: ‘A’ is stored as the value 65, or 01000001 in binary
• What do you think ‘B’ is stored as?
• What about lower-case ‘a’?
• Why do you think they are numbered this way?
Bytes: KB, MB, GB, TB… Oh My!
Bytes and Storage
• Bytes represent the fundamental storage metric in a computer
• Kilobyte (KB)
• So…. How much storage space would the word ALBANY take up in a
computer?
• Roughly 1,000 bytes (1,024 bytes to be exact) ß 210
• Megabyte (MB)
• Roughly 1,000,000 bytes (1,048,576 bytes to be exact) ß 220
• Gigabyte (GB)
• Roughly 1,000,000,000 bytes (1,073,741,824 bytes to be exact) ß 230
• What do you think a Terabyte (TB) represents?
• How much storage space would be required for a typical page of text?
• Assuming 250 words per page
• Average word is 5 characters
• Assuming 250 ”space characters” to separate words.
• Let’s ignore punctuation
à250 * 5 + 250 = 1,500 characters….
1,500 bytes … or… 1.5 KB
What about other types of data?
Wrapping Up
• Images?
• It is very important to understand data and its representation before
you start programming
• With computers, data is digital (binary)
• Represented by arrays of numbers
• … so would be encoded with 0’s and 1’s
• Videos?
• Represented by arrays of images
• … so just more numbers and more 0’s and 1’s
• Turns out – everything is represented as a number, and hence stored
in binary form
01001010011010101101011010001111001010111000010101101101100010100100000101111111010110110
• All processing is ultimately a calculation
Back to the CPU
Solving Problems With
Python
Programs and Programming
• CPU processes very simple instructions only
• Referred to as machine language
• Example:
• Read a number from memory
• Add a number to what is in that memory location
• Subtract two numbers
• Move a number to another memory location
• Etc.
• BUT – a CPU does these small operations extremely FAST
How Does a Program Work?
Programming
• Programs are stored on secondary storage
• When needed, programs are transferred into RAM (working memory)
• CPU can then execute the instructions one by one:
• Would not be much fun if we could only write thousands (if not
millions) of micro-instructions!
• Not to mention, this is typically what a CPU sees as instructions:
01001111 01011011 11001100 10101010 …
• Fetch
• Decode
• Execute
(In walks high-level languages)
High-Level Languages
Compilers and Interpreters
• Instead of typing thousands of 0’s and 1’s, a programmer can type:
print “I am so excited to learn Python!”
• Each language must have its own compiler or interpreter
• Compiler
• NOTE: Code written in a high-level language is called source code
• Which could be translated into those 0’s and 1’s and executed by the
CPU
• How does this translation happen???
• Special programs called a compilers or interpreters
• Special program that translates high-level language into machine language
• Interpreter
• Special program that translates high-level language into machine language,
BUT… does this line by line and executes each one.
• NOTE: Python code is run through an interpreter
Python - History
Why Python?
• An interpreted programming language developed in late 1980’s
• Very powerful, yet intuitive language
• Easy to get started with
• Easy to interact with
• Cross-platform compatibility
• Widely used in industry, sciences, etc.
• Great for rapid prototyping
• Guido van Rossum, Netherlands
• First release (Python 0.9.0) in 1991
• Python 2.0 (2000) – discontinued 2020
• Note: “old” Python 2 code will not work with Python 3 interpreter
• Python 3.0 (2008)
Example of a Problem
Installing Python
• Find any words in the English language that contain three consecutive
double letters
hello
^^
balloon
^^^^
mississippi
^^ ^^ ^^
ß Not consecutive
• For this course, we will be using the IDLE interface for Python
• Available directly from www.python.org
Python – Getting Started
• Please use this time to install Python on your computer
• See you in the next Lecture Video to get started!
• Go to “Downloads”
• Download & Install
Python Data Types
Solving Problems With
Python
Data Types and Expressions
• A data type is a set of possible values (representation) and a set of
operations that can be performed on those values
• In this lesson, we will look at our first two data types:
• Integers
• Floats (AKA floating-point numbers)
Integers
Floating-Point
• Possible values:
{ …, -3, -2, -1, 0, 1, 2, 3, … }
• Floating-point data type à basically just a real number!
• Operations:
+ (add)
* (multiply)
% (modulus)
- (subtract)
/ (divide)
** (exponent)
• Example:
3.56
• Additional Unary Operators:
+ (positive)
-
-0.781098
917.091100
8.0
(negative)
Order of Operation
Order of Operation - Example
• The order in which basic operations in Python are evaluated:
1. Parenthesis (starting with inner-most)
2. Exponents (** operator): Right to Left
3. Unary + and – operators (positive and negative)
4. * and / and % operators, Left to Right
5. + and – operators, Left to right
3 * (4 - 2) + 2**3 / 4 - -3
Exercises
Let’s Go to IDLE
1. Write a formula to convert 70 Fahrenheit to Celsius. You must first
subtract 32, then multiply by 5/9.
àààà
2. Write the opposite formula (Celsius to Fahrenheit).
3. Write a formula to compute the volume of the moon.
What is a “Variable”?
Solving Problems With
Python
Variables
Variables in Memory
RAM
0
• Recall RAM (memory) ?
• We need a way to store something in memory and remember where
we put it
• Variables are symbolic references to a location in memory
Variable Names
• Here are the rules for naming variables:
4
• NO spaces
• First symbol must be a..z, A..Z or _
• Remaining characters can contain any letter, number or underscore
8
12
16
• Variables are CASE-SENSITIVE
20
24
28
Cat
CAT
CaT
cat
CAt
32
36
Reserved Words
• There are certain “reserved words” used by Python
• You cannot use these as your variable names
• Examples:
and
as
for
is
return
with
global
print
… and many others (see python.org for additional documentation)
Let’s Go Back to IDLE à
Sequential Structure
Solving Problems With
Python
• Every program we have seen so far has been sequential
Introduction to Control Structures
num1 = 10
Decision-Based Structure
• Used to test a condition, then execute the appropriate code
• Test must always be Boolean (that is true or false)
age >= 18
print(“You are NOT old enough to vote”)
print(f"{num1+num2}")
The if Statement
age = input(“what is your age?”)
false
num2 = 25
true
if condition:
statement1
statement2
...
if (condition):
statement1
statement2
...
print(“You are old enough to vote”)
Relational Operators
• A Boolean expression that evaluates to either true or false
• Relational Operators:
Greater than?
>
Less than?
<
Greater than or equal to?
>=
Less than or equal to?
<=
Equal to?
==
Not Equal to?
!=
Let’s Go Back to IDLE-->
The if-else Statement
• The else statement allows us to specify code to execute in the event the
condition is false
if condition:
Anything in here is
statement1
executed if the
statement2
condition is true
...
else:
Anything in here is
statement1
executed if the
statement2
condition is false
...
Let’s Go Back to IDLE-->
Logical Operators
Solving Problems With
Python
Control Structures – Part 2
• Recall that Boolean expression that evaluates to either true or false
• We have seen the relational operators >, <, >=, <=, ==, !=
• We can build more powerful expressions using logical operators:
and
or
not
The and Logical Operator
The or Logical Operator
• True if and only if both operands are true
• Otherwise, false
• Example:
(x > 100 ) and (x < 200)
• True if either (or both) of the operands are true
• false only if both operands are false
• Example:
(age < 12) or (age > 75)
The not Logical Operator
• Unary operator – only function on one operand
• Simply reverses the logical value
• Example
not age > 5
Let’s Go to IDLE-->
The Need For Repetition Structures
Solving Problems With
Python
Introduction to Repetition Structures
• AKA “Loops”
• It is very common that a computer must run a segment of code more
than once
• Imagine you needed to write the following program:
For all 20 students in your class, ask for their midterm and final exam
grades, then calculate their average and tell them if they are passing.
See anything
redundant???
The while Loop
Syntax For while Loop
Condition
false
(exit)
Note: while is a ”pre-test” loop
Don’t we just
want to do
THIS 20 times?
true
Statements
while condition:
statement1
statement2
...
Syntax For while Loop à Exit Stategy
while condition:
statement1
statement2
...
Note: One of these statements
must eventually make the
condition false
What do you think would
happen otherwise?
To Be Continued …
More looping on the way!
Let’s Go to IDLE-->
Count-Controlled Loop
Solving Problems With
Python
• Iterates a specific number of times
• Ex:
Print the numbers 1 through 100
Repetition Structures – Part 2
The for Loop - Syntax
The for Loop – Example with Numbers
for variable in [value1, value2, ...]:
statement1
statement2
...
The for Loop – Example with Strings
The range Function
• We really do not need to write out large lists of numbers in a for loop
• Instead, use the range function! Example:
The range Function
The range Function
Starting
Value
Let’s Go to IDLE-->
End
Limit
Step
Size
Nested Loops
Solving Problems With
Python
• You can put a loop inside of another loop!
• Imagine printing out each second for a simple stopwatch (minutes
and seconds only)
Repetition Structures – Part 3
Flow Chart for Stopwatch Example
Nested Loops
• How many total iterations are there in this example?
• That is, how many times is the print statement executed?
Nested Loops – Another Example
Nested Loops – Another Example
• How about printing all output for a digital clock in a 24 hour day?
• Now, how many total iterations?
Let’s Go to IDLE-->
Functions
Solving Problems With
Python
• A function is a group of statements that can be reused
• Reused within the program
• Reused in other programs
• Modular Programming
Functions
• Benefits:
• Faster coding
• Better Organization
• Divide & Conquer
Functions
Functions
• We have already seen the use of existing functions
• Some functions do not “return” anything
• These are called void functions
• This one also takes no input
Input Value
9
Return Value
sqrt
3
print_hello
Syntax of a Function in Python
def functionName ():
statement1
statement2
...
Let’s Go to IDLE-->
This is a very basic function
definition – no inputs & no
return value
Local Variables
• Any variable used within a function is considered local
• Local variables exist only within the scope of the function they are in
total is a local
variable
Let’s Go to IDLE-->
Passing Data to a Function
Solving Problems With
Python
• Data passed to a function is called an argument
9 is the
argument
passed to sqrt()
Functions – Part 2
Input Value
9
Function with Argument - Example
Return Value
sqrt
3
Function with Multiple Arguments - Example
Here, limit becomes a local variable and takes on the value 15
Global Variables and Constants
Let’s Go to IDLE-->
• Any variable (or constant) declared outside of any function is
considered global
• That is, it can be “seen” by any function
It can see the
constant PI
Let’s Go to IDLE-->
The import Statement
Solving Problems With
Python
Functions – Part 3
• Python comes with a standard library
• We have already been using many built-in function
• Examples:
print()
range()
int()
input()
...
Additional Libraries
Using Library Functions
• You can import additional libraries
• SIDE NOTE à you can even create your own!
• Syntax to import a library:
import LibraryName
• To use a function in the library, you need to follow the following
syntax:
library_name.function_name
• Example:
import math
• Example:
math.sqrt(25)
Imports the math library
The math Library
The random Library
• Plenty of useful functions… here are just some of them:
• A library dedicated to generating random numbers
• Random numbers are VERY IMPORTANT for several computations and
computer programs
ceil(x)
exp(x)
floor(x)
hypot(x, y)
log(x)
sin(x)
cos(x)
tan(x)
• Some useful constants:
math.pi
math.e
import random
secret_num = random.randint(1, 100)
Let’s Go to IDLE-->
Returning Values - The return Statement
Solving Problems With
Python
Functions – Part 4 (Finishing up!)
Functions: Returning Values – Example
• We have already used functions that return values
• Syntax for returning a value from a function:
def function_name(args):
statement1
statement2
...
return expression
Functions: Returning Values – Example
Alternatively, you can just return the calculation
Let’s Go to IDLE-->
Files
Solving Problems With
Python
File I/O
• Recall ROM (or secondary storage)
• You can store data generated by your program in a file
• Your program can read data in from a file later on
• Why not store in variables?
• RAM is temporary
Lord of the Files
Accessing a File Within Your Program
• Terminology:
1. Open the file
2. Read or write to the file
3. Close the file
• We write data to a file
• We read data from a file
Python program
grades.txt
customer_info.dat
NOTE: There are several types of files. Each varies by the format in
which the data is presented within the file, and its intended usage
gamedata.csv
Step 1: Opening a File -- Syntax
Step 1: Opening a File - Examples
file_variable = open( file_name, mode )
gradebook_file = open (“grades.txt”, ’r’)
product_ratings_file = open(“ratings.csv”, ‘w’)
Name and location of
file (this is a string)
Note: open() is a function in Python
'r’ for read
‘w’ for write
‘a’ for append to end
grocery_list_file = open(“supplies.txt”, ‘a’)
NOTE: The interpreter assumes the file you are using is
in the same folder as your program.
Step 1: Opening a File - Examples
Step 1: What does this file variable do???
scores = open (r“C:\data\scores.txt”, ’w’)
gradebook_file = open (“grades.txt”, ’r’)
NOTE: We can link to the direct path to a file using the r
string format (r stands for “raw string”)
Here, gradebook_file “points” to the file on disk. It has essentially
“opened a stream to the file”
gradebook_file also comes with several member functions as we
will see
gradebook_file
Step 2: Writing or Reading to the File
Step 3: Closing the File
• We can use the file_variable.write() function
• Very important to close the file… why?
• We can use file_variable.read() function
grades.txt
• Releases program’s “control” over the file
• Forces all pending write operations to complete
• Essentially, removes the link:
gradebook_file
Let’s Go to IDLE-->
grades.txt
File Handling
Solving Problems With
Python
• Recall - the readline() method returns the next string in a file up to a
delimiter (i.e. ‘\n’)
• If the end of file has been reached (no more to read):
• readline() returns the empty string ‘’
File I/O – Part 2
Loops For Reading a File
zoofile = open('animals.txt’)
animal = zoofile.readline()
while animal != '':
print(animal)
animal =
zoofile.readline()
zoofile.close()
animals.txt
Cat
Dog
Bird
Duck
Goat
Horse
Cow
Penguin
Lizard
Frog
Donkey
Chipmunk
Rhino
Hippo
animals.txt
Alternatively….
zoofile = open('animals.txt’)
for animal in zoofile:
print(animal)
zoofile.close()
Cat
Dog
Bird
Duck
Goat
Horse
Cow
Penguin
Lizard
Frog
Donkey
Chipmunk
Rhino
Hippo
Robust File I/O
• Example:
Let’s Go to IDLE-->
• Suppose you asked the user for a filename that you would open and attempt
to read from
• What if they entered the name of a file that did not exist?
program crash and burn!
Better Solution: try and except
Better Solution: try and except
• Exceptions are another word for errors that may occur in a program
• It is MUCH BETTER to catch these and provide a meaningful error
message
• Example
• Rather than let the Python interpreter communicate the error
Let’s Go to IDLE-->
Lists
Solving Problems With
Python
Lists
• A list in Python is collection of data items
• In other programming languages, these are often implemented as
arrays
colors = [‘red’, ‘blue’, ‘yellow’, ’green’]
primes = [2, 3, 5, 7, 11, 13, 17]
Lists - Syntax
Generating a List
• Data for a list is indicated inside of square brackets [ and ]
• The list() function can convert an object to a list
colors = [‘red’, ‘blue’, ‘yellow’, ’green’]
primes = [2, 3, 5, 7, 11, 13, 17]
Separated by commas
Operations on a List
• The * operator has special meaning when applied to a list
• You can think of it as “make x number of copies of”
Let’s Go to IDLE-->
Lists and Indexing
Lists and Indexing
• Data items in lists are stored sequentially in memory
colors = [‘red’, ‘blue’, ‘yellow’, ’green’]
‘red’
‘blue’
‘yellow’
‘green’
0
1
2
3
colors = [‘red’, ‘blue’, ‘yellow’, ’green’]
‘red’
‘blue’
‘yellow’
‘green’
primes = [2, 3, 5, 7, 11, 13, 17]
primes = [2, 3, 5, 7, 11, 13, 17]
2
3
5
7
11
13
Let’s Go to IDLE-->
2
3
5
7
11
13
17
0
1
2
3
4
5
6
17
Splitting Up a List
Solving Problems With
Python
Lists – Part 2
primes = [2, 3, 5, 7, 11, 13, 17]
Start Index
primes[2:4]
[5, 7]
End (but not including)
primes[1:5]
[3, 5, 7, 11]
Finding Items in a list
• We can use the in operator to find out if an item is in a list
primes = [2, 3, 5, 7, 11, 13, 17]
Let’s Go to IDLE-->
3 in primes
True
16 in primes
False
List Methods
append(item)
reverse()
index(item)
insert(index, item)
sort(item)
remove(item)
Let’s Go to IDLE-->
Lists in Memory
• Consider the following code:
• This did NOT actually make a copy!
• pets and animals are pointing to the same list in memory
• WHY? To avoid wasting valuable memory (lists can be BIG!)
What is a tuple?
Solving Problems With
Python
Tuples and String Manipulation
• A tuple is simply a list where the elements cannot change
• Think of it as a “protected list”
• Tuples are processed faster than lists
primes = (2, 3, 5, 7, 11, 13, 17)
Note ( ) instead of [ ]
Operations on Strings
Let’s Go to IDLE-->
• Most programs perform a significant amount of string manipulation
and processing
• Strings are sequences
• So are lists & tuples
• Can be treated similarly in many cases
• Example:
Searching Strings
Methods on Strings
• You can search for a string within a string
• There are SEVERAL Boolean functions
• Suppose we have a string mystring
mystring.isdigit()
mystring.isalpha()
mystring.isspace()
mystring.isupper()
mystring.islower()
mystring.isalnum()
Methods on Strings
• There are SEVERAL modification functions
• Suppose we have a string mystring
mystring.lower()
mystring.upper()
mystring.strip()
mystring.lstrip()
mystring.rstrip()
What is a dictionary in Python?
Solving Problems With
Python
• A dictionary facilitates a way to store collections of data so that:
• Data can be paired with a key
• Data can be “looked up” based on the key
• Similar to a trivial database
Dictionaries
emails = {’Becky’: ’smithb123@pyu.edu’,
’Jim’ : ‘andrewsj879@pyu.edu’,
‘Mary’ : ‘evansm901@pyu.edu’}
Note the key:value pairs
Syntax for a dictionary
emails = {’Becky’: ’smithb123@pyu.edu’,
’Jim’ : ‘andrewsj879@pyu.edu’,
‘Mary’ : ‘evansm901@pyu.edu’}
Note: { and } used to
define the dictionary
Note: : used to
correlate the key with
the data
Let’s Go to IDLE-->
What is a set?
Solving Problems With
Python
Sets
• A set is a collection of unique objects (no duplicates)
• Works exactly like a mathematical set
• Order does not matter
animals = set([‘cat’, ‘dog’, ‘mouse’])
Set Operations
• Union of 2 sets: A | B
Let’s Go to IDLE-->
• will combine contents of both sets
• duplicates will be discarded
A
B
A
B
• Intersection of 2 sets: A & B
• will create a set containing the common elements
• anything not in both sets will be discarded
Set Operations
Set Operations
• Difference of 2 sets:
• Symmetric Difference of 2 sets:
• A – B: Produces a set with everything in A, but removes any common
element from B
A
B
• A ^ B: Produces a set of all elements that A and B do not have in common
A
B
Subsets
Supersets
• A is a subset of B if:
• A is a superset of B if
• All elements of A are also elements of B
• Ex:
vowels are a subset of the alphabet
(2, 4, 6) is a subset of (1, 2, 3, 4, 5, 6, 7, 8)
students are a subset of the university population
Let’s Go to IDLE-->
• All elements in B also belong to A
• A can have elements that are not in B
• Example:
The alphabet is a superset of the set of vowels
(1, 2, 3, 4, 5, 6) is a superset of (1, 2, 5)