Class 6
Class 6
Fall 1 2024
Overview
Class Session 6
• Intro to Python
The Story So Far
Predicate Data
Programming Python
Logic Structures
- 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!")
• “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.
print("Hello, World!")
Input
• The opposite of print is input.
print(name)
Input
• All data captured by input is a string!!
#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.
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”{}”
Formatting output
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
print(f"Hello, {name}!”
A format string
print(f"Hello, {name}!”
"""This is
a multi-line
comment"""
A better program
Beyond “Hello, World!”
x = 10
y=2
print(x + y)
x = 10
2x = 10
Python:
x = 10
2 * x = 10
Variables
• Just like math, variables in programming languages hold real values.
x = 10
3. x = x / y
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
pi = 3.14159 Float
• 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]
• Consider books:
“author”: “title”
Data Types
Text Type: str
int, float,
Numeric Types:
complex
list, tuple,
Sequence Types:
range
Mapping Type: dict
40
Strings
• Strings in Python can be enclosed in single or double quotes.
• Be consistent; use one or the other.
The main advantage to single quotes is you can embed double quotes
without escaping them:
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.
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
name = "Alice”
print(name.lower())
# Output: 'alice’
print(name.upper())
# Output: 'ALICE'
Operations on Strings
• Replace part of a string with another string:
new_greeting =
greeting.replace("world", "Alice")
print(new_greeting)
# Output: 'Hello, Alice!'
Operations on Strings
• Remove leading and trailing whitespace:
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:
1
5
-13
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.
• 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:
56
Lists
• Unlike arrays in other languages, Python lists can store mixed types:
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.
• 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.
fruit1 = fruits[0]
print(fruit1)
#output: ‘apple’
Lists
• Unlike arrays in other languages, Python lists can store mixed data
types:
63
Another example
item3 = stuff[2]
print(item3)
#output: ‘Snoopy’
Lists
• Python strings are a special type of list.
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
print(greeting[0])
#output: ‘H’
print(greeting[6])
#output: ‘ ’
Operations on Lists
• Just like Strings, you can access individual elements of a list by their
position (index):
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.remove('blueberry')
print(fruits)
# Output: ['apple', 'cherry', 'orange']
Creating Lists
letters = list("Hello, World!")
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!")
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.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']
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.
• 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.
• 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"]
# Remove year
del cars["year"]
Other Dictionary Operations
• 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.
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.
104
Whitespace
• Whitespace is significant 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
def square(num):
return num * num
print(square(10))
2
𝐴 = 𝜋𝑟
pi = 3.14
radius = 5
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
def greet():
print("Hello, world!")
Anatomy of a Function
def find_largest_number(numbers):
...
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.
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}!")
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.
• 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.
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
is_raining = True
if is_raining:
use_umbrella = True
else:
use_umbrella = False
isRaining = True
if isRaining:
use_umbrella = True
else:
use_umbrella = False
is_raining = True
if is_raining:
use_umbrella = True
else:
use_umbrella = False
is_raining = True
if is_raining:
use_umbrella = True
else:
use_umbrella = False
is_raining = True
if is_raining:
use_umbrella = True
else:
use_umbrella = False
is_raining = True
if is_raining:
use_umbrella = True
else:
use_umbrella = False
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
• 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")
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.
• 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.
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.
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
• for
• while
Loops
• We’ve seen basic variables (data types).
print(1)
print(2)
print(3)
...
Loops
print(1)
print(2)
print(3)
...
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.
while True:
Do something
A Simple While Loop
i=1
while i < 6:
print(i)
i += 1
• Example:
4 / 2 = 2 remainder 0
4 / 3 = 1 remainder 1
Modulo
• 10 / 3 = 3 remainder 1
• 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.
print(total_vowels)
Looping over a dictionary
• We often need to iterate over dictionaries as well.
• 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”
}