Create an object called Accounts to be used for banking - python

Create an object called Accounts. This is to be used in a banking system.
Initialize the account with three data as inputs : Firstname, Lastname and initial deposit.
Create 4 additional member functions: Deposit, Withdraw, Fee Calculations, interest
The fee calculation is going to be $10 per month if the total amount in the account is less than $1000. Interest is set to be at 3%.
I already got the code to work once, however it was with all the variables as integers, meaning none of them were decimals. Here's what I have now and I keep getting errors:
input = 'John Doe 4893.27'
account = str(input)
account = account.split()
first_name = account[0]
last_name = account[1]
i_deposit = account[2]
i_deposit = float(i_deposit)
i_deposit = '{:.2f}'.format(i_deposit)
new_amount = 0
fee = 0
d = 0
w = 0
def Deposit(d):
d = float(d)
d = '{:.2f}'.format(d)
d = bin(d)
new_amount = bin(i_deposit) + d
new_amount = bin(new_amount)
return bin(new_amount)
def Withdraw(w):
w = float(w)
w = '{:.2f}'.format(d)
w = bin(w)
new_amount = bin(i_deposit) + w
new_amount = bin(new_amount)
return bin(new_amount)
def FeeCalc(money):
money = float(i_deposit)
if money <= 1000:
fee = 10
else:
fee = 0
fee = '{:.2f}'.format(fee)
return fee
i = 0
def Interest(i):
i = float(i_deposit)
i = int(i)
i = i * .03
i = '{:.2f}'.format(i)
return i
dep_amount = Deposit(d)
wit_amount = Withdraw(w)
net_amount = sum(dep_amount, wit_amount)
new_amount = int(new_amount)
int_fee = Interest(i)
Withdraw(276.84)
print(first_name, last_name, 'account information:', '\nInitial deposit: $', i_deposit, '\nNew balance: $', new_amount, '\nFee: $', fee, '\nInterest: $', int_fee)
The most recent error I can't seem to fix:
Traceback (most recent call last):
File "/Users/shardae/PycharmProjects/HW1/main.py", line 55, in <module>
dep_amount = Deposit(d)
File "/Users/shardae/PycharmProjects/HW1/main.py", line 23, in Deposit
d = bin(d)
TypeError: 'str' object cannot be interpreted as an integer
Process finished with exit code 1

When you use the "'{:.2f}'.format(some_variable)" function, you are actually converting whatever variable you are assigning a value into a string. I don't believe that is what you after. With that, let me offer up some revision to your program that keeps the spirit of your code.
input = 'John Doe 4893.27'
account = str(input)
account = account.split()
first_name = account[0]
last_name = account[1]
i_deposit = float(account[2])
def Deposit(amount, d):
amount = amount + d
return amount
def Withdraw(amount, w):
w = (int(w) * 100) / 100 # Example of insuring precision to two decimal places
amount = amount - w
return amount
def FeeCalc(money):
fee = 0
if money <= 1000.00:
fee = 10
return fee
def Interest():
i = float(i_deposit)
i = int(i)
i = i * .03
return i
new_amount = i_deposit # Set the work field to the initial deposit balance
int_fee = Interest() # Calculate interest and add it to the balance
new_amount += int_fee
new_amount = Withdraw(new_amount, 276.84) # Calculate the new balance once the withdrawal amount is applied
fee = FeeCalc(new_amount) # Subtract any bank fee if the balance has dropped below $1000.00
new_amount -= fee
print(first_name, last_name, 'account information:', '\nInitial deposit: $', '{:.2f}'.format(i_deposit), '\nNew balance: $', '{:.2f}'.format(new_amount), '\nFee: $', fee, '\nInterest: $', int_fee)
The code still does utilize floating point variables. However, the only time that specific formatting for two decimal points occurs is within the printed output.
Go ahead and review the tweaks and see if that fulfills the spirit of your solution.
Hope that helps.
Regards.

Related

How do I sum given data in written file in python

My code runs almost correctly. The program needs to take in a country name, software/hardware/accessory sales, and then give the average for each category per country, total sales for each category, and overall total sales. If the users opt to enter a second, third, etc country, the averages and total must all be added together to find each calculation. My code currently calculates all of those things, but it does it for each country separately and it doesn't correctly count the number of countries added. I don't know why or how to fix it, please help!
def request_countryname():
country_name = input('Please enter the country\'s name: ')
while len(country_name) < 2:
print('Name must be at least two chracters')
country_name = input('Please enter the country\'s name: ')
return country_name
def request_sales(product_type, country_name):
sales = float(input('Please enter the total sales for ' + product_type + ' in ' + country_name + ": "))
while sales == type(str) or sales < 0:
print('Sales must be a non-negative numeric input')
sales = float(input('Please enter the total sales for', product_type, 'in', country_name))
return sales
def request_data(sales_data):
sales_data = open('sales_data.txt', 'w')
records = 0
add_country = True
while True:
records += 1
country_name = request_countryname()
soft_sales = request_sales('software', country_name)
hard_sales = request_sales('hardware', country_name)
acc_sales = request_sales('accessories', country_name)
sales_data.write(f'{country_name}\n{soft_sales}\n{hard_sales}\n{acc_sales}\n')
add_country = input('Do you want to add another country? (Enter y/Y for Yes, any other key to stop): ')
if add_country == 'y' or add_country == 'Y':
records += 1
request_data("sales_data.txt")
analyze_data("sales_data.txt")
else:
print(records, 'record(s) successfully added to the file.')
print('----------------------------------------------\n')
sales_data.close()
return sales_data
def analyze_data(sales_data):
sales_data = open ('sales_data.txt', 'r')
software_sales = []
hardware_sales = []
accessory_sales = []
read_file = sales_data.readline()
while read_file != '':
soft_sales = sales_data.readline()
hard_sales = sales_data.readline()
acc_sales = sales_data.readline()
software_sales.append(float(soft_sales))
hardware_sales.append(float(hard_sales))
accessory_sales.append(float(acc_sales))
read_file = sales_data.readline().rstrip('\n')
soft_average= sum(software_sales)/len(software_sales)
hard_average = sum(hardware_sales)/len(hardware_sales)
acc_average = sum(accessory_sales)/len(accessory_sales)
total_soft = sum(software_sales)
total_hard = sum(hardware_sales)
total_acc = sum(accessory_sales)
total_sales = float(total_soft + total_hard + total_acc)
print('Average software sales per country: $' + format(soft_average, ',.2f'))
print('Average hardware sales per country: $' + format(hard_average, ',.2f'))
print('Average accessory sales per country: $' + format(acc_average, ',.2f'))
print('')
print('Total software sales: $' + format(soft_average, ',.2f'))
print('Total hardware sales: $' + format(hard_average, ',.2f'))
print('Total accessory sales: $' + format(acc_average, ',.2f'))
print('')
print('Total sales: $' + format(total_sales, ',.2f'))
sales_data.close
def main():
request_data("sales_data.txt")
analyze_data("sales_data.txt")
main()
Edit: my professor said the problem was in the request_data function, specifically the "while True" part because I need to specify what is true, I just don't know what.
I'm going to try to answer your question, but also give you some refactoring pointers that may be helpful:
def request_country_name():
country_name = ""
while len(country_name) < 2:
print('Name must be at least two characters')
country_name = input('Please enter the country\'s name: ')
return country_name
def request_sales(product_type, country_name):
sales = ""
while sales == type(str) or sales < 0:
print('Sales must be a non-negative numeric input')
try:
sales = float(input(f"Please enter the total sales for {product_type} in {country_name}: "))
except:
pass
return sales
def read_record(record):
header = {'country_name': str,'soft_sales': float,'hard_sales': float,'acc_sales': float}
str_dict = dict(zip(list(header.keys()), record.replace("\n", "").split(",")))
return {k:header[k](v) for k,v in str_dict.items()}
def request_data(sales_data_file="sales_data.csv"):
records = 0
add_country = True
while True:
records += 1
country_name = request_country_name()
soft_sales = request_sales('software', country_name)
hard_sales = request_sales('hardware', country_name)
acc_sales = request_sales('accessories', country_name)
with open(sales_data_file, 'w') as writer:
writer.write(f'{country_name},{soft_sales},{hard_sales},{acc_sales}\n')
add_country = input('Do you want to add another country? (Enter y/n): ').upper()
if add_country == 'Y':
analyze_data(sales_data_file)
else:
print(F"{records} record(s) successfully added to the file.\n----------------------------------------------\n")
break
def analyze_data(sales_data_file="sales_data.csv"):
latest_country_records = {}
with open(sales_data_file) as reader:
for line in reader.readlines():
data = read_record(line)
latest_country_records[data['country']] = data
total_soft = sum([v['soft_sales'] for v in latest_country_records.values()])
soft_average= total_soft/len(latest_country_records)
total_hard = sum([v['hard_sales'] for v in latest_country_records.values()])
hard_average = total_hard/len(latest_country_records)
total_acc = sum([v['acc_sales'] for v in latest_country_records.values()])
acc_average = total_acc/len(latest_country_records)
total_sales = total_soft + total_hard + total_acc
print('Average software sales per country: $' + format(soft_average, ',.2f'))
print('Average hardware sales per country: $' + format(hard_average, ',.2f'))
print('Average accessory sales per country: $' + format(acc_average, ',.2f'))
print('')
print('Total software sales: $' + format(total_soft, ',.2f'))
print('Total hardware sales: $' + format(total_hard, ',.2f'))
print('Total accessory sales: $' + format(total_acc, ',.2f'))
print('')
print('Total sales: $' + format(total_sales, ',.2f'))
def main():
request_data("sales_data.txt")
analyze_data("sales_data.txt")
if __name__ == "__main__":
main()
Alright, so after some refactoring -- I think your biggest issue was you weren't handling the file handlers well (I replaced with context managers) which led to some odd structuring -- ie. your "request_data" function was being called recursively (by itself) in an unnecessary way.
Some other things to note, in your final print out you were printing the avg in place of the totals -- also you avg & total calculations overlapped a bit (reuse the total and calc it first).
Last note, and one worth keeping front of mind -- 9 times out of 10 there's an existing, established data structure -- lean on those. In this case, csv is your friend, in others json will be helpful.
Storing the data in different rows leads to unneeded complexity, and if possible should be avoided.
FWIW -- I haven't run/tested this code so there may be a few errors

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)

Return multiple values in a function

I am doing a University project to create a plan ordering ticket program, so far these are what I have done:
First, this is the function finding the seat type:
def choosingFare():
print("Please choose the type of fare. Fees are displayed below and are in addtion to the basic fare.")
print("Please note choosing Frugal fare means you will not be offered a seat choice, it will be assigned to the ticketholder at travel time.")
listofType = [""] * (3)
listofType[0] = "Business: +$275"
listofType[1] = "Economy: +$25"
listofType[2] = "Frugal: $0"
print("(0)Business +$275")
print("(1)Economy +$25")
print("(2)Frugal: $0")
type = int(input())
while type > 2:
print("Invalid choice, please try again")
type = int(input())
print("Your choosing type of fare is: " + listofType[type])
if type == 0:
price1 = 275
else:
if type == 1:
price1 = 25
else:
price1 = 0
return price1, listofType[type]
And this is a function finding the destination:
def destination():
print("Please choose a destination and trip length")
print("(money currency is in: Australian Dollars: AUD)")
print("Is this a Return trip(R) or One Way trip(O)?")
direction = input()
while direction != "R" and direction != "O":
print("Invalid, please choose again!")
direction = input()
print("Is this a Return trip(R) or One Way trip(O)?")
if direction == "O":
print("(0)Cairns oneway: $250")
print("(2)Sydney One Way: $420")
print("(4)Perth One Way: $510")
else:
print("(1)Cairns Return: $400")
print("(3)Sydney Return: $575")
print("(5)Perth Return: $700")
typeofTrip = [""] * (6)
typeofTrip[0] = "Cairns One Way: $250"
typeofTrip[1] = "Cairns Return: $400"
typeofTrip[2] = "Sydney One Way: $420"
typeofTrip[3] = "Sydney Return: $575"
typeofTrip[4] = "Perth One Way: $510"
typeofTrip[5] = "Perth Return: $700"
trip = int(input())
while trip > 5:
print("Invalid, please choose again")
trip = int(input())
if trip == 0:
price = 250
else:
if trip == 1:
price = 400
else:
if trip == 2:
price = 420
else:
if trip == 3:
price = 574
else:
if trip == 4:
price = 510
else:
price = 700
print("Your choice of destination and trip length is: " + typeofTrip[trip])
return price, typeofTrip[trip]
And this is the function calculating the total price:
def sumprice():
price = destination()
price1 = choosingFare()
price2 = choosingseat()
sumprice = price1 + price2 + price
print("How old is the person travelling?(Travellers under 16 years old will receive a 50% discount for the child fare.)")
age = float(input())
if age < 16 and age > 0:
sumprice = sumprice / 2
else:
sumprice = sumprice
return sumprice
The error I have:
line 163, in <module> main()
line 145, in main sumprice = sumprice()
line 124, in sumprice
sumprice = price1 + price2 + price
TypeError: can only concatenate tuple (not "int") to tuple
Can someone help me? I am really stuck.
I can't return all the
These functions return 2 values each: destination(), choosingFare(), choosingseat().
Returning multiple values at once returns a tuple of those values:
For example:
return price, typeofTrip[trip] # returns (price, typeofTrip[trip])
So while calculating the sum of all prices, you need to access price, price1, price2 from the tuples:
sumprice = price1[0] + price2[0] + price3[0]
Alternatively: You can edit the code to return list/ dictionary or some other data structure as per your convenience.
First let me explain what happends when you write. return price, typeofTrip[trip].
The above line will return a tuple of two values.
Now for sumprice I think what you want is sum of all prices. So you just want to sum first element of returned values.
This should work for your case.
sumprice = price1[0] + price2[0] + price3[0]

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

NameError: global name 'totaloverpay' is not defined

I just started college and I am writing this code out for my college class and it keeps sending an error. Any enlightenment will help, maybe the problem is that I'm half asleep.
here is the code
def main():
overtime = int(0)
totaloverpay = float(0)
hours = int(input('How many hours did you work? NOTE** Hours can not exceed 86 or be less than 8 '))
while hours > 86 or hours < 8:
print('ERROR: Insufficient input. Try again')
hours = int(input('How many hours did you work? NOTE** Hours can not exceed 86 or be less than 8 '))
payrate = float(input('What is the payrate per hour for this employee? NOTE** Payrate can not exceed $50.00 or be less than $7.00 '))
while payrate > 50.00 or payrate < 7.00:
print('ERROR: Insufficient input. Try again')
payrate = float(input('What is the payrate per hour for this employee? NOTE** Payrate can not exceed $50.00 or be less than $7.00 '))
workhours(hours, payrate, overtime)
def workhours(hours, payrate, overtime):
if hours > 40:
overtime = (hours - 40) * -1
else:
regtime = hours + 0
paydistribution(hours, payrate, regtime, overtime)
def paydistribution(hours, payrate, regtime, overtime):
if hours >= 40:
halfrate = float(payrate * 0.5)
overpay = halfrate + payrate
totaloverpay = float(overpay * hours)
if hours < 40:
regpay = hours * payrate
display(hours, payrate, regpay, regtime, overtime)
def display(hours, payrate, regpay, regtime, overtime):
total = float(regpay + totaloverpay)
print(' Payroll Information')
print('Payrate :', format(payrate, '0.2f'))
print('Regular Hours :', format(regtime))
print('Overtime Hours:', format(overtime))
print('Regular Pay :', format(regpay, '6.2f'))
print('Overtime Pay :', format(totaloverpay, '7.2f'))
print('Total Pay :', format(total, '7.2f'))
main()
totaloverplay is not defined in any function below main in which it is referred to, or as a global variable. If you want it to be global, define it outside of the main function's scope.
This looks like a great use-case for a class rather than relying on functional programming.
from decimal import Decimal # more precision than floating point
MINIMUM_WAGE = Decimal("7.25")
OVERTIME_RATE = Decimal("1.5")
class Employee(object):
def __init__(self,first,last,MI="",payrate=MINIMUM_WAGE):
self.first = first.capitalize()
self.last = last.capitalize()
self.MI = MI.upper()
if not MI.endswith("."): self.MI += "."
self.payrate = payrate
self.hours = 0
#property
def name(self, reversed_=False):
return "{} {} {}".format(self.first,self.MI,self.last)
#property
def alphabetize(self):
return "{}, {}".format(self.last, self.first)
def payroll(self,numweeks=1):
regularhours = min(40*numweeks,self.hours)
OThours = max(0,self.hours-regularhours)
regularpay = regularhours * self.payrate
OTpay = round(OThours * self.payrate * OVERTIME_RATE,2)
return {"reghours":regularhours,
"overtime":OThours,
"regpay":regularpay,
"OTpay":OTpay,
"total":regularpay + OTpay}
def sethoursworked(self,amt):
self.hours = amt
def display(employee):
payrollinfo = employee.payroll()
print("{:^30}".format("Payroll Information"))
print("{:>30}".format(employee.name))
print("Payrate:{:>22}".format(employee.payrate))
print("Hours:{:>24}".format(payrollinfo['reghours']))
print("Overtime Hours:{:>15}".format(payrollinfo['overtime']))
print("Regular Pay:{:>18}".format(payrollinfo['regpay']))
print("Overtime Pay:{:>17}".format(payrollinfo['OTpay']))
print("-"*30)
print("Total Pay:{:>20}".format(payrollinfo['total']))
Adam = Employee("Adam","Smith","D")
Adam.sethoursworked(51)
display(Adam)
OUTPUT:
Payroll Information
Adam D. Smith
Payrate: 7.25
Hours: 40
Overtime Hours: 11
Regular Pay: 290.00
Overtime Pay: 119.62
------------------------------
Total Pay: 409.62
You should not get in the habit of using global; it's usually a sign that you're heading in the wrong direction. Instead, pass the variables you need around explicitly, using function arguments and return statements. Also, don't pass functions arguments they don't need to do their job, and prefer default arguments or explicit constants to "magic numbers". For example:
def workhours(hours, threshold=40):
if hours > threshold:
overtime = hours - threshold
regtime = threshold
else:
overtime = 0
regtime = hours
return regtime, overtime
def paydistribution(payrate, regtime, overtime, otrate=1.5):
regpay = regtime * payrate
overpay = overtime * payrate * otrate
return regpay, overpay
Now main can call:
regtime, overtime = workhours(hours)
regpay, overpay = paydistribution(payrate, regtime, overtime)
display(hours, payrate, regpay, regtime, overtime)
This keeps the flow mostly in main while letting the other functions do just their specific bits of the task.
In your position, I would also consider having a separate function to take user input, which loops until they provide something acceptable. An appropriate definition, for example:
def user_input(prompt, min_, max_):
Here is another cleaned-up version:
from textwrap import dedent
import sys
if sys.hexversion < 0x3000000:
# Python 2.x
inp = raw_input
else:
# Python 3.x
inp = input
MIN_HOURS = 8.
MAX_HOURS = 86.
MIN_RATE = 7.
MAX_RATE = 50.
OVERTIME_CUTOFF = 40.
OVERTIME_BONUS = 0.5
def get_float(prompt, lo=None, hi=None):
while True:
try:
val = float(inp(prompt))
if lo is not None and val < lo:
print("Value must be >= {}".format(lo))
elif hi is not None and val > hi:
print("Value must be <= {}".format(hi))
else:
return val
except ValueError:
print("Please enter a number")
def main():
hours = get_float("How many hours did you work? ", MIN_HOURS, MAX_HOURS)
rate = get_float("What is the hourly payrate? ", MIN_RATE, MAX_RATE)
time = min(hours, OVERTIME_CUTOFF)
pay = time * rate
overtime = max(0., hours - OVERTIME_CUTOFF)
overpay = overtime * rate * (1. + OVERTIME_BONUS)
print(dedent("""
Payroll Information
Payrate : $ {rate:>7.2f}
Regular Hours : {time:>4.0f} h
Regular Pay : $ {pay:>7.2f}
Overtime Hours: {overtime:>4.0f} h
Overtime Pay : $ {overpay:>7.2f}
Total Pay : $ {total:>7.2f}
""").format(rate=rate, time=time, pay=pay, overtime=overtime, overpay=overpay, total=pay+overpay))
if __name__=="__main__":
main()
which runs like
How many hours did you work? 46
What is the hourly payrate? 11
Payroll Information
Payrate : $ 11.00
Regular Hours : 40 h
Regular Pay : $ 440.00
Overtime Hours: 6 h
Overtime Pay : $ 99.00
Total Pay : $ 539.00

Categories