CS50 - Spring 2026 - Class 2
Example code in this lecture
simple-functions.py
bbq-functions.py
Lecture notes
Administrative
- Assignment 1
- mentor sessions posted (start attending!)
- lecture notes posted
functions
- What is a function in math?
- something like: f(x) = x^2 + 3
- it has a name: f
- it has some inputs: x
- it does something: x^2 + 3
- 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 PyCharm 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
- We can interact with these functions, but running the file through python interactively:
- python -i simple-functions.py
- then, we can use the functions:
>>> dog_years(7)
49
>>> dog_name()
'Fido'
>>> interest_calculator(1000, 3)
30.0
- 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
- 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 "<stdin>", line 1, in <module>
interest_calculator(10)
~~~~~~~~~~~~~~~~~~~^^^^
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: line 1 (of what we typed)
- 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 jasmin 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?
- What will be returned if we call:
>>> bbq_plan(1, 2, 6)
'We need to buy 13 hotdogs and 12 sodas for a total cost of $15.75'
- A few other things to note about these functions:
- We can "build up" a longer string, but taking what's currently in it and adding to it, e.g.
string_var = string_var + "more text to add"
- python assumes one statement per line
- if you have a long statement, it will get automatically line-wrapped, but this makes it hard to read
- we can tell python that the line continues to the next line by adding a \
- for long lines, make sure to do this
- 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
print
- Running python in interactive mode (-i) is very useful for testing out your functions individually
- If you'd like your program to display a result, there is a function that prints out values: print
- E.g., we could add a print statement at the end of our code:
- print(bbq_plan(1, 2, 6))
- Now, if we run the program (just using the run button) it will load all of the functions, call bbq_plan, and then display/print the result
print function uses
- 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