Jed Rembold & Fred Agbo
January 31, 2024
What is the printed value of A
in the
code below?
>>> A = 10
>>> B = 5 % 3
>>> C = A * B ** B
>>> A -= B + A // 2
>>> A, B, C = C, A, B
>>> print(A)
??
Python defines two types of operators that work with Boolean data: relational operators and logical operators
Relational operators compare values of other types and produce a
True
/False
result:
== |
Equals | != |
Not equals | |||
< |
Less than | <= |
Less than or equal too | |||
> |
Greater than | >= |
Greater than or equal to |
Be careful! ==
compares two
booleans. A single =
assigns a
variable. The odds are high you’ll use one when you meant the other at
least once this semester!
Logical operators act on Boolean pairings
Operator | Description |
---|---|
A and B |
True if both terms True, False otherwise |
A or B |
True if any term is True, False otherwise |
not A |
True if A False, False if A True (opposite) |
or
is
still True
if both options are
True
not
with and
and
or
not A or B
Example: if n=0
, then the
x % n == 0
is never actually checked in the
statement
n != 0 and x % n == 0
since n != 0
already is
False
and
False and
anything is always
False
x % n == 0
statement would have erred out if
n=0
input
To retrieve data from a user, we can use Python’s built-in
input()
function
The form will generally look like:
variable = input(prompt_text)
variable
is the variable name you want
to assign the user’s typed input toprompt_text
is the string that will be
displayed on the screen to communicate to the user what they should be
doingThe input()
function always
returns a string
If you want to get an integer from the user, you will need to convert it yourself after retrieving it
num = int(input('Pick a number between 1 and 10: '))
Using a variable to track/control a loop state
finished = False
while not finished:
line = input("Enter a number: ")
if line == "":
finished = True
else:
print(line)
Building up a sequence from nothing using concatenation
new = ""
word = "fantastical"
i = 0
while i < len(word):
new += word[i]
i += 2
Python programs specify what part of the code is supposed to be executed when a program is run using a few special lines at the end of the program
if __name__ == '__main__':
function_to_run()
function_to_run
is the name of whatever
function you want to execute when the program is run directlyPatterns of this sort are commonly called boilerplate
NUM_ODDS = 100 # Constant, so using all caps
def print_odds():
"""
Prints the first NUM_ODDS odd numbers
starting at 1.
"""
value = 1
for i in range(NUM_ODDS):
print(value)
value += 2
if __name__ == '__main__':
print_odds()
Most common is to use import
to grab
everything in a library
import math
var = math.sqrt(4)
)Can also use from ... import
to grab
specific functions from the library
from math import sqrt
var = sqrt(4)
)math
definitionsCode | Description |
---|---|
math.pi |
The mathematical constant \(\pi\) |
math.e |
The mathematical constant \(e\) |
math.sqrt(x) |
The square root of x |
math.log(x) |
The natural logarithm of x |
math.log10(x) |
The base 10 logarithm of x |
math.sin(x) |
The sine of x in radians |
math.cos(x) |
The cosine of x in radians |
math.asin(x) |
The arcsin of x |
math.degrees(x) |
Converts from radians to degrees |
math.radians(x) |
Converts from degrees to radians |
if
functionalityif
and
else
elif
statementelif
chained
statements as you wantif condition_1:
# Run this code if
# condition 1 is true
elif condition_2:
# This code runs if
# condition 1 is false
# but condition 2 is true
elif condition_3:
# Runs if both condition 1
# and 2 fail but condition
# 3 is true
else:
# This code runs if
# all above conditions
# fail
We have already seen for
loops in
Karel, but let’s expand on their use:
The more general syntax of a for
loop
looks like:
for variable_name in sequence:
# code to loop over
variable_name
is a variable name that
will be assigned every value in the sequence over the course of the
loopsequence
is any expression that produces
a variable that supports iteration
range()
fill this
rolerange()
iterablerange()
function handles
this and produces the needed iterable objectBe careful, the range
function will stop
one step before the final stop value.
Providing just a stop argument:
for n in range(5):
print(n)
Providing a start and stop:
for n in range(1,11):
print(n)
Providing a start, stop, and step:
for n in range(10,0,-1):
print(n)
We can also use a for
loop to iterate
directly over a sequence of values
We can loop through a string or list to examine each individual character or element
Example of looping through a word to count occurrences of a given letter:
def count_letters(letter, string):
count = 0
for character in string:
if character == letter:
count += 1
return count
You can use Python’s assert
statement
to write test functions, which take the form:
assert condition
where condition
is any operation that
returns a True
or
False
Assert statements “expect” a condition to yield a
True
, and if they do, nothing happens
If an assert condition evaluates to
False
, an error is raised
Naming your test functions starting with the word
test_
will make them automatically
discoverable by other tools
count_letters
function from earlierdef test_count_letters():
""" Runs several tests on the function count_letters """
assert count_letters("z", "banana") == 0
assert count_letters("a", "strawberry") == 1
assert count_letters("A", "apple") == 0
assert count_letters("e", "eerie") == 3