CS30 - Spring 2016 - Class 2

Example code in this lecture


Lecture notes

  • Administrative
       - Assignment 1 posted
       - Send videos!

  • functions
       - how did we convert an int to a float?
       - another way is to tell the shell you want the value represented by that expression to be a float

          >>> float(11)
          >>> float(11)/2

       - float is a "function". What is a function in mathematics?
       - A function in Python
          - has a name
          - has zero or more parameters
             - how many parameters does float have?
          - generally does something
          - often gives us a value
             - what type of value does float return?
                - a float :)
          - Python has many built-in functions. What are some that might be useful from a math standpoint?
             - abs (absolute value)
             - round
             - int (throws away the decimal part)
             - many more...

             >>> abs(10)
             >>> abs(-10)
             >>> round(10.4)
             >>> round(10.5)

          - Another interesting function: type
             - gives you the type of the expression
             >>> type(11)
             <type 'int'>
             >>> type(11/2)
             <type 'int'>
             >>> type(11.0/2)
             <type 'float'>

  • writing your own functions
       - the important components for a function are
          - the name of the function
          - how many parameters (or arguments) the function takes
          - what the function does
          - what value (if any) it returns/gives you when it's done
       - We can define our own functions using the following syntax

          def function_name(parameter1, parameter2, ...) :
             return expression # this is optional
          - function_name is the name of the function (i.e. what you want it to be called)
          - parameters are the list of parameters/arguments that are expected
             - you can use the parameters in the program like variables
             - when you call the function, the number of parameters specifies the number you must supply in the function call
          - the spacing indicates which statements are within a function
             - the tab key in WingIDE gives us 4 spaces
          - the "return" statement is the value that we want to return to whoever called us. We won't always have a return statement.

  • look at simple-functions.py code
       - Anything new here?
          - We have a third type, a string
          - strings are denoted by quotes and generally represent text
       - What do the first three functions do?
          - dog_years: calculates the number of dog years, given human years
          - dog_name: returns the name of the dog, as a string
          - interest_calculator: calculates the amount of interest earned for a given amount of money at a particular rate
       - If we "run" this file, what do you think will happen?
          - nothing gets printed out
          - but we've now defined new functions that we can use:

          >>> dog_years(7)
          >>> dog_name()
          >>> interest_calculator(1000, 3)
       - notice that the number of parameters defines how many arguments we must specify
       - when a function is called
          - we evaluate each of the arguments
          - these values are associated with the parameters
          - then we execute line by line of the function
          - if there is a return statement, where the original function call was made is replaced by the value returned

       - notice if we try to call one of our functions with the wrong number of arguments, we get an error

          >>> interest_calculator(1000)
          Traceback (most recent call last):
          File "<string>", line 1, in <fragment>
          TypeError: interest_calculator() takes exactly 2 arguments (1 given)

          - the first two lines don't mean much, but the last line tells us it takes 2, but we only gave it 1
       - if we knew that we wanted to run some of these functions, we could also add this to the end of the file and then that would get executed when we run it

  • strings
       - strings are another type (just like int or float)
       - They represent text
       - You can either use double quotes "this is a string" or single quotes 'this is also a string'
       - but you can't mix the two for any given string 'this is not a valid string"
       - if you want to concatenate two strings you can us the plus sign

          >>> "this is one string " + "plus another one"
          'this is one string plus another one'
       - If you want to include an int or a float in a string, you need to convert it to a string (just like int to float)

          >>> x = 4
          >>> "The value of x is " + str(4)
          'The value of x is 4'

  • dog_stats
       - has a single parameter
       - say we call the function as:
          >>> dog_stats(2+5)

       - The following will happen
          - first, we'll evaluate the argument to the function and get 7
          - 7 will then get associated with the parameter year
          - the first statement in the function calls our other function, dog_name()
             - this will go to the dog_name function and execute the code
             - dog_name will return "Fido", which will then get stored into the variable, name
          - the second statement is a call to the dog_years function
             - we evaluate it's argument (years), which gives us 7
             - 7 is then passed to dog_years
             - 7 is associated with the parameter human_years
             - 7*7 is calculated, giving us 49, which is returned
             - 49 is then stored in the variable "age"
          - finally, we return a string
             - "Fido" + " is " + "49" + " years old" -> "Fido is 49 years old"

  • advanced bbqing
       - if we look back at our bbq code, we notice that we only need information from some of the people to calculate the number of hot dogs
       - Who?
          - only teran and jasmin affect the number of hot dogs required

       - look at the hotdogs method in bbq-functions.py code
          - What does this function do?
          - Any things we haven't seen before?

  • multi-line 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

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

                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(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.

  • Look at the other functions in bbq-functions.py code
       - Anything else unusual? What do they do?

  • bbq functions
       - The rest of these functions are fairly straightforward
       - notice that we can build up more complicated functions by using the simpler functions
       - don't forget that if you want to print a string and and int/float, you need to convert the int/float to a string using str

  • print vs. return
       - print
          - the print statement 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 interpreter after defining these functions?

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

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