In [1]:
instructors = ['Dave', 'Joe', 'Dorkus the Clown']
instructors
Out[1]:
In [2]:
print("dave")
In [3]:
for instructor in instructors:
print(instructor)
In [4]:
for idx in range(len(instructors)):
print(instructors[idx])
In [5]:
for instructor in instructors:
if not "Clown" in instructor:
print(instructor)
else:
pass
In [6]:
for instructor in instructors:
if "Clown" in instructor:
pass
else:
print(instructor)
In [8]:
for instructor in instructors:
if not "Clown" in instructor:
print(instructor)
elif not "z" in instructor:
print(instructor)
else:
pass
In [ ]:
if 'Dorkus the Clown' in instructors:
print('#fakeinstructor')
Usually we want conditional logic on both sides of a binary condition, e.g. some action when True
and some when False
In [ ]:
if 'Dorkus the Clown' in instructors:
print('There are fake names for class instructors in your list!')
else:
print("Nothing to see here")
There is a special do nothing word: pass
that skips over some arm of a conditional, e.g.
In [ ]:
if 'Joe' in instructors:
print("Congratulations! Joe is teaching, your class won't stink!")
else:
pass
Note: what have you noticed in this session about quotes? What is the difference between '
and "
?
Another simple example:
In [ ]:
if True is False:
print("I'm so confused")
else:
print("Everything is right with the world")
It is always good practice to handle all cases explicity. Conditional fall through
is a common source of bugs.
Sometimes we wish to test multiple conditions. Use if
, elif
, and else
.
In [ ]:
my_favorite = 'pie'
if my_favorite is 'cake':
print("He likes cake! I'll start making a double chocolate velvet cake right now!")
elif my_favorite is 'pie':
print("He likes pie! I'll start making a cherry pie right now!")
else:
print("He likes " + my_favorite + ". I don't know how to make that.")
Conditionals can take and
and or
and not
. E.g.
In [ ]:
my_favorite = 'pie'
if my_favorite is 'cake' or my_favorite is 'pie':
print(my_favorite + " : I have a recipe for that!")
else:
print("Ew! Who eats that?")
In [ ]:
for instructor in instructors:
print(instructor)
You can combine loops and conditionals:
In [ ]:
for instructor in instructors:
if instructor.endswith('Clown'):
print(instructor + " doesn't sound like a real instructor name!")
else:
print(instructor + " is so smart... all those gooey brains!")
In [1]:
# Loops can be nested
for i in range(1, 4):
for j in range(1, 4):
print('%d * %d = %d' % (i, j, i*j)) # Note string formatting here, %d means an integer
# Can exist loop if a condition is met
for i in range(10):
if i == 4:
break
In [12]:
4 % 2
Out[12]:
In [21]:
N = 100
for candidate in range(2, N):
# n is candidate prime. Check if n is prime
is_prime = True
for m in range(2, candidate):
if (candidate % m) == 0:
is_prime = False
break
if is_prime:
print("%d is prime!" % candidate)