Week 3
Monday
Activity: More practice with functions
Create a file called more-functions.py
. Save it to your cs100/ch1
folder.
Define a function
add(x, y)
that adds its two parameter and returns the result. Call/invoke your function to test it.Define a function
addPrint(x, y)
that adds its two parameter and prints the result. Call/invoke your function to test it.Define a function
subtract(x, y)
that subractsy
fromx
and prints the result. Call/invoke your function to test it.Define a function
hello(name)
that has a single parameter that is a string and prints out a few welcoming messages. For example, if “Alice” is passed as an argument via the function callhello("Alice")
, then the function should print out:
Hello, Alice
Welcome to CS 100
Have an awesome day!
- Add the following function definition.
def mystery():
print("A")
print("B")
return "123"
print("C")
print("D")
- Call the function as follows. What is output to the shell? Explain in comments.
myResult = mystery()
print(myResult)
Part 3: Optional - if you have time
- Write a function that solves a generic quadratic equation of the form
a
x2 +b
x +c
= 0, wherea
,b
, andc
are passed as parameters. For example, your function call may look likesolveQuadraticEquation(1, 3, 5)
, where the values ofa
,b
, andc
are passed in as 1, 3, and 5, respectively. Note: to compute square root of 7 you may use:
import math
result = math.sqrt(7)
How to submit
Make sure you saved your work and that it runs without errors. Submit your demo-functions.py file on Moodle
.