CS51A - Fall 2019 - Class 2
Example code in this lecture
simple-functions.py
bbq-functions.py
bbq-functions-bad-style.py
Lecture notes
Administrative
- Send videos!
- Lab Friday afternoon
- Start in Edmunds 219 (upstairs)
- bring your laptop if that's something you'd be interested/willing to do!
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
- What are some other math operations we might want to support?
- A function in Python
- has a name
- has zero or more parameters (i.e. inputs)
- generally does something
- often gives us a value, though sometimes they don't
- 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 of 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 some functions will simply "do something" and then not give back a value
- 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):
Python Shell, prompt 2, line 1
builtins.TypeError: interest_calculator() missing 1 required positional argument: 'rate_percent'
- the first line gives some history about how the function was called (you can ignore this for now)
- the second line tells us where the error happened: Python shell on line 1
- the last line is the most important and tells us what the error was, i.e. that the function 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'
- A *very* common mistake is to forget to use str(), e.g.
>>> "The value of x is " + x
Traceback (most recent call last):
Python Shell, prompt 4, line 1
builtins.TypeError: can only concatenate str (not "int") to str
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
look at
bbq-functions-bad-style.py code
- what does this code do?
- These have the same functionality as the first three functions in
bbq-functions.py code
- But... they're much harder to read and understand. Use good variable names, good function names and whitespace to help make the code more readable (this is called using good style)