Activity: More practice with functions

Create a file called more-functions.py. Save it to your cs100/ch1 folder.

  1. Define a function add(x, y) that adds its two parameter and returns the result. Call/invoke your function to test it.

  2. Define a function addPrint(x, y) that adds its two parameter and prints the result. Call/invoke your function to test it.

  3. Define a function subtract(x, y) that subracts y from x and prints the result. Call/invoke your function to test it.

  4. Define a function hello(name) that has a single parameter that is a string and prints out a few welcoming messages. For example, if “Heather” is passed as an argument via the function call hello("Heather"), then the function should print out:
    Hello, Heather
    Welcome to CS 100
    Have an awesome day!
    
  5. Add the following function definition.
    def mystery():
       print("A")
       print("B")
       return "123"
       print("C")
       print("D")
    
  6. 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

  1. Write a function that solves a generic quadratic equation of the form ax2 + bx + c = 0, where a, b, and c are passed as parameters. For example, your function call may look like solveQuadraticEquation(1, 3, 5), where the values of a, b, and c 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.