Program for Internet Service Provider - python

I am writing an internet service provider program. My problem with the code is that it is not printing the monthly bill correctly.
For example:
If the user enters package "A" and num of hours used (say 9 hrs)
Then it should print 9.95 when the function printBill is called
My question: How can I call the data from getPackage() to the function printBill()
#Bill for Package A
def getPackageA(hours):
if (hours < 10):
return 9.95 #Cost of Package A
else:
return (hours-10)*2 + 9.95
#Bill for Package B
def getPackageB(hours):
if (hours < 20):
return 13.95 #Cost of Package B
else:
return (hours - 20) + 13.95
#Bill for Package C
def getPackageC():
return 19.95 #Cost of Package C
#Print Bill and savings
def printBill(bill):
if (bill != 0):
print("Your monthly bill is $", format(bill, '.2f'),
sep = '')
getSavings(bill)
print()
print()
else:
print()
#Checks and display savings if applicable
def getSavings(bill):
if(bill > getPackageA(hours)):
print("If you had package A, you'd save $",\
format(bill - getPackageA(hours),'.2f'), sep =
'')
if(bill > getPackageB(hours)):
print("If you had package B, you'd save $",\
format(bill - getPackageB(hours),'.2f'), sep =
'')
if(bill > getPackageC()):
print("If you had package C, you'd save $",\
format(bill - getPackageC(), '.2f'), sep = '')
def main():
bill = 1
#Asks user to enter choice of package and hours used
packageChoice = str(input("Enter package purchased (A,
B, or C): "))
hours = int(input("Enter the number of hours used: "))
if(packageChoice == 'A' or packageChoice == 'a'):
getPackageA(hours)
elif (packageChoice == 'B' or packageChoice == 'b'):
getPackageB(hours)
elif (packageChoice == 'C' or packageChoice == 'c'):
getPackageC()
else:
print("Package choice must be A, B, or C.")
printBill(bill)
main()

You can pass in multiple parameters to a function.
def printBill(bill)
becomes:
def printBill(bill,hours):
and you call it with:
printBill(bill,hours)
You will also have to pass it to getSavings in the same way.

You need to pass hours to every function that needs to use it, also when you RETURN something, it needs a place to get returned to. So you were saying if hours were < 10, return 9.95, but when you say return it sends the code back to the place it got called, you didnt assign this to a variable, so bill defaults to $1. Here is the updated code to work
#Bill for Package A
def getPackageA(hours):
if hours < 10:
return 9.95 #Cost of Package A
else:
return (hours-10)*2 + 9.95
#Bill for Package B
def getPackageB(hours):
if hours < 20:
return 13.95 #Cost of Package B
else:
return (hours - 20) + 13.95
#Bill for Package C
def getPackageC():
return 19.95 #Cost of Package C
#Print Bill and savings
def printBill(bill, hours):
if (bill != 0):
print("Your monthly bill is $", format(bill, '.2f'), sep='')
getSavings(bill, hours)
print('\n')
#Checks and display savings if applicable
def getSavings(bill, hours):
if bill > getPackageA(hours):
print("If you had package A, you'd save $",\
format(bill - getPackageA(hours),'.2f'), sep='')
if bill > getPackageB(hours):
print("If you had package B, you'd save $",\
format(bill - getPackageB(hours),'.2f'), sep='')
if bill > getPackageC():
print("If you had package C, you'd save $",\
format(bill - getPackageC(), '.2f'), sep='')
def main():
bill = 1
#Asks user to enter choice of package and hours used
packageChoice = str(input("Enter package purchased (A, B, or C): "))
hours = int(input("Enter the number of hours used: "))
if packageChoice in ('a', 'A') :
bill = getPackageA(hours)
elif packageChoice.lower() == 'b':
bill = getPackageB(hours)
elif packageChoice.upper() == 'C':
bill = getPackageC()
else:
print("Package choice must be A, B, or C.")
printBill(bill, hours)
main()
I also edited your main() function to show you different ways to check responses. You also don't need to wrap things in brackets in Python in IF statements.

To answer your question, you can simply do:
bill = 1
bill += getPackage() # call function and add return value to total bill
printBill(bill)

Related

Print function not being called?

When I run the script, It allows me to input the two user inputs i have in getSales function and getIncrease function, but does my print function at the end seems to do nothing. This is for an extra credit assignment which starts out as just the functions being defined with comments and i have to fill in the rest. Please enlighten me stack overflow community!
def main():
monnthlySales = getSales()
#call to get sales
# This function gets the monthly sales
def getSales():
monthlySales = float(input('Enter the monthly sales $'))
salesIncrease = getIncrease() #call to get sales increase
return monthlySales
# This function gets the percent of increase in sales
def getIncrease():
salesIncrease = float(input('Enter percent of sales increase: '))
salesIncrease = salesIncrease / 100
return salesIncrease
# This function determines the storeAmount bonus
def storeBonus(monthlySales):
if monthlySales >= 110000:
storeAmount = 6000
elif monthlySales >= 100000:
storeAmount = 5000
elif monthlySales >= 90000:
storeAmount = 4000
elif monthlySales >= 80000:
storeAmount = 3000
else:
storeAmount = 0
return storeAmount
# This function determines the empAmount bonus
def empBonus(salesIncrease):
if salesIncrease >= 0.05:
empAmmount = 75
elif salesIncrease >= 0.04:
empAmmount = 50
elif salesIncrease >= 0.03:
empAmmount = 40
else :
empAmmount = 0
return empAmmount
# This function prints the bonus information
def print(storeAmount, empAmount):
print('The store bonus amount is $', storeAmount)
print('The employee bonus amount is $', empAmount)
if storeAmount == 6000 and empAmount == 75:
print('Congrats! You have reached the highest bonus amounts possible!')
main()
At least from what I can see, your logic is correct, the only thing that it's necessary to change is to change the word print for any kind of function, class, etc. Python have reserved words such as print,return,if, etc. That serve for a specific use.
The only thing that you have to do is to rename your function def print() into any word that is not a reserved word.
def printBonus(storeAmount, empAmount):
printBonus('The store bonus amount is $', storeAmount)
printBonus('The employee bonus amount is $', empAmount)
if storeAmount == 6000 and empAmount == 75:
print('Congrats! You have reached the highest bonus amounts possible!')
I hope this works for you

Calculate the total of tickets and give a discount to student. There is a problem with function of the calculation the total and loops

Ticket sales. Calculate the total, based on the number of half price and full price tickets. If the user is a student, give a 50 cent discount for each ticket. Ask user to input number of child tickets, number of adult tickets, and if the person is a student (y/n). Keep asking until user enters a 0 and a 0
FULL_PRICE = 10.00
HALF_PRICE = FULL_PRICE % 2
giveDiscount = True
def calculatePrice(nHalfPriceTix, nFullPriceTix, giveDiscount):
if giveDiscount:
total = (nHalfPriceTix * HALF_PRICE) + (nFullPriceTix * FULL_PRICE) - .5
else:
total = (nHalfPriceTix * HALF_PRICE) + (nFullPriceTix * FULL_PRICE)
return total
while True:
print()
nChildTickets = input('How many child tickets do you want? ')
nChildTickets = int(nChildTickets)
nAdultTickets = input('How many adult tickets do you want? ')
nAdultTickets = int(nAdultTickets)
if (nChildTickets == 0) or (nAdultTickets == 0):
break
yesOrNo = input('Are you a student (y/n)? ')
if yesOrNo.lower() == 'y':
isStudent = True
else:
isStudent = False
thisTotal = calculatePrice(nChildTickets, nAdultTickets)
print('Your total is $' + thisTotal)
print()
totalSales = totalSales + thisTotal
print('Total of all sales $', totalSales)
Also to add on, this:
print('Your total is $' + thisTotal)
should be:
print('Your total is $' + str(thisTotal))
since the '+' operator in print() can only accept strings(not a float).
Or you could change the + to a ,.
calculatePrice function requires 3 arguments and got only two:
thisTotal = calculatePrice(nChildTickets, nAdultTickets)
so i think for that to work you need to pass isStudent because you didnt use it
thisTotal = calculatePrice(nChildTickets, nAdultTickets,isStudent)

need to add code from user input but not sure how

I'm working on a small personal project in Python 3 where you put in a name and get there weekly wages. I want to add a feature where an admin can come in and add a person to the workers, including their wages. Here's what I have as for people so far:
worker = input("Name: ")
if worker == "Anne":
def calcweeklywages(totalhours, hourlywage):
'''Return the total weekly wages for a worker working totalHours,
with a given regular hourlyWage. Include overtime for hours over 40.
'''
if totalhours <= 40:
totalwages = hourlywage * totalhours
else:
overtime = totalhours - 40
totalwages = hourlywage * 40 + (1.5 * hourlywage) * overtime
return totalwages
def main():
hours = float(input('Enter hours worked: '))
wage = 34
total = calcweeklywages(hours, wage)
print('Wages for {hours} hours at ${wage:.2f} per hour are ${total:.2f}.'
.format(**locals()))
main()
elif worker == "Johnathan":
def calcweeklywages(totalhours, hourlywage):
'''Return the total weekly wages for a worker working totalHours,
with a given regular hourlyWage. Include overtime for hours over 40.
'''
if totalhours <= 40:
totalwages = hourlywage * totalhours
else:
overtime = totalhours - 40
totalwages = hourlywage * 40 + (1.5 * hourlywage) * overtime
return totalwages
def main():
hours = float(input('Enter hours worked: '))
wage = 30
total = calcweeklywages(hours, wage)
print('Wages for {hours} hours at ${wage:.2f} per hour are ${total:.2f}.'
.format(**locals()))
main()
I want to add a part where if someone types in a code or something that they're an admin, it will let them add a person or edit an existing persons information.
I am not sure how you intend to deploy it, but even from the coding standpoint as it stands it will not behave the way you expect it to. I am guessing you are doing this just to learn. So, let me point out a couple of places where you have understood the basics wrong and a purely pedagogic example of how it could be done. Bear in mind that I strongly discourage from using this in any real context.
You have defined the function calcweeklywages twice in your code. When in fact it has to be defined just once. If you want to use the code, you call it, like you have done so in the main() program. The function works exactly the same for both your workers, so to get different weekly wages you pass different wages. But, how do you link their respective wages to their names (or some representation of them in your code)?
This is a good example where object oriented programming is used. A brief and entertaining primer is here. As for the code, it will look like this,
class Employee:
def __init__(self, Name, Wage = 0, Hours = 0):
self.Name = Name
self.Wage = Wage
self.Hours = Hours
def calcweeklywages(Employee, totalhours):
'''Return the total weekly wages for a worker working totalHours,
with a given regular hourlyWage. Include overtime for hours over 40.
'''
hourlywage = Employee.Wage
if totalhours <= 40:
totalwages = hourlywage * totalhours
else:
overtime = totalhours - 40
totalwages = hourlywage * 40 + (1.5 * hourlywage) * overtime
return totalwages
# In your main body, you just test the functionality
EmployeeList = []
EmployeeList.append(Employee("Anne", 34))
EmployeeList.append(Employee("Johnathan", 30))
while(True):
action = input('Exit? (y/n): ')
if(action == 'y'):
break
else:
name = input('Enter the employee\'s name: ')
for Employee in EmployeeList:
if(Employee.Name == name):
Person = Employee
hours = int(input('Enter the number of hours worked: '))
print('Wages for', hours, 'hours at', Person.Wage,'per hour is', calcweeklywages(Person, hours))
EDIT: I am sorry, I forgot about the admin part. But here goes,
class Employee:
def __init__(self, Name, Wage = 0, Hours = 0, Admin = False, code = ''):
self.Name = Name
self.Wage = Wage
self.Hours = Hours
self.Admin = Admin
self.code = code
def calcweeklywages(Employee, totalhours):
'''Return the total weekly wages for a worker working totalHours,
with a given regular hourlyWage. Include overtime for hours over 40.
'''
hourlywage = Employee.Wage
if totalhours <= 40:
totalwages = hourlywage * totalhours
else:
overtime = totalhours - 40
totalwages = hourlywage * 40 + (1.5 * hourlywage) * overtime
return totalwages
# In your main body, you just test the functionality
EmployeeList = []
EmployeeList.append(Employee("Anne", 34))
EmployeeList.append(Employee("Johnathan", 30))
EmployeeList.append(Employee("Mr. Admin", 50, 0, True, 'Open Sesame'))
while(True):
action = int(input('Enter action :\n 1. Exit.\n 2. Add new employee.\n 3. Compute weekly wage\n'))
if(action == 1):
break
elif(action == 2):
AdminName = input('Enter operator name : ')
Flag = False
for EmployeeInst in EmployeeList:
if((EmployeeInst.Name == AdminName) & (EmployeeInst.Admin)):
code = input('Enter code :')
if(code != EmployeeInst.code):
break
NewName = input('New Employee name? :')
NewWage = int(input('New employee wage? :'))
EmployeeList.append(Employee(NewName, NewWage))
Flag = True
if(not Flag):
print('Wrong Credentials')
break
elif(action == 3):
name = input('Enter the employee\'s name: ')
for Employee in EmployeeList:
if(Employee.Name == name):
Person = Employee
hours = int(input('Enter the number of hours worked: '))
print('Wages for', hours, 'hours at', Person.Wage,'per hour is', calcweeklywages(Person, hours))
else:
print('Input out of range')
break
But again, the session is not persistent between different kernel runs. There is no real "security", this is just an exploration of Python's object oriented code. Please do not use this for any real application. There is a lot more that goes with all this. You need to store it in a secure file, have some GUI front end etc etc. There are far wiser users who will guide you to implement the system as a whole. All the best with your studies. Cheers.

How to better implement a history of user action?

I decided to make a calculator as a project.
Implementing basic addition, subtraction, division, and multiplication was fairly easy.
I wanted to add more functionality so I decided to implement a list of results the user view. However, I had a difficult time keeping track of the results numerically. I wrote a maze of if statements that are functional but seem to be overwrought with code. I am sure there is a better way to handle this.
Any advice?
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
value = None
while True:
try:
value = x / y
break
except ZeroDivisionError:
print('Value is not dividable by 0, try again')
break
return value
def num_input(prompt='Enter a number: '):
while True:
try:
print(prompt, end='')
x = int(input())
break
except ValueError:
print('You must input a number. Try again.')
return x
def get_two_val():
x, y = num_input(), num_input()
return x, y
print("Welcome to Simple Calc")
# declaration of variables
num_of_calc_counter = 0
index_of_calc = 1
calculations = []
while True:
print("Choose from the following options:")
print(" 1. Add")
print(" 2. Subtract")
print(" 3. Multiply")
print(" 4. Divide")
print(" 5. Sales Tax Calculator")
print(" 6. Recent Calculations")
print(" 0. Quit")
usrChoice = num_input('Enter your choice: ')
'''
Menu workflow
options 1-4 take in two numbers and perform the specified calculation and
then add the result to a master list that the user can reference later.
lastly, the workflow increments the num_of_calc variable by 1 for recent
calc logic
option 5 is a simple tax calculator that needs work or option to enter
or find tax rate
option 6 returns a list of all the calculations perform by the user
'''
if usrChoice is 1:
numbers = get_two_val()
result = add(*numbers)
print(numbers[0], "plus", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 2:
numbers = get_two_val()
result = sub(*numbers)
print(numbers[0], "minus", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 3:
numbers = get_two_val()
result = mul(*numbers)
print(numbers[0], "times", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 4:
numbers = get_two_val()
result = div(*numbers)
print(numbers[0], "divided by", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 5:
tax_rate = .0875
price = float(input("What is the price?: "))
total_tax = tax_rate * price
final_amount = total_tax + price
print('Tax rate: ', tax_rate, '%')
print('Sales tax: $', total_tax)
print('_____________________________')
print('Final amount: $', final_amount)
#
elif usrChoice is 6:
if len(calculations) is 0:
print('There are no calculations')
elif num_of_calc_counter == 0:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif index_of_calc == num_of_calc_counter:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif num_of_calc_counter > index_of_calc:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter -= 1
elif num_of_calc_counter < index_of_calc:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif usrChoice is 0:
break
I don't know if you could find this simpler:
def num_input(prompt='Enter a number: '):
finished = False
while not finished:
string_input = input(prompt)
try:
input_translated = int(string_input)
except ValueError:
print('You must input a number. Try again.')
else:
finished = True
return input_translated
def division_operation(x, y):
if y == 0:
print('Value is not dividable by 0, try again')
return None
else:
return x / y
math_operations_values = [
(lambda x, y: x + y, 'plus'),
(lambda x, y: x - y, 'minus'),
(lambda x, y: x * y, 'times'),
(division_operation, 'divided by')
]
def get_two_val():
return (num_input(), num_input())
def operate_on_numbers(operation_index):
def operate():
numbers = get_two_val()
operator, operation_string = math_operations_values[operation_index]
result = operator(*numbers)
if result is not None:
print(numbers[0], operation_string, numbers[1], "equals", result)
calculations.append(result)
return operate
def tax_computation():
tax_rate = .0875
price = float(input("What is the price?: "))
total_tax = tax_rate * price
final_amount = total_tax + price
print('Tax rate: ', tax_rate * 100, '%')
print('Sales tax: $', total_tax)
print('_____________________________')
print('Final amount: $', final_amount)
def show_computations():
if calculations:
for (index, values) in enumerate(calculations, start=1):
print(f'{index}: {values}')
else:
print('There are no calculations')
calculations = []
finished = False
choices_actions = [
operate_on_numbers(0),
operate_on_numbers(1),
operate_on_numbers(2),
operate_on_numbers(3),
tax_computation,
show_computations
]
while not finished:
print("""
Choose from the following options:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Sales Tax Calculator
6. Recent Calculations
0. Quit""")
user_choice = num_input('Enter your choice: ')
'''
Menu workflow
options 1-4 take in two numbers and perform the specified calculation and
then add the result to a master list that the user can reference later.
lastly, the workflow increments the num_of_calc variable by 1 for recent
calc logic
option 5 is a simple tax calculator that needs work or option to enter
or find tax rate
option 6 returns a list of all the calculations perform by the user
'''
if user_choice == 0:
finished = True
else:
try:
operation_to_do = choices_actions[user_choice - 1]
except IndexError:
print('Please enter one of choice shown.')
else:
operation_to_do()

Get my search to solve only if solution is negative (MIT6.00)

Folks,
I am getting my head stuck in knots here with problem 3 from PS1 in MIT6.00. I have written a couple of functions (one bisection search, and one function modelling the credit card debt). The problem is that it converges on a solution that gives a slightly positive remaining credit card balance. I could lower the tolerance in the bisection search, but I wanted to know if there was some more elegant way of making this optimiser return only negative results.
Cheers,
Aiden
code:
import numpy as np
def bisection(a, b, fun, tol, var = None):
"""Note that this only works if you put the independant variable
as the first argument in the parameter """
#def tstr(x):
# return 2*(x**2) - 3*x + 1
#sol = bisection(0,0.9,tstr,0.1)
c = (a+b)/2.0
if var != None:
arga = var[:]
argc = var[:]
arga.insert(0,a)
argc.insert(0,c)
else:
arga = a
argc = c
if (b-a)/2.0 <= tol:
#Debugging print statement 1:
#print 'SOL1: c = ', c
if var != None:
return [c] + fun(argc)
else:
return c
if fun(argc)[0] == 0:
if var != None:
return [c] + fun(argc)
else:
return c
elif fun(arga)[0]*fun(argc)[0] < 0:
b = c
else:
a = c
return bisection(a, b, fun, tol, var)
"""
Now we have defined a version of the paidOff function to work
with the bisection method"""
def paidOffBis(args):#(Pay, Bal, Apr):
"""Tester for Bisection Implementation"""
# TEST SIZE OF args:
if (type(args) != list)|(np.size(args) != 3):
print 'Incorrect size or type of input, input size:', np.size(args), '-', args
return None
Pay, Bal, Apr = args
Mpr = Apr/12.0
Baln = Bal
Nm = 0
for n in range(12):
Baln = Baln*(1 + Mpr) - Pay
if (Baln < 0)&(Nm == 0):
Nm = n + 1
if Baln < 0:
return [Baln, Nm]
else:
return [Baln, Nm]
Out_Bal = float(raw_input('Enter the outstanding balance on your credit card: '))
Apr = float(raw_input('Enter the annual credit card interest rate as a decimal: '))
varin = [Out_Bal, Apr]
#(Out_Bal*(1 + (Apr/12.0))**12.0)/12.0
sol = bisection(Out_Bal/12.0, Out_Bal, paidOffBis, 0.01, varin)
print 'RESULT'
print 'Monthly payment to pay off debt in 1 year: $%.2f' % sol[0]
print 'Number of months needed:', sol[2]
print 'Balance: $%.2f' % sol[1]
To ensure a balance less than or equal to zero you need to set your conditional statements correctly - you need to keep searching till that criteria is met. You asked for ... a more elegant way .... Using descriptive names for your variables and keeping it simple would certainly improve your code. Here is one way to craft a solution using a bisection search.
annualInterestRate = .1
balance = 1000
def balance_after_one_year(balance, annualInterestRate, payment):
'''Calculate the balance after one year of interest and payments.
balance --> int or float
annualInterestRate --> float between 0 and 1
payment --> float
returns float
'''
for _ in xrange(12):
balance = (balance - payment) * (1 + annualInterestRate / 12.0)
return balance
def min_payment(balance, annualInterestRate, tolerance = .01):
'''Find the minimum payment to pay off a loan.
Uses a bisection search.
Ensures balance is not positive.
balance --> float, int
annualInterestRate --> float less than one
tolerance --> float
'''
# we want the tolerance to be negative
# this isn't strictly a tolerance, it is a lower limit
tolerance = -abs(tolerance)
hi = balance
lo = 0
while True:
payment = (hi + lo) / 2.0
tmp_balance = balance_after_one_year(balance, annualInterestRate, payment)
if tmp_balance < tolerance:
hi = payment
# ensure balance is not positive
elif tmp_balance > 0:
lo = payment
else:
return payment, tmp_balance
Usage:
min_pmt, final_balance = min_payment(balance, annualInterestRate)
print 'minimum payment', min_pmt
print 'final balance', final_balance

Categories