Lecture 3: For Loops, Booleans

Topics

Print vs Return (Briefly)

  • Difference between these functions: What do they return and what do they print?
def fn1(x):
    print("hi")
    "hello"
    x

def fn2(x):
    print("hey there")
    return x

def fn3(x):
    "greetings"
    return "yo"

For loops (again)

  • Python has a number of different "loop" structures that allow us to do repetition (computers are really good at doing repetitive tasks!)
  • The for loop is one way of doing this
  • There are a number of ways we can use the for loop, but for now the basic structure we'll use is:
for some_variable in range(num_iterations):
    statement1
    statement2
    ...
  • Here are a couple examples. What will each of these do?
def mystery1():
    for i in range(10):
        print(i)

def mystery2(n):
    total = 0
    for val in range(n):
        total = total + val
    return total

def double(n):
    # use a for loop!

Turtle Time

For Loops in turtle

  • Back to turtle, how can we use a for loop to draw a square?
  • What does the simple_star function in turtle-examples.py do?
    • draws a 36-sided star (or asterisk)
  • What if we wanted to have a star/asterisk with a different number of spokes?
    • look at asterisk_star function
      • figure out how we have to space the spokes
      • do a for loop over the number of spokes
        • each iteration in the loop draw a spoke
        • need to go backwards into the middle for the next spoke
        • rotate right based on the angle we calculated
  • what will simple_spiral, spiral and rotating_circles in turtle-examples.py do?
    • simple_spiral
      • i
        • i is just the name of a variable
        • for small loops (i.e. just a couple of statements), it's common to just us the variable name i (short for index)
      • each time, the length of the edge drawn will be longer by a factor of 5
        • 0, 5, 10, 15, 20, …
      • and will be at a 50 degree angle
        • if it is < 90 it will spiral out
        • > 90, spiral in
    • spiral
      • similar to simple_spiral, however now we've parameterized the length of the sides and the angle
    • rotating_circles
      • draws num circles
      • each one rotated "angle" degrees from the previous

Random Walk

  • run the walk function from turtle-examples.py
    • how is this being accomplished?
      • turns a random angle between -90 and 90
      • steps forward some step size
  • if you only want to import a single function, you can do that like:
from random import randint
  • before the * indicated all function and variables. Here, we just said the randint function
  • You can print out a bunch of random numbers if you're curious:
for i in range(100):
    print(randint(0,10))
  • look at walk function in turtle-examples.py
    • went through the loop num_steps times/iterations
    • uses the uniform function to get an angle between -90 and 90
  • what will the pretty_picture function do?
    • draws a line
      • at an angle between -90 and 90
      • of length between 10 and 60
    • then draws a star
      • of length between 10 and 60
      • with int(spokes) spokes
        • remember, if we want an integer, for example to be used in range, you need to turn it into an int

Booleans

  • We've seen three types so far: int, float and str (string)
  • Python has another type called bool (short for boolean)
    • bool can only take the value True or False
  • bool's generally result from asking T/F question
  • What questions might we want to ask on data we've seen so far (e.g. numbers)?
    • comparison operators
      • == (equal)
        • notice that = is the assignment operator while == asks whether two things are equal
      • != (not equal)
      • < (less than)
      • > (greater than)
      • <= (less than or equal to)
      • >= (greater than or equal to)
  • Using the comparison operators
>>> 10 < 0
False
>>> 11 >= 11
True
>>> 11 > 11.0
False
>>> 11 >= 10.9
True
>>> 10 == 10.1
False
>>> "test" == "test"
True
>>> "test" == "TEST"
False
>>> 10 != 10
False
>>> 10 != 11
True
>>> "banana" < "apple"
False
>>> type(True)
<type 'bool'>
>>> type(0 < 10)
<type 'bool'>

Combining Booleans

  • we can also combine boolean expressions to make more complicated expressions
  • what kind of connectors might we want?
    • and
      • <bool expression> and <bool expression>
      • only returns True if both expressions are True
      • otherwise, it returns false

        >>> x = 5
        >>> x < 10 and x > 0
        True
        >>> x = -1
        >>> x < 10 and x > 0
        False
        
      • Truth table

        A B A and B
        T T T
        T F F
        F T F
        F F F
    • or
      • <bool expression> or <bool expression>
      • returns True if either expression is True
      • False only if they are both False

        >>> x = 5
        >>> x < 10 or x > 0
        True
        >>> x = -1
        >>> x < 10 or x > 0
        True
        
      • Truth table

        A B A or B
        T T T
        T F T
        F T T
        F F F
    • not
      • not <bool expression>
      • negates the expression

        • if it's True returns False
        • if it's False returns True
        >>> not 5 == 5
        False
        
      • Truth table

        A not A
        T F
        F T

if

  • the key use of bool is to make decisions based on the answers
  • the if statement allows us to control the flow of the program based on the result of a boolean expression
if bool_expression:
    # do these statements if the bool is True
    statement1
    statement2

statement3
  • the if statement is called a "control" statement in that it changes how the program flows
    • for is also a control statement
    • as the program runs, it evaluates the boolean expression
    • if it is true, it evaluates all of the statements under the "if" block and then continue on
      • it will execute statement1, statement2 and then statement3
    • otherwise (i.e. the boolean was false), it will skip these statements and continue on
      • it will just execute statement3
  • look at simple_if function in conditionals.py

User input

  • run silly_name function from conditionals.py
  • input
    • takes a string as a parameter
    • it displays the string to the user
    • then waits for the user to enter some text. The program doesn't continue until the user hits enter/return
    • whatever the user typed will be returned by the input function as a string
      • if you want a number you need to use int(...) or float(...)
  • first prompts the user for their name
  • depending on the input, the output of the program partially differs
    • if statements allow us to control the flow of the program
  • if-else: sometimes we'd also like to do something if the bool is False, in this case, we can include an "else"
if <bool expression>:
    # do these statements if the bool is True
    statement1
    statement2
else:
    # do these statements if the bool is False
    statement3
    statement4

Conditional Turtles

  • look at the add_circles function in conditional_turtle.py
    • setcolor_random function picks a random color
    • uses the if-elif-else statement to select between options
    • note that it saves the random number generated to use later in if-elif-else statements
      • you MUST save this number to a variable and not try and do your if/else statement based on new calls to random.randint
  • run add_circles function from conditional_turtle.py using setcolor_xy
    • picks random x and y coordinates to draw a circle
      • uses randint
    • How are the colors chosen?
      • each quadrant of the xy-axes is a different color
      • how can we do this?
        • want to ask a question about the x and y

Multiline Strings and Documentation

Quotes for days

Try copying and pasting each of these five strings into the Python console. What happens?

"hi\nthere"

"hi\
there"

"""hello"""

"""hello
    there"""

"""What happens
to
    whitespace?"""

Remember help()?

  • How does it know?
  • Docstrings!
    • A nice long comment at the top of each function
  • help(input)

Docstrings Forever

  • We'll be using docstrings on every function from here on out
  • Always use triple quotes (even if it's just one line of documentation)
  • Simple function, simple docstring
  • Longer function: talk about what it does, what the parameters are for, and why it might be useful

Style (Revisited)

  • Use good variable/function names
  • Use whitespace (vertical and horizontal) to make code more readable
  • Comment code — docstrings but also tricky parts of your functions
  • Try to write code as simply as possible
    • E.g. avoid repetition, prefer less error-prone approaches

Modules (Again)

  • Importing from math
    • Remember my ceil() example from before?
  • Defining your own modules
    • Any .py file is a module
    • Any .py file in the same folder as e.g. mod.py can import it using import mod.

Author: Joseph C. Osborn

Created: 2020-04-21 Tue 10:44

Validate