CS51A - Fall 2019 - Class 3

Example code in this lecture

   bbq-functions.py
   print_vs_return.py
   bbq-functions-commented.py
   turtle-examples.py

Lecture notes

  • admin
       - assignment 1: due Thursday at 11:59pm
       - Mentor session hours
       - The book/reading
       - Practice problems

  • print function
       - very useful for helping you understand how your code is working
       - look at bbq_cost function in bbq-functions.py code
          - let's say you run this and the cost seems high:
             >>> bbq_cost(1,2,6)
             15.75

          - if you wanted to figure out *why* it was that high, you could temporarily add some print statements in the code, e.g.
             print("hotdogs: " + str(num_hotdogs))
             print("sodas: " + str(num_sodas))
          
          - if we run it again:
             >>> bbq_cost(1,2,6)
             hotdogs: 13
             sodas: 12
             15.75

          - We can dig further if we'd like by adding more print statements (e.g., "print(num_sodas * soda_cost)")
          - When you're done, REMOVE ALL PRINT STATEMENTS!
             - In most cases, we're adding print statements to help us *debug* our program

  • print vs. return
       - print
          - the print function prints the value to the screen/shell
       - return
          - a return statement has two parts:

          return [expression]

          - when the program gets to this line, it evaluates the expression. Whatever value this expression evaluates to then is "returned" from that function and represents the value at where the function was called.
       - Consider the following two functions (found in print_vs_return.py code ):

          def print_square(number):
             print(number * number)

          def return_square(number):
             return number * number

       - They do similar things, but their behavior is VERY different
       - What would be printed out if the following was typed into the Python shell after defining these functions?

          print_square(10)
          return_square(10)
          x = print_square(10)
          x
          y = return_square(10)
          y

          - the first two statements appear to do the same thing, but it is different. print_square is actually printing to the shell inside the function. return_square(10) evaluates to 100, then that value is printed because the default behavior for the shell is to print the value
          - This difference is highlighted in the next 4 statements
             - when we call print_square, it prints out the value, but does NOT return a value. Therefore, x remains undefined
             - when we call return_square, it will NOT print out the value, because it is part of an assignment statement. However, if we look at y, it gets the value returned.

       - What would happen if we added the lines below to the end of a file and the run it?

          print_square(5)
          return_square(5)
          print print_square(5)
          print return_square(5)

          - When you run a file, it starts at the top and executes each statement/line one at a time

          - The first call to print_square prints 25
          - The first call to return_square does NOTHING. It returns a value, but then we don't do anything with it (just as if we'd typed 5*5 there)
          - The second call the return_square print 25 again, then when we return we try and print out the value that was returned from print_square. Since print_square does not return a value, we get "None"
          - Finally, we print out another 25 for the 2nd call to return_square. In this case when the value is returned, we print it out.

       - other differences
          - return also affects the flow of the program. When you hit a return statement, that indicates to the program to leave the function

  • Look at the other functions in bbq-functions-commented.py code
       - What's new here?

  • multiline strings
       - So far we've seen double quotes and single quotes for strings
       - If we want a string to span over multiple lines we have a few options
          - there is a special character '\n' that represents the end of the line
             - we can put this in a string

             >>> print "This is a string\nthat spans over multiple\nlines"
             This is a string
             that spans over multiple
             lines

             - drawbacks of this approach?
                - hard to read as a human
                - hard to get formatting/alignment right
                - if it's a long string (e.g. a paragraph) it's going to go off the screen
                - pain to copy and paste multiline text from somewhere else
          - Python also includes multi-line strings
             - Use triple quotes (or triple single quotes) around a multiline string

                >>> print """This is a multiline string
                ... I can continue to type
                ... over many different lines
                ... and it won't stop until
                ... I close the strings"""
                This is a multiline string
                I can continue to type
                over many different lines
                and it won't stop until
                I close the strings

             - notice that until we close/end the triple quotes, Python continues to prompt us with "..." to let us know that we're still in the middle of something (at least at the shell)

  • docstrings
       - So, the long string after the function definition of hotdogs is a multiline string
       - Any idea why we put it here?
       - We can put a string immediately following the definition. This string is called a "docstring".
          - The docstring is another form of commenting
          - Besides being a useful comment, once we run this program, we can also get the docstring from the shell using the "help" functions

          >>> help(hotdogs)
          Help on function hotdogs in module __main__:

          hotdogs(teran, jasmin)
             Returns the number of hotdogs required for the party.

             Parameters:
                teran -- the number of hotdogs teran will eat
                jasmin -- the number of hotdogs jasmin will eat

       - This can be VERY useful when you're using code that you haven't written
          >>> help(abs)
          Help on built-in function abs in module __builtin__:

          abs(...)
             abs(number) -> number

             Return the absolute value of the argument.
       - conventions
          - We're going to be defining docstrings for ALL functions we write from here on out
          - We'll always use triple quotes for docstrings (even if they're just one line)
          - For simple functions, a one line docstring is sufficient
          - For longer ones, first give a description of what it does, then describe what each of the parameters represents.

  • good style
       - use good variable/function names
       - use whitespace (both vertical and horizontal) to make code more readable
       - comment code, including both comments and docstrings
       - try and write code as simply as possible (more on this as we go)

  • Modules
       - When I say the word module what does that make you think of?
       - A module in python is a collection of functions and variables
       - modules allow us to use code that other people have written
       - For example, there is a module called "math" that has many of the math functions you might want
          - We can look at the documentation for this module online by searching for "math python" or by going to docs.python.org and browsing searching there
          - http://docs.python.org/library/math.html
             - logs
             - sqrt
             - trigonemtric functions
             - constants
       - If we want to use a module, we need to tell the program to include it with our program. To do this, we need to "import" it
          - there are many ways of importing modules (some better than others)
          - for now, we're going to import the functions and variables into our program as if they were local (i.e. just as if we'd written them in our program)
             - this is convenient for now, but in some situations there are better ways of doing it (more on this later)
             
             from math import *

          - this statement has multiple components:
             - "from" is a keyword
             - "math" is the name of the module
             - "import" meaning, load them into our program
             - "*" means everything, i.e. everything in the math module

       - once we've imported a module, we can then use the functions in that module
          >>> log(10)
          2.302585092994046
          >>> sqrt(16)
          4.0
          >>> cos(10)
          -0.8390715290764524
       
       - notice that we just use them just like any other functions we've seen before
       - in a program, the imports are generally put at the top of the program
       - Python has LOTS of built-in modules and many more that you can download that other people have written
          - http://docs.python.org/library/   

  • turtle module
       - One of the modules that Python makes available is the "turtle" module
       - The turtle module implements a set of commands similar to the Logo programming language
          - some of you may have used Logo at some point in your schooling
          - http://en.wikipedia.org/wiki/Logo_(programming_language)

       - the basic idea is that you control the movements of a turtle (in our case, it will be an arrow) through basic commands such as
          - forward
          - backward
          - right
          - left
          - and many others

       - As the turtle moves, it draws a line behind it, so by giving it different commands, we can draw things on the screen
       - you can see the documentation for the turtle class online
          - http://docs.python.org/library/turtle.html
          - you'll be getting more comfortable with this documentation as part of the lab this week

       - We can import all of the functions, etc. from the turtle module just like we did for the math module

          from turtle import *

       - Once you've done this, then we can start playing with it

          >>> forward(100)
          >>> right(45)
          >>> forward(100)

       - the right and left commands are in degrees (though you can change the mode to radians if you prefer that)
       - how would we draw a square?
          forward(some_length)
          right(90)
          forward(some_length)
          right(90)
          forward(some_length)
          right(90)
          forward(some_length)

       - We can easily turn this into a function that takes the length as a parameter. For example, look at the square function in the turtle-examples.py code

       - This seems like a lot of repetitive typing. Let's say we can tell the turtle to repeat some statements, would there be a better way of creating a square (state it in English)?
          - go forward some length and then turn right, repeat this 4 times
       
  • 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
             ...

          - "for" is a keyword
          - "in" is a keyword
          - range is a function that we'll use to tell Python how many repetitions we want
          - num_iterations is the number of iterations that we want the loop to do
          - some_variable is a local variable whose scope (where it can be referred to) is only within the for loop
             - some_variable will take on the values from 0 to num_iterations-1 as each iteration of the loop occurs
             - for example, in the first iteration, it will be 0, 1 the second time, etc.
             - we're computer scientists so we start counting at zero :)
          - don't forget the ':' at the end
          - Like with defining functions, Python uses indenting to tell which statements belong in the for loop

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