Skip to main content
Chemistry LibreTexts

2.6: Functions

  • Page ID
    206264
  • hyypothes.is tag: s20iostpy06ualr 
    Download Assignment S2020py06

     

    Learning Objectives

    Students will be able to:

    Content:

    • Explain the meaning and purpose of a function
    • Recognize a function definition, function header, and function call in a program
    • Combine the use of functions with if/else statements
    • Explain programs that use the same function multiple times
    • Use good test data for programs that include functions

    Process:

    • Write code that includes function definitions and function calls
    • Write programs that incorporate functions and if/else statements

    Prior Knowledge

    • Python concepts from Activities 1-5
    • Understanding of flowchart input symbols

    Further Reading

    Model 1: User defined Functions

    function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. A function definition is the segment of code that tells the program what to do when the function is executed. The first line of a function definition is known as the function header.

    Python Program 1
    # Programmer: Monty Python
    # Date: today's date
    # Program uses a function to print a message
    
    # User defined Function definition
    def printMessage():
        print("Welcome to Python.")
        print("Learn the power of functions!")
    
    # User defined Function definition
    def main():
        print("Hello Programmer!")
        # Function call
        printMessage()
    
    # Function Call
    main()
    print("Done!")


     

    Critical Thinking Questions:

     

    1. Closely examine the Python program above.
     

      a.  What Python keyword is used to indicate that a code segment is a user defined function definition?

      b.  What are the two function headers in the Python code?

      c.  The name of the user defined function is in the function header. What are the names of the two user defined functions?

      d.  Enter and execute the Python program.  What is the output?             

      e.  What one line of code could you add to the program to repeat the lines "Welcome to Python" and "Learn the power of functions!" twice. Where would you add the code?

     

    2.         Examine the following program

    Python Program 2
    # Description: This program uses a function to calculate
    # the area of a circle given the radius.
    
    import math
    
    def calculateArea(radius):
        area= math.pi * radius **2
        print("Area of a circle with a radius of", radius, "is",format(area,'.2f'))
    
    def main():
        radius = int(input("Enter the radius: "))
        calculateArea(radius)
    
    main()
    print("Done!")

     

    a.     Label the user defined function definition and the function calls.
     

    b.     The user defined function call and the function definition for calculateArea each include a variable within the parentheses. The variable in the function call is known as an argument. The variable in the function definition is called a parameter. What is the parameter in the function definition?  What is its purpose?

    c.     In this example the argument in the function definition and the argument in the function call have the same name.  Is this required?
     

    d.     Enter and execute the program. Verify your answer to question ‘c’ by changing the variable name and the function argument in the main function from radius to number. Do not change the parameter variable name in the function definition. Does the program still work?

     

    e.     Add a line of code to the main program that calls the calculateArea function and sends the value “6” as the argument. Execute the program to be sure it works properly.

     

    f.     Add another function to the program that calculates and prints the diameter of a circle, given the radius as the parameter. Place the function definition above call to the main function of the program. Write the function below.

     

    g.     Add another line of code to the main part of the program that calls the function that was created in part ‘f’. Send the radius entered by the user as the argument to the function.

    Note

    Parameter the variable listed inside the parenthesis of the function definition, there can be more than one variable (a,b below)
    Argument: the value sent to a function when it is called, there can be more than one value, and the number of values needs to equal the number of variables in the defined function being called (fname, lname). 

    def printName(a,b):
        print(a," ",b)
        
    fname=input("input your first name: ")
    lname=input("input your last name: ")
    
    printName(fname,lname)
    

     

    3. What is the purpose of a function?  Why do programmers use them?

     

    4.  Carefully examine the following program.

    Python Program 3

    def addNumbers(num1, num2):
        print(num1, "+", num2,"=",num1+num2)

    def subtractNumbers(num1, num2):
        print(num1, "+", num2,"=",num1-num2)

    def main():
        firstNumber = int(input("Enter a number between 1 and 10: "))
        secondNumber = int(input("Enter another number between 1 and 10: "))
        operator = input("Enter a + to add or a - to subtract: ")

        if operator == "+":
            addNumbers(firstNumber,secondNumber)

        elif operator == "-":
            subtractNumbers(firstNumber,secondNumber)
        
        else:
            print("Invalid operator!")
        
    ######call to main program #######
    main()
    print("Done!")

    a.         Circle the first line of code executed by the Python interpreter.

    b.         Enter and execute the program.  Use the following test data and indicate what the output is for each set of data.

    Data Set Operand 1 Operand 2 Operator
    1 2 6 +
    2 3 8 -
    3 34 23 *
    4 4 5 /

    c.         What problems did you notice when you entered Data Sets 3 and 4?

     

    d.         Add code to the program that would warn the user about the problems that could occur when data similar to that in Data Sets 3 and 4 are entered. See sample output below.  List the lines of code below the sample output.

    python logic code

    NOTE:  There are two types of Functions, Void Functions, that do not send back information to where they are called, and Value Returning Functions, that send back information to where they are called.

    5.  Enter and execute the code below. Carefully examine the code.

    Python Program 4
    # This program prompts the user for two numbers,
    # calls a function to determine the smaller number
    # and prints the smaller number that is returned from the function
    
    def getSmaller(num1, num2):
        if num1<num2:
            smaller = num1
        else:
            smaller = num2
        return smaller
    
    def main():
        userInput1 = int(input("Enter a number: "))
        userInput2 = int(input("Enter a second number: "))
        
        smallerNumber = getSmaller(userInput1,userInput2)
        print("The smaller of the two numbers is", smallerNumber)
    
    
    ###call to main program####
    main()
    print("Done!")
    

     

    a.         What is the new keyword used in the function definition? What do you think the keyword tells the program to do?

     

    b.         Circle the line of code from the program that includes the function call to getSmaller.

                         

    c.         In a void function, the function call is on a line by itself.  Why is this function call placed on the right-hand-side of an assignment statement?

     

    d.        What are the arguments used for the function call?

     

    6.         Examine the following Python program. 

    Python Program 5

    def getMolarity(grams, molMass, volume):
        volume = volume/1000
        molarity = grams/molMass/volume
        return molarity

    def main():
        grams = float(input("Enter grams of substance: "))
        molMass = float(input("Enter molar mass of substance in grams per mole: "))
        volume = float(input("Enter volume in milliliters: "))
        print("Your Molarity is: ", getMolarity(grams, molMass, volume)," mol/L.")

    main()
    print("Done!")

    a.         Circle the user defined function call in the main program.

     

    b.         How does the location of the function call in the main program differ from others you have seen today?

     

    c.         Is the function a void function or a value returning function?

     

     

    Information: Style guides define the maximum number of characters in a line of computer source code. The standard for python is 79 characters. This allows for several files to be open side-by-side, and makes code easier to read. You can read more at: https://www.python.org/dev/peps/pep-0008/#code-lay-out

    7.         The following Python program performs the same operations as found in question 6.

    Python Program 6
    def getMolarity(grams, molMass, volume):
        volume = volume/1000
        molarity = grams/molMass/volume
        return molarity
    
    def main():
        grams = float(input("Enter grams of substance: "))
        molMass = float(input("Enter molar mass of substance in grams per mole: "))
        volume = float(input("Enter volume in milliliters: "))
        print("The molarity of your solution is: ", 
              format(getMolarity(grams, molMass, volume),'.2f'), " mol/L.")
    
    main()
    print("Done!")

     

    a.         Circle the user defined function call in the main program

     

    b.         How does the program above show that a user defined function can be the argument of another function?

     

    c.         Why is the print function within the main function written on two lines?

     

    d.           Execute the program by copying and pasting this code into your IDE editor window.

     

    e.      What happens if you remove the indentation from the second line of the the print  

    function in the main function as show below:

     

     

    Copyright Statement

    cc4.0
    This work  is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License, this material is a modification by Ehren Bucholtz and Robert Belford of CS-POGIL content, with the original material developed by Lisa Olivieri, which is available here.


    Application Questions: Use the Python Interpreter to check your workfrog

    1.  Write a function that draws a frog. Call the function to be sure it works.
    Sample frog:  

     

    2.   Expand the program in #1 to produce the following output:

    four frogs

    3.         Write a Python program that prompts the user for three words and prints the word that comes last alphabetically. Use a function to create the program.