CS51A - Spring 2019 - Class 2

Example code in this lecture

   bbq.py
   simple-functions.py
   bbq-functions.py

Lecture notes

  • Administrative
       - Assignment 1 posted
       - Send videos!
       - Lab this afternoon
          - 28 students in the class, 18 computers in the lab... bring your laptop if that's something you'd be interested/willing to do!
       - Lunch with me

  • look at bbq.py code
       - Recall from last time:
          - We're planning a party and we're trying to figure out how many hotdogs to order
          - We calculated it in the shell, but it's a pain to change/edit
       - I've typed in the same code we typed into the shell, but now in the text editing section
       - I've saved it in a file called bbq.py
          - we'll use the extension .py by convention to indicate a Python program
       - Anything different from what I'd typed before into the shell?
          - In a program (vs. typing it into the shell) if you want to see the value of a variable or an expression, you need to "print" it
             - If I didn't include this, I wouldn't get any answer (in fact I wouldn't see anything)
          - I've used whitespace
             - you can use spaces without affecting how the code executes
             - we use blank lines to make the code more understandable
          - I've included "comments"

  • comments
       - comments in Python are designated using '#' (the pound sign)
       - python ignores everything from the # to the end of the line
          - you can put them on lines by themselves
          - or if you have short comments, you can add them at the end of a line
       - comments are VERY important
          - they allow you to communicate in plain English (to others and to yourself when you look at the code later)
          - you will be required to put them in your programs for this course

  • running the code
       - With an IDE, not only can you edit code, you can also run it
       - the green arrow, runs the program
       - when you run a program, you get a brand new shell session (in the python shell)
          - Any variables, etc. you may have manually created in the shell window will NO LONGER EXIST
          - it executes your program a line at a time from the top
             - it's like you typed all of those commands in the shell
          - the one difference is that you don't get line-by-line feedback
             - for example, if you put 4+4 in a program on a line by itself, you won't see anything
          - if you want to see the value of a variable or an expression, you need to "print" it
       - if we run this program, we see 13 printed out, like we would expect

  • What is the syntax of a language (say English)?
       - It describes what are valid things to say in that language
          - "I like dogs" is syntactically correct (it's a determiner followed by a verb followed by a noun)
          - "I dog like" is not syntactically correct (it's a determiner followed by a noun followed by a verb)
       - programming languages also have there own syntax
       - it describes what is valid in a language

  • when syntax fails...
       - have we seen any examples of syntax so far?
          - all of the math operations have implicit syntax
          
             >>> 4+
             Traceback (most recent call last):
             File "<string>", line 1, in <fragment>
             invalid syntax: <string>, line 1, pos 3
       
              - this big mess tells us that we had a syntax error

          - assignment as well

          >>> dave =
          Traceback (most recent call last):
          File "<string>", line 1, in <fragment>
          invalid syntax: <string>, line 1, pos 7
       
       - the nice thing about using the WingIDE is that when you save a file, it checks the syntax and tries (but doesn't always succeed) at highlighting where the syntax error is
          - sometimes look at the line right before it if you can't find it on that line

  • functions
       - how did we print out the answer to our hotdog calculation last time?
          print(total_hotdogs)

       - print is a "function". What is a function in math?
       - A function in Python
          - has a name
          - has zero or more parameters (i.e. inputs)
             - how many parameters does print have?
          - generally does something
          - often gives us a value, though sometimes they don't (like print)
          - 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)
             10
             >>> abs(-10)
             10
             >>> round(10.4)
             10.0
             >>> round(10.5)
             11.0

             - Note all these functions have a single parameter and give us back a value
                - We'll talk more later about what it means to "give back" a value, but understand now that print only displays a value it doesn't do any calculation and doesn't give back a value, whereas round does!

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

  • 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, ...) :
             statement1
             statement2
             ...
             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 (called the "body" of the 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 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)
          49
          >>> dog_name()
          'Fido'
          >>> interest_calculator(1000, 3)
          30.0
       
       - 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 (similar to assigning to a variable with the name of the parameter)
          - then we execute the function line by line
          - 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 (i.e. combine) two strings you can use 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(x)
          '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 (2+5) 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 its 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 jasmine affect the number of hotdogs required

       - look at the hotdogs method in bbq-functions.py code
          - What does this function do?
             - same thing as our bbq program, just now we've encapsulated it as a program where we can pass it parameters
             >>> hotdogs(1, 2)
             13
             >>> hotdogs(1, 3)
             19

  • bbq functions
       - Look at the other functions in bbq-functions.py code: what do they do?
       - The rest of these functions don't really have any new features from the ones we've previously seen
       - notice that we can build up more complicated functions by using the simpler functions
       - don't forget that if you want to combine a string and an int/float, you need to convert the int/float to a string using str