CS21A Lab 3: Functions

CS21A            Lab 3:  Functions (25 points)
Learning Objectives for this lab include:
1. Understand how functions work.
2. Know how to define and call a function.
3. Learn how to declare local variables.
4. Learn how to pass arguments to functions.
Divide and Conquer
Lab 3 focuses on breaking up processes into many different functions so you become familiar with the concept of divide and conquer.  Large tasks divided into many smaller tasks will help them understand how functions and Python work together.
Naming Functions
Python requires that you follow the same rules that you follow when naming variables, which are
recapped here:
 You cannot use one of Python's key words as a function name.§
 A function name cannot contain spaces.§
 The first character must be one of the letters a through z, A through Z, or an underscore§
character (_).
 After the first character, you may use the letters a through z or A through Z, the digits 0§
through 9, or underscores.
 Uppercase and lowercase characters are distinct. §
Defining and Calling a Function
To create a function, you write its definition. Here is the general format of a function definition in Python:
def function_name():
A call is then made by a simple statement such as:
Using a Main Function
To reinforce the concept of everything centering on a main function, you should be always use a main( ).  The following figure demonstrates the general setup with a main function definition, and a call to main.  The main function should control the calls to all other functions within the program.
Indentation in Python
In Python, each line in a block must be indented.  Indentations that are not aligned evenly will cause compiler errors.
Local Variables and Passing Arguments
A variable's scope is the part of a program in which the variable may be accessed. A variable is
visible only to statements in the variable’s scope. A local variable's scope is the function in which the variable is created.
The following code will print that the value is 10 because the changevalue() cannot see the local value variable.  
#the main function
def main():
    value = 10
    print ('The value is ', value)
def changevalue():
    value = 50
#calls main
One way to fix this issue is to pass the value to the function and set it equal to the value.
Additionally, a return value statement is added to the function.  This is demonstrated in the
following code:
#the main function
def main():
    value = 10
    value = changevalue(value)
    print ('The value is ', value)
def changevalue(value):
    value = 50
    return value
#calls main
Multiple arguments can also be passed to functions simply by separating the values with commas.  The arguments and the parameter list must be listed sequentially.
A function can either be written by the programmer or a system function.  Both are used in this lab.
Returning Multiple Values from a Function
In Python, you are not limited to returning only one value. You can specify multiple expressions separated by commas after the return statement, as shown in this general format:
    return expression1, expression2, etc.
As an example, look at the following definition for a function named get_name. The function prompts the user to enter his or her first and last names. These names are stored in two local variables: first and last. The return statement returns both of the variables.
def get_name():
    # Get the user's first and last names.
    first = input('Enter your first name: ')
    last = input('Enter your last name: ')
    # Return both names.
    return first, last
When you call this function in an assignment statement, you need to use two variables on the left side of the = operator. Here is an example:
first_name, last_name = get_name()
The values listed in the return statement are assigned, in the order that they appear, to the variables on the left side of the = operator. After this statement executes, the value of the first variable will be assigned to first_name and the value of the last variable will be assigned to last_name.
Standard Library Functions
Python comes with a standard library of functions.  Some of the functions that you have used already are input, type, and range. Python has many other library functions. Some of Python's library functions are built into the Python interpreter. If you want to use one of these built-in functions in a program, you simply call the function. This is the case with the input, type, range, and other functions that you have already learned about. Many of the functions in the standard library, however, are stored in files that are known as modules. These modules, which are copied to your computer when you install the Python language, help organize the standard library functions. 
For example, functions for performing math operations are stored together in a module; functions for working with files are stored together in a module, and etc. In order to call a function that is stored in a module, you have to write an import statement at the top of your program. An import statement tells the interpreter the name of the module that contains the function.
Using Random
Python provides several library functions for working with random numbers. These functions are stored in a module named random in the standard library. To use any of these functions you first need to write this import statement at the top of your program:
import random
This statement causes the interpreter to load the contents of the random module into memory.
This makes all of the functions in the random module available to the program.
The random-number generating function used is named randint. Because the randint function is in the random module, you will need to use dot notation to refer to it in the program.
In dot notation, the function's name is random.randint. On the left side of the dot (period) is the name of the module, and on the right side of the dot is the name of the function.
The following statement shows an example of how you might call the randint function.
   number = random.randint(1, 100)
The part of the statement that reads random.randint(1, 100) is a call to the random
function. Notice that two arguments appear inside the parentheses: 1 and 100. These arguments tell the function to give a random number in the range of 1 through 100. 
Notice that the call to the randint function appears on the right side of an = operator. When the function is called, it will generate a random number in the range of 1 through 100 and then return that number.  
Variables can either be local or global in scope.
A local variable is created inside a function and cannot be accessed by statements that are outside a function, unless they are passed.
A local variable that needs to be used in multiple functions should be passed to the necessary functions. 
An argument is any piece of data that is passed into a function when the function is called.  A parameter is a variable that receives an argument that is passed into a function.
A global variable can be accessed by any function within the program, but should be avoided if at all possible.
Converting Data Types
When you perform a math operation on two operands, the data type of the result will depend on
the data type of the operands. Python follows these rules when evaluating mathematical
1. When an operation is performed on two int values, the result will be an int.
2. When an operation is performed on two float values, the result will be a float.
3. When an operation is performed on an int and a float, the int value will be temporarily converted to a float and the result of the operation will be a float. (An expression that uses an int and a float is called a mixed-type expression.)
A call to float must be used such as:
Average = float(number) / 10
Formatting in Python
When a floating-point number is displayed by the print statement, it can appear with up to 12 significant digits.  When values need to be rounded to a specific decimal, Python gives us a way to do just that with the string format operator. 
The % symbol is the remainder operator. This is true when both of its operands are numbers.
When the operand on the left side of the % symbol is a string, however, it becomes the string format operator. Here is the general format of how we can use the string format operator with the print statement to format the way a number is displayed:
print (string % number)
In the general format string is a string that contains text and/or a formatting specifier. A
formatting specifier is a special set of characters that specify how a value should be formatted.
number is a variable or expression that gives a numeric value. The value of number will be
formatted according to the format specifier in the string. Here is an example:
myValue = 7.23456
print ('The value is %.2f' % myValue)
Lab3.1: Retail Tax [10 points]
A retail company must file a monthly sales tax report listing the total sales for the month and the amount
of state and county sales tax collected. The state sales tax rate is 4 percent and the county sales tax rate is
2 percent. 
1. Open the Python program RetailTax.py.
2. Fill in the code so that the program will do the following:
 Ask the user to enter the total sales for the month.§
 The application should calculate and display the following:§
o The amount of county sales tax
o The amount of state sales tax
o The total sales tax (county plus state)
Consider the following functions for your program:
 main that calls your other functions§
 input_data that will ask for the monthly sales§
 calc_county that will calculate the county tax§
 calc_state that will calculate the state tax§
 calc_total that will calculate the total tax§
 print_data that will display the county tax, the state tax, and the total tax§
3. Save the code to a file by going to File         Save.
Python code
#This program uses functions and variables
#the main function
def main():
    print ('Welcome to the total tax calculator program')
    print()#prints a blank line
    totalsales = inputData()
    countytax = calcCounty(totalsales)
    statetax = calcState(totalsales)
    totaltax = calcTotal(countytax, statetax)
    printData(countytax, statetax, totaltax)
# this function will ask user to input data for monthly sales
def inputData():
# this function will calculate the county tax
def calcCounty(totalsales):
# this function will calculate the state tax
def calcState(totalsales):
# this function will calculate the total tax
def calcTotal(countytax, statetax):
# this function will display the the county tax, state tax, and total
Tax def printData(countytax, statetax, totaltax):
Write a program that will calculate a XXX% tip and a 6% tax on a meal price. 
1. Open the Python program MealPrice.py.
2. Fill in the code so that the program will do the following:
 The user will enter the meal price§
 The program will calculate tip, tax, and the total. §
 The total is the meal price plus the tip plus the tax. §
 Display the values of tip, tax, and total.§
The tip percent is based on the meal price as follows:
 MealPriceRange Tip Percent
.01 to 5.99 10%
6 to 12.00 13%
12.01 to 17.00 16%
17.01 to 25.00 19%
25.01 and more 22%
3. Save the code to a file by going to File         Save.
Python code:
#the main function
def main():
    print ('Welcome to the tip and tax calculator program')
    print()   #prints a blank line
    mealprice = _________
    tip = _________
    tax = _________
    total = _________
    print_info(mealprice, tip, tax, total)       
#this function will input meal price
def input_meal():
#this function will calculate tip at 20%
def calc_tip(mealprice):
#this function will calculate tax at 6%
def calc_tax(mealprice):
#this function will calculate tip, tax, and the total cost
def calc_total(mealprice, tip, tax):
#this function will print tip, tax, the mealprice, and the total
def print_info(mealprice, tip, tax, total):
#calls main
Here is a sample run:
Welcome to the tip and tax calculator program
Enter the meal price $34.56
The meal price is $ 34.56
The tip is $ 7.6032
The tax is $ 2.0736
The total is $ 44.2368
1. Include the standard program header at the top of your Python files.
2. Submit your files to Etudes under the “Lab 03”category.
Standard program header
Each programming assignment should have the following header, with italicized text appropriately replaced.
Note: You can copy and paste the comment lines shown here to the top of your assignment each time. You will need to make the appropriate changes for each lab (lab number, lab name, due date, and description).
 * Program or Lab #: Insert assignment name
 * Programmer: Insert your name
 * Due: Insert due date
 * CS21A, Summer 2014
 * Description: (Give a brief description for Lab 3) '''
Powered by