0% found this document useful (0 votes)
9 views194 pages

Class 6

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views194 pages

Class 6

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 194

CS 108 – Foundations of CS I

Fall 1 2024
Overview
Class Session 6
• Intro to Python
The Story So Far

Number Lightweight Propositional


Truth Tables
Bases Set Theory Logic

Predicate Data
Programming Python
Logic Structures

Even More Computing


Python and Society
“The only way to learn a
new language is to write
programs in it.”

- Dennis Ritchie
A Simple Program
Hello, World!
The most basic thing we can do in a computer program is print
something to the console.

print("Hello, World!")

This program consists of output (print) and a string literal (“Hello,


World!”)
What is a string?
• A string is anything contained in single or double quotes.

• “Hello”

• “3.14”

• ‘World!’

• ‘10’
Output
• Python has a very powerful function called print.
Print
• At its most basic, print just prints whatever is given to it in
parentheses to the console.

• We’ll see later how it can be used in more interesting ways.

print("Hello, World!")
Input
• The opposite of print is input.

• Use input to allow a user to enter data and save it.

name = input(“Enter your name: “)


Input
• Input stores the entered value in the variable called ‘name’:

name = input(“Enter your name: “)

We can use ‘name’ later in our program:

print(name)
Input
• All data captured by input is a string!!

• If you want it to be a number, you must convert it to a number.

• To convert, or cast the value to a number, use:


int()
float()
Casting
• Converting input:

num = input(“Enter a number: “)


print(num)
#output: ‘10’ Notice quotes

num = input(“Enter a number: “)


num = int(num)
print(num)
#output: 10 Notice missing quotes
Converting numbers
num = input(“Enter a number: “)
num = int(num)
print(num)
#output: 10

We don’t have to make it a separate line:

num = int(input(“Enter a number: “))


Converting numbers
num = input(“Enter a number: “)
num = float(num)
print(num)
#output: 10.0

What if the user doesn’t enter a number???


Dealing with input
num = input(“Enter a number: “)
#user enters 3.14
num = int(num)
print(num)
#output: ???

#output:
Traceback (most recent call last):
File "/Users/davidgood/Projects/python/Ignite/userinput.py", line 5, in <module>
num = int(num)
ValueError: invalid literal for int() with base 10: '3.14'
Dealing with input
• Be very careful when accepting user input.

• Users can not be trusted.

• If you want an integer, make your message specific:

num = input(“Enter a whole number: “)

There are other ways to deal with garbage input that we’ll see
later.
Formatting output
• Python has a handy feature to format output called f-strings.

• F-strings can be used almost anywhere to format strings.

f”{}”
Formatting output

name = input("Enter your name: ")

print(f"Hello, {name}!”

f “ … “ is called an f-string,
short for format string. It tells
Python to replace anything in
curly braces with the variable value.
Formatting output

name = input("Enter your name: ")

print(f"Hello, {name}!”

A format string

Replace {} with the variable value


Formatting output

name = input("Enter your name: ")

print(f"Hello, {name}!”

#output: “Hello, Alice!”


Comments in Python
Single Line comment:
# This is a comment

Multi-line comments start and end with “”” (three


double quote characters)

"""This is
a multi-line
comment"""
A better program
Beyond “Hello, World!”
x = 10
y=2

print(x + y)

This program consists of:


• 2 variables: x and y
• Addition: x + y
• Output: print
Variables
• Algebra:

x = 10
2x = 10

Python:

x = 10
2 * x = 10
Variables
• Just like math, variables in programming languages hold real values.

• In a computer, the real value is stored somewhere in memory (RAM) ,


and the variable “points” to it or references it.

x = 10

10 gets stored in memory, but we can use x anywhere we want in our


program.
Variables
1. x = 10
2. y = 2

3. x = x / y

# After line 3 executes, x now holds 5

We can do almost anything we want with x as long as we treat it like an


integer.
More variables
x = 10

apple = “apple”

pi = 3.14159

isRaining = False

banana = ’banana’
Data types
Data types
• Everything we store in a program is data, and all data has a type.

x = 10

10 is an integer, therefore x is also an integer

Integer is the data type

Integers are whole numbers, including zero and negative numbers.


Data Types
apple = “apple” String

pi = 3.14159 Float

isRaining = False Boolean


Python data types
• Python has specific types for strings, numbers, booleans (true/false), and
collections of items.

• String: str
• Numbers: int, float, complex (3 + 4i)
• Boolean: False, True
• Collections: list, dictionary
Collections
• It’s often helpful to hold a variety of things and collect them all into one
location and refer to them with a single variable.

• Baseball cards
• Screw drivers
• Test scores
• Dates
• Temperatures
•…
Python lists
temps = [32.0, 45.5, 50.0, 60.2]

fruits = ['apple', 'banana', 'orange’]

testScores = [95, 85, 75, 65]

didItRain = [True, False, True, False]

Lists are _everywhere_ in Python.


Python dictionaries
• Sometimes a list of things isn’t quite good enough. We often want to
associate items in a list with some other value.

• Consider books:

• War and Peace by Leo Tolstoy


• The Stranger by Albert Camus
• The Hobbit by J.R.R. Tolkien

• We may want to associate the title with the author.


Python dictionaries
books = {
"Leo Tolstoy": "War and Peace",
"Albert Camus": "The Stranger",
"J.R.R. Tolkien": "The Hobbit”
}

Dictionaries are lists that have key-value pairs:

“author”: “title”
Data Types
Text Type: str
int, float,
Numeric Types:
complex
list, tuple,
Sequence Types:
range
Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool


bytes,
Binary Types: bytearray,
memoryview
None Type: NoneType
Basic data types
• Strings: Represent text.

• Boolean: True or False

• Integers: Any fixed-point numeric value

• Floats: Any non-fixed point numeric value

• Lists: A collection of items. Known as arrays


in other languages.
38
Strings
Strings
• Strings represent text.
• Python is smart, so you can treat strings as arrays of characters
if you need to.
• Take that, C.

40
Strings
• Strings in Python can be enclosed in single or double quotes.
• Be consistent; use one or the other.

msg = "Hello, World!"


msg = 'Hello, World!’

The main advantage to single quotes is you can embed double quotes
without escaping them:

msg = 'Hello, "World"!'

41
Strings
• Strings are just sequences of characters enclosed in single or double
quotes.

• You can think of a string as a word or sentence. Just like words and
sentences are made up of letters and spaces, strings are made up of
individual characters.

name = “Alice”
greeting = “Hello, World!”
Python Strings
• Python strings are immutable. Once you assign a value to
them, the individual characters can’t be changed.

• You can access individual characters in the string by its index


(position).

word = "Hello"
print(word[0]) # output: ‘H’
print(word[4]) # output ‘o’
Operations on Strings
• Concatenate (join two strings):

first_name = "Alice"
last_name = "Smith"
full_name = first_name + " " + last_name
print(full_name)
# Output: 'Alice Smith'
Operations on Strings
• Repetition: repeat strings using the * operator

repeat_hello = "Hello! " * 3


print(repeat_hello)
# Output: 'Hello! Hello! Hello! '
Operations on Strings
• Get the length of string:

sentence = "Hello, world!”


print(len(sentence))
# Output: 13
Operations on Strings
• Upper and Lower case:

name = "Alice”

print(name.lower())
# Output: 'alice’

print(name.upper())
# Output: 'ALICE'
Operations on Strings
• Replace part of a string with another string:

greeting = "Hello, world!”

new_greeting =
greeting.replace("world", "Alice")

print(new_greeting)
# Output: 'Hello, Alice!'
Operations on Strings
• Remove leading and trailing whitespace:

spaced_string = " Hello ”

print(spaced_string.strip())
# Output: 'Hello'
Operations on Strings
• Sometimes you need to include special characters like quotes or
newlines inside of a string. Python uses \ to ”escape” special characters
within a string:

message = "She said, \"Hello!\""


print(message) # Output: She said, "Hello!"

multiline = "This is line 1.\nThis is line 2."


print(multiline)
# Output:
# This is line 1.
# This is line 2.
Numbers
Integers
• Fixed-point numeric values:

1
5
-13

You can also use binary, hex, and octal in Python.


Thanks, C.

If it has a decimal in it, it’s not an int.


52
Floating Point
• Any number with a fractional part (aka a decimal) is a floating point, or
float.

0.5
3.14
-2

If you need to convert a float to an int, you will truncate the number due to
rounding and losing the fractional part.

53
Lists
Lists
• Python lists are just a collection of variables or values under a
single name.

• What kinds of lists do you use?

• Grocery list
• Classes
• Books
• Favorite songs
• Daily temperatures
Lists
• Lists are called arrays in other languages.

• Lists in python are much more powerful than a standard array. They’re
used very frequently.

• Basic syntax:

name = [item1, item2, item2, …]

56
Lists
• Unlike arrays in other languages, Python lists can store mixed types:

name = [int, float, string]

You still access the elements of a list the same as arrays:

name[0]

57
Python Lists
• Definition: A list is an ordered collection of items in Python. It can contain
elements of different data types (e.g., integers, strings, floats).
• Analogy: Think of a list as a container (like a shopping list) where you can
store multiple items and access each item by its position.

fruits = ["apple", "banana", "cherry"]


numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "hello", 3.14, True]
Python Lists
• Key properties of Lists:

• Ordered: Items are stored in a specific sequence, and each item has an
index.

• Mutable: You can modify, add, or remove elements after the list is created.

• Heterogeneous: Lists can contain items of different data types.


Lists
• Every element in a list has an index, or location, in the list.

• List indices begin at zero, not one!


List of fruits

fruits = ['apple', 'banana', 'orange']

Item apple banana orange


Index 0 1 2
Working with lists
• You access individual items in a list by their index.

fruits = ['apple', 'banana', 'orange’]

fruit1 = fruits[0]

print(fruit1)

#output: ‘apple’
Lists
• Unlike arrays in other languages, Python lists can store mixed data
types:

name = [int, float, string]

stuff = [10, 3.14, “Snoopy”]

63
Another example

stuff = [10, 3.14, “Snoopy”]

item3 = stuff[2]

print(item3)

#output: ‘Snoopy’
Lists
• Python strings are a special type of list.

“Hello, World” is a list of 12 characters.

H E L L O , W O R L D
0 1 2 3 4 5 6 7 8 9 10 11
String as list example

greeting = “Hello, World!”

print(greeting[0])
#output: ‘H’

What would greeting[6] print?

print(greeting[6])
#output: ‘ ’
Operations on Lists
• Just like Strings, you can access individual elements of a list by their
position (index):

fruits = ["apple", "banana", "cherry"]


print(fruits[0]) # Output: apple
print(fruits[2]) # Output: cherry
Operations on Lists
• You can change the value of a list element by assigning a new value to
an index:

fruits = ['apple', 'banana', 'cherry']


fruits[1] = "blueberry"
print(fruits) # Output: ['apple', 'blueberry', 'cherry']
Operations on Lists
• You can add new items to a list by using the append() or insert()
methods:

fruits = ['apple', 'banana', 'cherry']


fruits[1] = "blueberry”

fruits.append("orange")

print(fruits)
# Output: ['apple', 'blueberry', 'cherry', 'orange']
Operations on Lists
• You can remove items from a list by using the remove() method or the
built-in del() function.

fruits = ['apple', 'banana', 'cherry']


fruits[1] = "blueberry"
fruits.append("orange")

fruits.remove('blueberry')
print(fruits)
# Output: ['apple', 'cherry', 'orange']
Creating Lists
letters = list("Hello, World!")

What does this give us?


Creating Lists
letters = list("Hello, World!")

What does this give us?

Value H e l l o W o r l d !
Index 0 1 2 3 4 5 6 7 8 9 10 11
Creating Lists
letters = list("Hello, World!")

What does this give us?

Value H e l l o , W o r l d !
Index 0 1 2 3 4 5 6 7 8 9 10 11 12

print(letters[5])
,
Adding Items to a List
• Use Append to add an item to a list:

fruits = ["apple", "banana", "orange"]

fruits.append("pear")
fruits.append("plum")
Removing Items from a List
• Three ways to remove an item from a list:

• .remove(item)
• .pop(index)
• del item
Removing Items from a List
fruits = ['apple', 'banana', 'orange']

# Removes the first occurrence of banana


fruits.remove('banana')

# Removes the element at index 1 (banana)


popped_val = fruits.pop(1)

# Deletes the first element (apple)


del fruits[0]
Inserting an Item into a List
• While .append adds a new item to the end of a
list, .insert puts an item into a list at the specified
index, or position:

fruits = ['apple', 'banana', 'orange']

#Inserts pear at index 1


fruits.insert(1, 'pear')
Updating an item in a List
fruits = ["apple", "banana", "orange"]
# Change banana to pear
fruits[1] = 'pear'
Operations on Lists
• append(x): Adds x to the end of the list.
• insert(i, x): Inserts x at index i.
• remove(x): Removes the first occurrence of x.
• pop(i): Removes and returns the element at index i (or the last item if i is not
specified).
• sort(): Sorts the list in place.
• len(list): Returns the number of elements in the list.
Combining Two Lists
• Use .extend to append one list to another:

odds = [1,3,5,7,9]
evens = [2,4,6,8,10]
odds.extend(evens)
Sorting a List
temperatures = [22.4, 25.6, 24.1, 23.8]
print(temperatures)
[22.4, 25.6, 24.1, 23.8]

temperatures.sort()
print(temperatures)
[22.4, 23.8, 24.1, 25.6]
Reverse a List
temperatures = [22.4, 25.6, 24.1, 23.8]
print(temperatures)
[22.4, 25.6, 24.1, 23.8]

temperatures.reverse()
print(temperatures)
[23.8, 24.1, 25.6, 22.4]
List Summary
• Lists are one of the most useful data types in python

• You can combine lists with loops (we’ll see later) to make powerful
operations.

• Lists begin with [ and end with ]

• List items are accessed by index

• Indices start at 0
Dictionaries
Dictionaries
• Python dictionaries are similar to lists, but they use a key instead of an
index.

• The key can be anything you want, but it must be unique within the
dictionary.

• The computer science term for a dictionary is “associative array” – each


value is associated with a unique key.

• Dictionaries are building blocks of other data structures, such as hash


tables.
Python Maps (Dictionaries)
• We’ve seen Python lists – they’re just a collection of items enclosed in
square brackets []

• Sometimes, we want to use a list but also have a way to refer to an item,
like its name or Id. We can accomplish this with a dictionary, which is a
list of key-value pairs enclosed in curly braces {}
Dictionaries
Our fruits list:
lst = ["Apple, Banana, Cherry"]

dict = {1:"Apple", 2:"Banana", 3:"Cherry"}


Cars dictionary

cars = {"make": "Ford",


"model": "Mustang",
"year": 1964}
Using a Dictionary
• There are four main ways to use a dictionary:
• Kind of like a list
• With Keys
• With Values
• With Items – both keys and values
Using a Dictionary
• Like a list:
make = cars.get("make")
• With Keys
for key in dict.keys():
print(f"Key: {key}")
• With Values
for val in dict.values():
print(f"Val: {val}")
• With Items
for key, val in dict.items():
print(f"Key: {key}, Val: {val}")
Creating a Dictionary

d1 = dict(name="Alice", age=20, dept="HR")

cars = dict(make="Ford", model="Mustang", year=1964)

d2 = {"1":"item1", "2":"item2", "3":"item3"}

d3 = {1:"Apple", 2:"Banana", 3:"Cherry”}

d4 = dict(1="Apple", 2="Banana", 3="Cherry")


Adding and Updating Items
cars = {"make": "Ford",
"model": "Mustang",
"year": 1964}

# Add an item to the dictionary


cars["color"] = "Red”

# Change the year


cars["year"] = 2020
Remove an Item
# Remove color
cars.pop("color")

# Remove the last item


cars.popitem()

# Remove year
del cars["year"]
Other Dictionary Operations

# Get the length, just like a list


l = len(cars)

# Clear all items from the dictionary


cars.clear()
Functions
Functions
• Functions are snippets of reusable code that have a name.

• Consider:

x = 10
x=x*x

What happens to x?
Square
x = 10
x=x*x
print(x)

y=5
y=y*y
print(y)

Squaring numbers
We can do better
x = 10
x=x*x
print(x)

We could give this operation a name and use the name wherever we want to
square a number.
Functions
• Enter functions…

def square(num):
return num * num

x = square(10)
print(x)
Anatomy of a function
definition
name parameter

def square(num):
return num * num

body
Anatomy of a function

signature

def square(num):
return num * num

return statement
Functions
• Functions do not have to return a value.

• Functions do not have to have parameters.

• Functions MUST begin with def

• Function signatures end with a colon (:)

• Function bodies must be indented


Anatomy of a function

colon

def square(num):
return num * num

Indentation (4 spaces)
Indentation
• You MUST be consistent.

• Indenting one line with spaces and the next line with a tab will
cause weird behavior and errors.

• You must either use spaces or tabs.

104
Whitespace
• Whitespace is significant in Python.

• There are no curly braces {} to denote the beginning and ending


of blocks of code.

• Code blocks are indented in Python.

105
Indentation
Error:

if num > 0:
print("Positive number")

Correct:

if num > 0:
print("Positive number")

106
A simple function

def sayHello():
print(“Hello, World!”)

• No parameters
• No return value

• To call (execute) the function:


sayHello()
Square improved (shortened)

def square(num):
return num * num

print(square(10))

Moved the function call inside print()


More functions
• Calculate the area of a circle:

Area = pi times radius squared

2
𝐴 = 𝜋𝑟

How do we write that in Python?


Area in Python

pi = 3.14
radius = 5

area = pi * radius * radius

OR

area = pi * radius ** 2
Area of a circle
pi = 3.14
radius = 5
print(pi * radius ** 2)

radius = 6
print(pi * radius ** 2)

radius = 6.29
print(pi * radius ** 2)
Area of a circle function

def area(radius):
return 3.14 * radius ** 2

print(area(3))
print(area(6.28))
Function names
def area(radius):
return 3.14 * radius ** 2

Is this a good name for the area function?

What if we want the area of a rectangle, square, or triangle?


Function names
def circle_area(radius):
return 3.14 * radius ** 2

How about now?

What if we want the area of a rectangle, square, or triangle?

We have to implement separate functions for those.


Function names

def rectangle_area(width, height):


return width * height

def triangle_area(base, height):


return 0.5 * base * height
Function Example
def calculate_average_temperature(temps):
return sum(temps) / len(temps)

temperatures = [22.4, 25.6, 24.1, 23.8]


print(calculate_average_temperature(temperatures))

Calculate_average_temperatures is a function that


takes a parameter called temps and returns the
average of the temperatures in the list.
Another Example
def find_largest_number(numbers):
largest_number = 0
for number in numbers:
if number > largest_number:
largest_number = number
return largest_number

numbers = [15, 25, 3, 4, 11, 99, 1]


print(find_largest_number(numbers))
Function
A function is a block of organized, reusable code that performs a specific
task.
Functions are defined with the def keyword, the function name, followed
by parentheses and a colon. Indentation in Python is significant.

def greet():
print("Hello, world!")
Anatomy of a Function
def find_largest_number(numbers):
...

• All functions start with def


• Functions have a name
• Functions have parentheses
• Functions take zero or more parameters
• Functions end with a colon
• This is called the Function Signature
• Everything that comes after the colon is the Function
Body
Anatomy of a Function

Function Signature:
def find_largest_number(numbers):
largest_number = 0
for number in numbers:
if number > largest_number:
largest_number = number
return largest_number
Anatomy of a Function

Function Body:
def find_largest_number(numbers):
largest_number = 0
for number in numbers:
if number > largest_number:
largest_number = number
return largest_number
Function
Key points about functions
• Functions to not have to return values
• Functions do not have to have parameters

def print_menu():
print("WELCOME TO THE MENU")
print("Choose an Option:")
print("1: Show Temps")
print("2: Calculate Average Temp")
print("3: Exit")
Functions
• Functions can have parameters:

def greet(name):
print(f"Hello, {name}!")

greet("Alice")
Functions
• Functions can return values with the return keyword.

def add(a, b):


return a + b

result = add(5, 3)
print(result) # Output: 8
Functions
• Functions can have optional parameters by giving them a default value:

def greet(name="world"):
print(f"Hello, {name}!")

greet() # Output: Hello, world!


greet("Alice") # Output: Hello, Alice!
Functions
• Functions can be called with keyword arguments:

def greet(name, greeting="Hello"):


print(f"{greeting}, {name}!")

# Output: Hi, Alice!


greet(name="Alice", greeting="Hi")
greet(greeting="Hey", name="Bob")
A simple function
def multiply(a, b):
"""Returns the product of two
numbers."""
return a * b

result = multiply(4, 5)
print(result) # Output: 20
Questions so far?
Controlling Program
Flow

129
Control Flow
• During the execution of your program, you will
need to make decisions and control the program's
flow.

• The most basic way to make decisions is with:

• If / else statements.
• Evaluate to True or False

130
Making Decisions
No program is very useful without being able to
make decisions about what to do.

If all we have are ints, floats, and strings it’s not


very helpful.

Sometimes we want to do one thing for some value


and something different for another value.
Conditional Statements
We use if and else to make decisions in our
everyday lives.

• If it’s raining, then I’ll use an umbrella.

• If it’s not raining, then I won’t use an umbrella.

• If it’s sunny, then I’ll go golfing.


Conditional Statements
• We use the same logic in our Python program.

is_raining = True

if is_raining:
use_umbrella = True
else:
use_umbrella = False
Conditional Statements
• Let’s break this down

is_raining = True

if is_raining:
use_umbrella = True
else:
use_umbrella = False

We create a new variable with the name is_raining


that holds a boolean (True/False) value.
Conditional Statements
• Let’s break this down

is_raining = True

if is_raining:
use_umbrella = True
else:
use_umbrella = False

Here we check whether is_raining is True


Conditional Statements
• We use the same logic in our Python program.

isRaining = True

if isRaining:
use_umbrella = True
else:
use_umbrella = False

If is_raining Then we make a new variable called


use_umbrella and set its value to True. Note in
Python “Then” is a colon :
Conditional Statements
• We use the same logic in our Python program.

is_raining = True
if is_raining:
use_umbrella = True
else:
use_umbrella = False

Otherwise (else) we do something else. In this case


make a new variable called use_umbrella and set its
value to False.
Conditional Statements
• We use the same logic in our Python program.

is_raining = True
if is_raining:
use_umbrella = True
else:
use_umbrella = False

Note that in Python, every “if” and “else” statement


is ended with a : (colon)
Conditional Statements
• We use the same logic in our Python program.

is_raining = True
if is_raining:
use_umbrella = True
else:
use_umbrella = False

Also Note that in Python, the statements that follow


“if” and “else” are indented.
Conditional Statements
• We use the same logic in our Python program.

is_raining = True
if is_raining:
use_umbrella = True
else:
use_umbrella = False

Also note that in Python, the values True and False


are capitalized.
Another Example
• If it’s sunny then I’ll go golfing.

is_sunny = True
if is_sunny:
go_golfing = True

What’s different?
Another Example
• If it’s sunny then I’ll go golfing.

is_sunny = True
if is_sunny:
go_golfing = True

There is no “else” clause in this decision. “If” can


be used by itself or with an else clause.
Conditional Statements
• What if we want to do many things depending on
certain conditions? We can use more than one if
clause.

• If today is less than the 10th day of the month


then I’ll go golfing.
• If it’s between the 11th and 20th day of the month
then I’ll go fishing.
• Otherwise, if today is greater than the 20th day of
the month, I’ll stay home.
Conditional Statements
today = 18
if today < 10:
print("go golfing")
elif today >= 10 and today <= 20:
print("go fishing")
else:
print("stay home")

Notice “else if” is shortened to elif in Python. Each


“if” and “else” still ends with a colon.
Conditional Statements
today = 18
if today < 10:
print("go golfing")
elif 10 <= today <= 20:
print("go fishing")
else:
print("stay home")

This is a shortcut way checking if “today” is


between 10 and 20.
Conditional Statements
today = 18
if today < 10:
print("go golfing")
elif today >= 10 and today <= 20:
print("go fishing")
else:
print("stay home")

• If today is less than the 10th day of the month then I’ll
go golfing.
• If it’s between the 11th and 20th day of the month then
I’ll go fishing.
• Otherwise, if today is greater than the 20th day of the
month, I’ll stay home.
Conditional Statements
today = 18
if today < 10:
print("go golfing")
elif today >= 10 and today <= 20:
print("go fishing")
else:
print("stay home")

Notice that we didn’t have to check if the day is


greater than 20 because the first two checks failed.
Since the first two conditions were False, the final
condition is automatic.
Conditional Statements
• You can use “if” by itself without any else
statements.
• You can use one or more elif statements together.
• You can only have one “automatic” or default case
called “else.”
• All if and elif statements must evaluate to True or
False:
• If [some condition] (== True)
• Do Something
• Else
• Do Something else
Conditional Statements
• Lastly, the statements that follow an if/elif/else
statement are not limited. You can include any
number of statements to execute.
• Example:

is_raining = True
if is_raining:
use_umbrella = True
wear_boots = True
print("It's raining.")
else:
print("It's not raining.")
Match-Case
Match Case
• Match-case is a cleaner way of writing a bunch of if/elif statements:
day = 4
if day == 1:
return "Monday"
elif day == 2:
return "Tuesday"
elif day == 3:
return "Wednesday"
else:
return "Invalid day"
Match-Case
if day == 0: match day:
print("Sunday") case 0:
elif day == 1: print("Sunday")
print("Monday") case 1:
elif day == 2: print("Monday")
print("Tuesday") case 2:
elif day == 3: print("Tuesday")
print("Wednesday") case 3:
else: print("Wednesday")
print("Unknown") case _:
print("Unknown")
Match-Case Program
day = int(input("Enter a number between 1 and 7: "))
match day:
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case 4:
print("Thursday")
case 5:
print("Friday")
# You can match multiple cases together
case 6 | 7:
print("Weekend!")
case _:
print("Invalid day")
Guard Clauses
• Guard Clauses are a way to “guard” certain conditions.

• Guard clauses are implemented with If

• Basic form:
case pattern if condition
Guard Clause
def describe_number(number):
match number:
case n if n < 0:
print("Negative number")
case n if n == 0:
print("Zero")
case n if n > 0:
print("Positive number")

describe_number(-5)
# Output: Negative number
Guard Clauses
match num:
case 0:
print("Zero")
case _ if num < 0:
print("Negative number")
case _ if 0 < num < 5:
print("Positive number")
case _ if num > 5:
print("Greater than 5")
case _:
print("Unknown")
Complex Case Conditions
• You can have complex conditions for each case.

case [“item”, variable]:


Complex Case Conditions
def process_command(command):
match command:
case ["move", direction]:
print(f"Moving {direction}")
case ["stop"]:
print("Stopping")
case ["shoot", target]:
print(f"Shooting at {target}")
case _:
print("Unknown command")

process_command(["move", "north"])
# Output: Moving north
process_command(["shoot", "enemy"])
# Output: Shooting at enemy
Loops
Doing things more than once
• Oftentimes, we want to repeat an operation.

• We want to do something more than once.

• We could use a function and call it repeatedly.

• Is there a better way?


Finding an average
temp1 = 89.5
temp2 = 88.3
temp3 = 93.0
temp4 = 90.1

temp1 +
temp2 +
temp3 +
temp4
Divided by total temps (4)
Finding an average
temp1 = 89.5
temp2 = 88.3
temp3 = 93.0
temp4 = 90.1

average = (temp1 +
temp2 +
temp3 +
temp4) / 4
That’s Ok
• That’s Ok if we have four temperatures

• What if we have 365, 10,000, or 1 million temperatures?

• We can use a loop to add each temperature to a running total.


Activity
• Develop an algorithm to calculate the average temperature.

• Assume you have a spreadsheet with one million temperatures to


average.
Loops
• Python gives us 2 types of loops

• for

• while
Loops
• We’ve seen basic variables (data types).

• We’ve seen how to make decisions (conditional


logic)

• What if we want to do something multiple times in


a row?
Loops
Suppose we want to print the numbers from 1 to
10.

How do we do that in Python?

print(1)
print(2)
print(3)
...
Loops
print(1)
print(2)
print(3)
...

That works. Now, suppose we want to print the


numbers 1 through 232 (4+ billion).

Now what?
Loops
Fortuantely, computers are really good at repetitive
tasks. The inventor of Python included ways for us
to do repetitive tasks. In Python we can use a “for”
loop with a “range” of numbers.

for num in range(10):


print(num)
Loops
for num in range(10):
print(num)

range is a function in Python that returns a list of


numbers up to the value provided to it.

We can combine the range() function with the for


keyword to create a loop.
Loops
for num in range(10):
print(num)

Notice that, like the “if” and “else” statements, “for”


statements are followed by a :

What this does is creates a variable called “num”


that holds one value from the range at a time and
prints it out.
Loops
for num in range(10):
print(num)
What this does is creates a variable called “num”
that holds one value from the range at a time and
prints it out.

Each iteration of the “for” loop automatically gets one


number from the range() function and assigns its
value to the “num” variable.

It then “falls” into the “body” of the for loop that


contains a single print() statement.
Loops
for num in range(100000000000000000):
print(num)

This is much better suited to a computer’s strengths


than ours!
Loops
for num in range(100000000000000000):
total = total + num
print(num)

Just like “if” statements, you can include any


statements or expressions you like in the “body” of the
for loop.
Loops
One nice thing about loops in Python is that you
can break out of them at any time:

for num in range(999999999999999999):


total = total + num
if total > 1000:
break
print(num)
Loops
One nice thing about loops in Python is that you can
break out of them at any time:

for num in range(999999999999999999):


total = total + num
if total > 1000:
break
print(num)

Here, we check if total is greater than 1000. If so,


we use the break statement to exit the for loop early.
While Loops
• While loops will execute as long as some
condition holds true.
• Example:

while True:
Do something
A Simple While Loop
i=1
while i < 6:
print(i)
i += 1

As long as i is less than 6, the loop continues


Using While with break
while True:
choice = input("Enter a number: ")
if choice == "exit":
break
# Do Something else
Modulo
• Modulo or Modulus is a division operation that returns the remainder.
• Modulo gives us the remainder portion instead of the quotient.

• Example:

4 / 2 = 2 remainder 0
4 / 3 = 1 remainder 1
Modulo
• 10 / 3 = 3 remainder 1

• In Python (and most other programming languages) we use the %


symbol instead of the / symbol.

• 10 % 3 = 1
• 11 % 2 = 1
• 23 % 3 = 2
• 10 % 2 = ???
Modulo
• The most frequent use of modulo is to check whether a number is even
or odd by dividing by 2.
• Even numbers will always have a modulo of zero
• Odd will always have a modulo of one.
• Example

• 10 % 2 = 0 Therefore, 10 is even
•9%2=1 . Therefore 9 is odd
The Continue Statement
• We’ve seen how to use break to exit a loop.
• What if we want to continue the loop and ignore
certain conditions?
• We can use the continue statement
Using continue to print even numbers
i=0
while i < 50:
i += 1
if i % 2 == 1:
continue
print(i)

2
4
6
...
Looping over Strings
• A very common use of loops in Python is to iterate over lists.
• Remember strings are a special type of list.

for letter in “Hello, World”:


print(letter)
Looping over lists
• Lists are collections of items. We can iterate over the list using a for
loop.

fruits = [‘apple’, ‘banana’, ‘orange’]


for fruit in fruits:
print(fruit)
Looping over Lists
• Suppose we want to check if an item is a member of a list. We can do so
by using in.

vowels = ['a', 'e', 'i', 'o', 'u']


greeting = "Hello, World!"

for char in greeting:


if char.lower() in vowels:
print(f"{char} is a vowel")
else:
print(f"{char} is not a vowel")
Activity
• Given the phrase:
“Python is awesome!”

Come up with an algorithm to count the number of vowels


in the phrase and print the total.
Solution

phrase = "Python is awesome!"


total_vowels = 0

for char in phrase:


if char.lower() in vowels:
total_vowels += 1

print(total_vowels)
Looping over a dictionary
• We often need to iterate over dictionaries as well.

• There are 3 ways:

1. Using the keys


2. Using the values
3. Using both
Iterating over a Dictionary
• With Keys
for key in dict.keys():
print(f"Key: {key}")

• With Values
for val in dict.values():
print(f"Val: {val}")

• With Items
for key, val in dict.items():
print(f"Key: {key}, Val: {val}")
One last thing…
• Sometimes we need to do a loop, check a value, or call a function but
don’t care about the return value.

• Python lets us “throw away” the value by using the underscore _ symbol.
Throwing a value away
books = {"Leo Tolstoy": "War and Peace",
"Albert Camus": "The Stranger",
"J.R.R. Tolkien": "The Hobbit",
"George Orwell": "1984”
}

for _, value in books.items():


print(value)

Ignore key or “throw it away”


Questions?

You might also like