def computepay(hours, rate):
if hours > 40.0:
p = rate * 40.0
p = p+(1.5*rate*(hours-40))
else:
p = rate*hours
return p
hours = float(input("Enter worked hours: "))
rate = float(input("Enter Pay rate per hour: "))
print computepay(hours, rate))
I am getting E902 - EOF in multi-line statement on the def computepay.
First of all welcome to Stackoverflow.
And here is your code after I corrected with proper indentation and brackets.
It should work:
def computepay(hours, rate):
if hours > 40.0:
p = rate * 40.0
p = p+(1.5*rate*(hours-40))
else:
p = rate*hours
return p
hours = float(input("Enter worked hours: "))
rate = float(input("Enter Pay rate per hour: "))
print(computepay(hours, rate))
Related
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.
I want to use bisection search to find out how much monthly payment should be in order to pay the full amount of balance within 12 months which user will input. However, this code I write goes into the infinite loop,showing "low, high, montlyPayment infinite times." I don't know which code causes this problem since conditional statement seems right to me .
initialBalance = float(raw_input('Enter the outstanding balance on your credit card'))
annualInterestrate = float(raw_input('Enter the annual credit card interest rate as a decimal'))
monthlyInterestrate = round(annualInterestrate, 2)
balance = initialBalance
while balance > 0:
numMonth = 0
balance = initialBalance
low = balance/12.0
high = (balance*(1+(annualInterestrate/12.0))**12.0)/12.0
epsilon = 0.01
monthlyPayment = round((high + low)/2.0, 2)
while abs(monthlyPayment*12.0 - initialBalance) >= epsilon:
print 'low =', low, 'high =', high, 'monthlyPayment =', round(monthlyPayment,2)
if monthlyPayment*12.0 < balance:
low = monthlyPayment
else:
high = monthlyPayment
monthlyPayment = round((high + low)/2.0, 2)
while balance > 0 and numMonth < 12:
numMonth += 1
interest = monthlyInterestrate * balance
balance -= monthlyPayment
balance += interest
balance = round(balance, 2)
print 'RESULT'
print 'monthly payment to pay off debt in 1 year:', monthlyPayment
print 'Number of months needed:', numMonth
print 'Balance:',balance
I have re-coded the above problem as
balance = 120000
annualInterestRate = 0.1
rate=annualInterestRate/12.0
high=(balance * (1 + rate)**12) / 12.0
low=balance/12.0
payment=0
bal_ref=balance
unpaid=balance
N=0
while (abs(unpaid) > .01):
month=0
pay=(high+low)/2
balance=bal_ref
while(month < 12):
unpaid=balance-pay
balance=unpaid + (unpaid * rate)
month +=1
if (abs(unpaid) < .01):
payment=pay
break
elif (unpaid > .01):
low=pay
elif (unpaid < -.01):
high=pay
N+=1
print("Payment:",round(pay,2))
The question is to find the fixed amount you need to pay to a credit card company when -
bal= the amount you need to pay at the beginning of 0th month
N = it is the monthly fixed amount to be to paid to the credit card company such that at the end of the year, you will have paid the total amount
int = interest rate of the credit card company
bal = int(raw_input("Enter balance"))
rate = int(raw_input("enter rate"))
lower_b = bal/12
upper_b = (bal + ((rate*bal)/1200))/12
N= (lower_b+upper_b)/2
def Credit(bal,rate,N):
global upper_b
global lower_b
i=1
k=bal
while (i<13):
print(N)
paid = N
bal = bal - paid
print("Balance remains to be paid is %s" %(round(bal,2)))
Interest = rate * bal /1200
print("The interest added on is %s" %(round(Interest,2)))
bal=bal+Interest
print ("The amount that needs to be payed is %s " %(round(bal,2)))
i=i+1
if bal==0:
return N
elif 50 < bal < 2000 :
lower_b = N
upper_b = upper_b
N = (upper_b +lower_b)/2
return Credit(k,rate,N)
elif -2000<bal< -50:
upper_b = N
lower_b = lower_b
N = (lower_b +upper_b)/2
return Credit(k,rate,N)
elif -50 < bal < 50:
return N
else:
return bal
result=Credit(bal,rate,N)
print(result)
My code never terminates. The problem is the value of N defined in the code is not changing. It remains fixed N = upper_b +lower_b)/2
Using recursion would not be the ideal approach, you also have logic errors including needing to get the interest rate for the month, your initial upper bound should be greater than the principal plus the interest. You can use a while loop with an inner for loop resetting the balance after each unsuccessful inner loop:
balance = int(raw_input("Enter balance"))
int_rate = float(raw_input("enter rate"))
int_rate /= 100
lower_b = balance / 12.
upper_b = ((balance * (1 + (int_rate / 12.0)) ** 12) / 12.0)
payment = (lower_b + upper_b) / 2
def Credit(bal, rate, low, high, pay):
new_b = bal
# calculate monthly interest rate
month_int = rate / 12
while abs(new_b) > 0.001: # use epsilon
# always reset balance
new_b = bal
for _ in range(12): # loop over 12 month range
new_b -= pay # deduct pay
new_b += month_int * new_b
# if we still have a balance we need to take more so set low to current payment
if new_b > 0:
low = pay
# else we took to much so set high to current payment
else:
high = pay
pay = (low + high) / 2.0
return "Lowest monthly payment over 12 months: {}".format(pay)
print(Credit(balance, int_rate, lower_b, upper_b, payment))
Trying to find the total time worked in this. Cant seem to figure out what I have wrong.
#Problem 3, Python, Extra Credit
hourStart = int(input("Please enter the hour that Jimmy started work."))
minStart = int(input("Please enter the minute on the hour that Jimmy started work."))
hourEnd = int(input("Please enter the hour that Jimmy ended work."))
minEnd = int(input("Please enter the minute on the hour that Jimmy ended work."))
lunchHourStart = int(input("Please enter that hour that Jimmy started lunch."))
lunchMinStart = int(input("Please enter the minute on the hour that Jimmy started lunch."))
lunchHourEnd = int(input("Please enter the hour that Jimmy ended his lunch break."))
lunchMinEnd =int(input("Please enter the minute on the hour that Jimmy ended his lunch break."))
start = hourStart * 60 + minStart
end = hourEnd * 60 + minEnd
totalTime = end + start
lunchStart = lunchHourStart * 60 + lunchMinStart
lunchEnd = lunchHourEnd * 60 + lunchMinEnd
lunchTime = lunchEnd - lunchStart
timeWorked = (totalTime - lunchTime) * 60
hoursWorked = int(timeWorked)
min = (timeWorked - hoursWorked) * 60
print (min)
Total time should be calculated as
totalTime = end - start
All durations are in minutes, so the following is already in minutes, and does not need to be multiplied by 60:
timeWorked = (totalTime - lunchTime)
Now you have timeWorked in minutes, so in hours that is:
hoursWorked = int(timeWorked / 60)
and the minutes would be the remainder:
minutesWorked = timeWorked % 60
The last 2 statements could be replaced with divmod():
hoursWorked, minutesWorked = divmod(timeWorked, 60)
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