First, let's talk briefly about guardians.
Read section 6.8 in the book and do the examples.
Remember is_even? It required an integer, but someone could put a floating-point value in there and get the wrong result! Let's defend that function with a guardian!
def is_even(integer): """Returns whether integer is even.""" #first, ensure that integer is an integer if not is_instance(integer, int): print("is_even only works on integers! Attempted: is_even(" + str(integer) + ")") else: return integer % 2 == 0
Trials!
>>> is_even(5) False >>> is_even(0) True >>> is_even(2.7182818284) is_even only works on integers! Attempted: is_even(2.7182818284) >>> is_even("horse") is_even only works on integers! Attempted: is_even(horse)
That's a little awkward, because it looks like horse is a variable there. Pro-Python-Tip: if we want it to print out with the little quotes, we can use the repr function instead of str:
if not is_instance(integer, int): print("is_even only works on integers! Attempted: is_even(" + repr(integer) + ")")
Test it out again!
Okay, now let's move on to the reassignment. Read sections 7.1 and 7.2 in the book and do the examples. This will probably either blow your mind or make perfect sense. I hope it does both!
Finally, read section 7.3 in the book and do the examples. You'll learn about another type of loop, while, that is like a combination of for and if.