Write program that will calculate a tip and a tax on a meal

Assignment Help Python Programming
Reference no: EM131274403

Programming in Python

Lab: Functions

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():
statement
statement
etc.

A call is then made by a simple statement such as:

function_name()
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
changevalue()
print ('The value is ', value)

def changevalue():
value = 50

#calls main
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
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

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 expressions:

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

#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):

Programming in Python
# 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):

#calls main
Here is a sample run:
Welcome to the total tax calculator program

Enter the total sales for the month $12567
The county tax is $ 251.34
The state tax is $ 502.68
The total tax is $ 754.02

Lab: Tip, Tax, and Total

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

Submission

1. Include the standard program header at the top of your Python files.
2. Submit your files to Etudes under the "Lab 03"category.

RetailTax.py
MealPrice.py
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) '''

Reference no: EM131274403

Questions Cloud

How biological and psychological theories can be used : Compare and contrast how biological and psychological theories can be used to explain violent crime. Provide one shortcoming, or critique, in the utilization of these theories for measures of crime reduction.
Green supply chain management in organization : In 2 or 3 paragraphs demonstrate how you would use green supply chain management in your organization.
Do you think the court upheld the authority of congress : Do you think the court upheld the authority of Congress to pass the statute? Why or why not? What case discussed in this chapter is relevant to the decision?
Problem regarding the employee performance : Go toSAS's Websiteand review the benefits offered by this company by scrolling down to the middle of the web page and clicking the "Benefits" tab. Next, determine whether or not these types of benefits would motivate you as an employee for a long-..
Write program that will calculate a tip and a tax on a meal : Write a program that will calculate a XXX% tip and a 6% tax on a meal price. Each programming assignment should have the following header, with italicized text appropriately replaced.
Research restorative justice programs in the uk : Research restorative justice programs in the UK, Canada, Australia, or New Zealand and choose one on which to focus. In a well-written and informative paper, summarize the program's mission goals, and processes, and evaluate who benefits from the ..
Operating officer for thomason health system : You are the newly appointed chief operating officer for Thomason Health System (THS), a large health care delivery system that will be acquiring and implementing a new information technology system:
What do you think the outcome of this case was and why : The district court upheld the law and the Recyclers appealed.- What do you think the outcome of this case was and why?
Discuss your issue significance to public health : Discuss your issue's significance to public health. In other words, is it significant because it affects a large percentage of the population, does it affect a largely underserved/disadvantaged population, etc.? Be sure to provide examples and evi..

Reviews

Write a Review

 

Python Programming Questions & Answers

  Implement key exchange using the diffie-hellman algorithm

Implement key exchange using the Diffie-Hellman algorithm, when peer- to-peer connections are made between bots and achieve confidentiality through encryption of the client-server commu- nications with an appropriate block or stream cipher.

  Without using the system function to call any bash commands

without using the system function to call any bash commands write a python program that will implement a simple version

  Design a prgram using python

Design a prgram USING PYTHON that students can use to calculate what score they need on final exam to get a certan final grade for a course.

  Write a python program that starts from the starting state

Task consists of programming a Python implementation of a solver for the Desert Crossing Task - write a Python program that starts from the starting state.

  Write python code that will execute a list

Write python code that will execute a list of functions with supplied parameters and report the observed runtime for each function run. Assume that the input file has a list of strings like so:

  Displays the charges for a patients hospital stay

Write a program that computes and displays the charges for a patient's hospital stay. First, the program should ask patient name and if the patient was admitted as an in-patient or an out-patient.

  Write a program that will input the name of five students

Write clearly with documentations where necessary as you write the program to solve the following problem.

  Which stores and manipulates times on a 24 hour clock.

Complete the class Time, which stores and manipulates times on a 24 hour clock. As specified below, write the required methods, including those needed for overloading operators. Exceptions messages should include the class and method names, and ident..

  Build a utility app that helps customers figure out the cost

Build a utility app that helps their customers figure out the cost of items in the countries they visit on a trip. Bill thinks the app should run on any mobile phone, laptop, or desktop computer, since his customers come from all over the world.

  Write a python program that reads a dumbbasic program

You should write a Python program that reads a DUMBBASIC program from standard input1, and prints the results of executing that program to standard output.

  Print out the average score accurate to two decimal places

print out the average score accurate to two decimal places.

  The interest rate per period

The interest rate per period. For example, if your loan's interest is 6.5% per year, and you are paying monthly, this would be 6.5%/12. If you are paying every two weeks, r would be 6.5%/26, because there are 26 two-week periods in a year.

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd