Contents
This notebook is based on "Think Python, 2Ed" by Allen B. Downey
https://greenteapress.com/wp/think-python-2e/
In [1]:
7 // 3 # Floor division results in the quotient
Out[1]:
In [2]:
7 % 3 # Modulus returns the remainder
Out[2]:
In [3]:
5 == 5
Out[3]:
In [4]:
5 == 4
Out[4]:
True
and False
are not strings, nor are the equivalent to stringsbool
datatype==
:!=
Not equal>
Greater than<
Less than>=
Greater than or equal to<=
Less than or equal to=
is an assignment operator and ==
is a relational operator that tests equality
In [5]:
True and True
Out[5]:
In [6]:
True and False
Out[6]:
In [7]:
True or True
Out[7]:
In [8]:
True or False
Out[8]:
In [9]:
False or False
Out[9]:
In [10]:
True and (True or False)
Out[10]:
True
In [11]:
x = 1
if( x > 0 ):
print( 'x is positive' )
if
is called the conditionTrue
, then the indented portion is executed
In [12]:
if( 0 == x % 2 ):
print( 'x is even' )
else:
print( 'x is odd' )
In [13]:
y = 0
if( x < y ):
print( 'x is less than y' )
elif( x > y ):
print( 'x is greater than y' )
else:
print( 'x and y are equal' )
elif
is an abbreviation for "else if"elif
statements, butdon't go overboardelse
statement isn't required so don't use one if it doesn't make sense
In [14]:
# TODO - calculate a tax rate, tip or GPA example
In [15]:
if( x == y ):
print( 'x and y are equal' )
else:
if( x < y ):
print( 'x is less than y' )
else:
print( 'x is greater than y' )
In [16]:
# Using nested conditionals
if( 0 < x ):
if( x < 10 ):
print( 'x is a positive single-digit number' )
In [17]:
# Using logical operators - this is easier to read
if( (0 < x) and (x > 10) ):
print( 'x is a positive single-digit number' )
In [18]:
def countdown( n ):
if( n <= 0 ):
print( 'Blastoff!' )
else:
print( n )
# Recursive call
countdown( n - 1 )
countdown( 5 )
n <= 0
countdown
function from above
In [19]:
def countdown_unsafe( n ):
if( n == 0 ):
print( 'Blastoff!' )
else:
print( n )
# Recursive call
countdown( n - 1 )
In [20]:
# Uncomment this to see what will happen
# countdown_unsafe( 3.5 )
<=
acts as a failsafe if an incorrect value is passed to the function\n
newline charactereval
function to evaluate it as if it where a Python expressioncalculate_gpa
that takes the number of hours for each letter grade A through F and computes the GPA. Test your function with at least three different sets of letter grade hours.
In [21]:
def calculate_gpa( a_hours, b_hours, c_hours, d_hours, f_hours ):
# INSERT YOUR CODE HERE
return 0
calculate_fibonacci
that takes a parameter n
, denoting the $n$-th fibonacci number, and returns the fibonacci number.
In [22]:
def calculate_fibonacci( n ):
# INSERT YOUR CODE HERE
return 0