2. Functions
Feel free to use your laptop
You are strongly encourage to work with others
When you get stuck, ask those sitting around you for help
Get used to working together in the labs
Peer teaching and peer learning has been empirically shown to be very effective
2.1. Pre Lab Exercises
-
5 but have it in a function that returns the result
-
8
2.2. Before Kattis
Write a function called
add_five_print(some_integer)
The code you write must be within a function
The function will take one parameter
some_integer
The function adds five to the parameter and
print
s out the resultThe function will not return anything
Call the function a few times to verify that it works properly
1def add_five_print(some_integer): 2 # stuff goes here
Write a function called
add_two_numbers_print(some_integer, some_other_integer)
The code you write must be within a function
The function will take two parameters
some_integer
andsome_other_integer
The function will calculate their sum and
print
out the resultThe function will not return anything
Call the function a few times to verify that it works properly
1def add_two_numbers_print(some_integer, some_other_integer): 2 # stuff goes here
Write a function called
add_two_numbers_return(some_integer, some_other_integer)
The code you write must be within a function
The function will take two parameters
some_integer
andsome_other_integer
The function will calculate their sum
The function will
return
the resultCall the function a few times to verify that it works properly
Run the following code and take note of the output
1result = add_two_numbers_return(4, 5) 2print(result)
Run the following code and take note of the output
1result = add_two_numbers_print(4, 5) 2print(result)
Why do these two functions behave differently when called?
Take note of when and where
print
is called
Write a function called
this_is_tough(n1, n2, n3, n4)
The code you write must be within a function
This function will take four parameters
n1
,n2
,n3
, andn4
This function will sum all four numbers
The function will
return
the resultYou can not make use of the addition operator (
+
) directly within this functionYou must make use of
add_two_numbers_return
three timesVerify correctness by running the function a few times
2.3. Kattis Problems
Do not forget the code we used last time to read input on Kattis
1data = input() # Read a WHOLE, SINGLE line of input
2data = data.split() # Split string into individual pieces
3a_var = int(data[0]) # Take string from data[X], convert it to int...
4b_var = int(data[1]) # ... And store it in some variable
Warning
The above code will only work when the input is 2 integers on the same line. You may need to hack this code to make it work for your particular problem.
Skip any of the following problems if you did them already.