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. Write a function multiPrint which accepts two parameters: a string and a nonnegative integer representing the number of times that the string should be printed

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

  5. 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!
    
  6. Add the following function definition.
    def mystery():
       print("A")
       print("B")
       return "123"
       print("C")
       print("D")
    
  7. Call the function as follows. What is output to the shell? Explain in comments.
    myResult = mystery()
    print(myResult)
    
  8. Write a function toCelsius(temperature) that converts Fahrenheit degrees to Celsius degrees and returns the degrees in Celsius. (Hint: C = (F-32)*(5/9)). Call/invoke your function to test it.

Part 3: Optional - if you have time

  1. Write a function called displayStudentInfo which accepts two parameters: a string representing a student’s name and a nonnegative integer representing the student’s age. The function should print a sentence about the student. For example, displayStudentInfo("Bob", 20) would print “Bob is a 20 year old student.”

  2. Write a function called factorial which accepts one parameter: an integer n. The function should use a for loop to compute n! (\(1*2*3*...*n\)), and return the result. Call/invoke your function to test it.

  3. Write a function called firstSum which accepts one parameter: an integer n. The function should use a for loop to compute the sum of the first n numbers, and return the result. Call/invoke your function to test it via firstSum(50) which should compute and return the sumer of the first 50 numbers (that is, 1+2+3+….+49+50).

  4. 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.