CS51A - Spring 2022 - Class 4

Example code in this lecture

   turtle-examples.py
   conditionals.py
   conditional-turtle.py

Lecture notes

  • admin
       - assignment 1 (how did it go?!)
       - Class and lab will be in person going forward. Edmunds 219 and 229 are right upstairs.
       - Prof Papoutsaki's office hours will be in person
       - Dr. Dave and Prof Ye will be via zoom still
          - Dr. Dave's office hours will start at 3pm today (instead of 2:30pm)

  • for loops in Python
       - 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 few simple examples. What will each of these do?

             # prints out the numbers from 0 to 9
             for i in range(10):
                print(i)

             # sum the numbers from 0 to n-1
             def sum(n):
                total = 0
                
                for val in range(n):
                   total = total + val

                return total

  • for loops in turtle
       - Back to turtle, how can we use a for loop to draw a square?
          - look at the iterative_square function in turtle-examples.py

       - 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 code 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

  • run the walk function from turtle-examples.py code
       - how is this being accomplished?
          - turns a random angle between -90 and 90
          - steps forward some step size

  • random module
       - there is another python module called "random"
       - http://docs.python.org/library/random.html
          - it generates pseudo-random numbers
             - what does this mean?
             - the numbers are not technically random, they're generated based on an algorithm
             - for most purposes this is pretty good
             - if you want truly random numbers, check out:
                - http://www.random.org/
                - also there are some programs that try and measure things like time between keystrokes, etc. to get some randomness (but these also aren't quite perfect)
       - many useful methods inside random
          - random -- random number between 0 and 1.0
          - uniform(a, b) -- random floats between a and b
          - randint(a, b) -- random integers between a and b
          - samples from many other distributions
             - beta
             - exponential
             - gamma
             - normal
       
       - for now, we're just going to utilize the randint function
       - 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 code
       - 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

  • 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

  • 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 truth table gives you a mapping from input to output for boolean functions

                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 B
                -------------
                T | F
                F | T
                
  • if statement
       - the key use of bool's 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
          - 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 code

  • run name_analysis function from conditionals.py code
       - 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

          statement5

          - if the boolean expression is true
             - execute statement1, statement2 then statement 5
          - if the boolean expression is false
             - execute statement3, statement4 then statement 5

  • look at name_analysis function from conditionals.py code
       - we first use the input function to get the user's name
          - input returns the text the user entered
          - in the variable "name" will be whatever the users entered
       - name == "Dave" checks whether the entered name is "Dave"
       - if statement directs the program's behavior depending on the answer
       - finally, regardless of the name, we print out "Nice to meet you..."

  • look at the add_circles function in conditional-turtle.py code
       - setcolor_xy function takes the x and y as a parameter and sets the fill color
       - what will this function look like?

  • look at setcolor_xy function in conditional-turtle.py code
       - uses the if-elif-else statement to select between the four options

  • run add_circles function in conditional-turtle.py code with setcolor_random function instead of setcolor_xy
       - what does this do?
          - randomly picks between blue, purple, red and yellow (instead of based on x, y)
       - how could we get this behavior?
          - use random.randint to select a number between 1 and 4
          - save this number and use it in an if-elif-else statement
             - you MUST save this number to a variable and not try and do your if/else statement based on new calls to random.randint
       - look at setcolor_random function

  • run forecast function in conditionals.py code
       - takes two parameters
          - temperature
          - amount of rain
       - depending on what these values are, gives us different answers
       - to start with, let's just look at the temperature. We want to define 4 temperature bands:
          - > 80 => "hot"
          - 71 - 80 => "warm"
          - 51 - 70 => "cool"
          - <= 50 => "cold"

          - say we have a variable called temperature with the temperature, how would we write the if statements for this?
             if temperature > 80:
                temp = "hot"
             if 70 < temperature <= 80:
                temp = "warm"
             if 51 < temperature <= 70:
                temp = "cool"
             if temperature <= 50:
                temp = "cold"
          - if we know the temperature is above 80, do we need to check any of the other ones?
             - no!
          - Python has another statement that allows us to represent this type of expression: elif

             if <bool expression>:
                statement1
             elif <bool expression>:
                statement2
             ... # we can have as many elif blocks as we want
             else:
                statement3
             
             statement4

             - the program starts with the first if statement. If it is true, it executes the statements in the if block then goes to the end (after else) and continues
             - if it is false, it goes to the first elif and see if it is true. If it is true, it executes the statements in the elif block then goes to the end (after the else) and continues
             - the program will keep going down the list of elif statements as long as none of them are true
             - if they are all false, then it will execute the statements under else
          - why is the elif useful?
             - avoids redundant calculations: if we know things are mutually exclusive, then once we find one that is true, don't need to check the others
             - can simplify the statements, when we get to an elif statement, we know that the above boolean checks are false and don't need to check those again

  • look at the temperature_report and precipitation_report functions in conditionals.py code
       - both use if-elif-else statements to calculate an answer

  • look at forecast function in conditionals.py code
       - uses the other functions to generate the answer