I am having some problem in my code, it is returning the regular hours and not overtime pay. I am new , and I belive I am not calling the function properly , any help will be appreciated. Thanks All...
def computepay(rate, hours):
if hours > 40:
salary = rate * hours
return salary
else:
return (hours-40)*1.5*rate + salary
hours = raw_input("Enter Hours:")
hourly = raw_input("Enter Rate:")
hours = float(hours)
hourly = float(hourly)
p = computepay(hourly,hours)
print p
You have got the code wrong here. The correct code will be:
def compute pay(rate, hours):
if hours <= 40:
return rate*hours
else:
return (hours-40)*1.5*rate + (40*rate)
In your code, in the else condition, you are using salary without defining/declaring it.
Related
here is my code
def computepay(h,r):
if h>40.0:
OT = 1.5*float(r)
p=OT
else:
ck = float(h)*float(r)
p=ck
return 'p'
hrs = input("Enter Hours:")
rate = input("Enter rate:")
h = float(hrs)
r = float(rate)
p = computepay(h,r)
print("Pay", p)
here are the parameters it needs to fill
4.6 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate for all hours worked above 40 hours. Put the logic to do the computation of pay in a function called computepay() and use the function to do the computation. The function should return a value. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking the user input unless you want to - you can assume the user types numbers properly. Do not name your variable sum or use the sum() function.
here is the sample code given
def computepay(h, r):
return 42.37
hrs = input("Enter Hours:")
p = computepay(10, 20)
print("Pay", p)
i've tried messing with indentation several times also removing else statement entirely
can I get some advice?
instead of return 'p' in line 8 of your code...
type return p so that it returns the variable instead of a string.
def computepay(h,r):
if h > 40.0 :
reg = r * h
OT = (h - 40.0) * (r * 0.5)
p= reg + OT
else:
p = h * r
return p
hrs = input("Enter Hours:")
rate = input("Enter rate:")
fh = float(hrs)
fr = float(rate)
p = computepay(fh,fr)
print("Pay",p)
def computepay(h,r):
if h>40.0:
p = 40.0*r
p = p + (h-40.0)*1.5*r
else:
p = h*r
return p
hrs = input("Enter Hours:")
rate = input("Enter rate:")
h = float(hrs)
r = float(rate)
p = computepay(h,r)
print("Pay", p)
my code:
def computepay():
mhours = (h - 40) * (r * 1.5) + uhours*r
return mhours
uhours = 40
try:
hours = input("Enter Hours please: ")
rate = input("Enter Rate per hours please: ")
h = float(hours)
r = float(rate)
if h <= uhours:
print('Pay', h * r)
elif h > uhours:
print('Pay', computepay())
except ValueError:
print('Please Enter a Number! not a word!')
Here is my code (btw I am new to Stackoverflow and coding in general so forgive me if I made some mistakes in formatting this question):
hours = int(input('Enter hours:'))
rate = int(input('Enter rate:'))
pay =('Your pay this month' + str((hours + hours/2) * rate))
def computepay(hours,rate):
pay =('Your pay this month' + str((hours + hours/2) * rate))
return pay
print(pay)
To take into account overtime versus regular rates of pay it seems like you will need to know how much time the employee worked in each category. With that in mind, here is a simplified example to illustrate some of the key concepts.
Example:
def computepay(hours, rate):
return hours * rate
regular_rate = float(input("Hourly rate in dollars: "))
regular_hours = float(input("Regular hours worked: "))
overtime_hours = float(input("Overtime hours worked: "))
regular_pay = computepay(regular_hours, regular_rate)
overtime_pay = computepay(overtime_hours, regular_rate * 1.5)
total_pay = regular_pay + overtime_pay
print(f"This pay period you earned: ${total_pay:.2f}")
Output:
Hourly rate in dollars: 15.00
Regular hours worked: 40
Overtime hours worked: 10
This pay period you earned: $825.00
My teacher told me to solve it in one function, computerpay . so try this .
def computepay(hours, rate):
if hours > 40:
reg = rate * hours
otp = (hours - 40.0) * (rate * 0.5)
pay = reg + otp
else:
pay = hours * rate
return pay
Then The input Output Part
sh = input("enter Hours:")
sr = input(" Enter rate:")
fh = float(sh)
fr = float(sr)
xp = computepay(fh,fr)
print("Pay:",xp)
def computepay(hours, rate) :
return hours * rate
def invalid_input() :
print("Input Numeric Value")
while True :
try :
regular_rate = float(input("Hourly rate in dollars: "))
break
except :
invalid_input()
continue
while True :
try :
regular_hours = float(input("Regular Hours Worked: "))
break
except :
invalid_input()
continue
while True :
try :
overtime_hours = float(input("Overtime hours worked :"))
break
except :
invalid_input()
continue
overtime_rate = regular_rate * 1.5
regular_pay = computepay(regular_hours, regular_rate)
overtime_pay = computepay(overtime_hours, overtime_rate)
total_pay = regular_pay + overtime_pay
print("PAY : ", total_pay)
This code calculates the regular wage with flat rates and overtime with time-and-half for any work hours over forty(40) hours per work week.
hour = float(input('Enter hours: '))
rate = float(input('Enter rates: '))
def compute_pay(hours, rates):
if hours <= 40:
print(hours * rates)
elif hours > 40:
print(((hours * rate) - 40 * rate) * 1.5 + 40 * rate)
compute_pay(hour, rate )
This code calculates the regular wage with flat rates and overtime with time-and-half for any work hours over forty(40) hours per work week.
hour = float(input('Enter hours: '))
rate = float(input('Enter rates: '))
def compute_pay(hours, rates):
if hours <= 40:
pay = hours * rates
return pay
elif hours > 40:
pay = ((hours * rate) - 40 * rate) * 1.5 + 40 * rate
return pay
pay = compute_pay(hour, rate)
print(pay)
I dont understand why the code doesnt work and they have repeated the questions to me 4 times. and say that float is not callable. i have tried doing this for quite awhile but i dont seem to get anything at all. is there any easier way for python3? I just learnt this language 2 weeks ago. its not a whole new world to me but many of the things i am not familiar with. such as indentation
def get_taxi_info():
flag_down = float(input("What's the flag-down fare: $"))
within = float(input("What's the rate per 400 meters within 9.8km? $"))
beyond = float(input("What's the rate per 350 meters beyond 9.8km? $"))
distance = float(input("What's the distance traveled (in meters)? "))
peak = input("Is the ride during a peak period? [yes/no]")
mid6 = input("Is the ride between midnight and 6am? [yes/no]")
location = input("Is there any location surcharge? [yes/no]")
surloca = float(input("What's the amount of location surcharge?"))
return (flag_down, within, beyond, distance, peak == 'yes', mid6 == 'yes', location == 'yes', surloca)
def calculate_taxi_fare():
dist = get_taxi_info()
if dist[3] > 9800:
extra = (dist[3] - 9800) % 350
if extra == 0:
a = (extra//350) + 22
else:
a = (extra//350) + 23
return a
elif dist[3] <= 9800:
extra = (dist[3] - 1000) % 400
if extra == 0:
a = (extra//400)
else:
a = (extra//400) + 1
return a
def peakornot():
peak = get_taxi_info()
if peak[4] == True and peak[5] == False:
surcharge = 1.25
return surcharge
elif peak[4] == False and peak[5] == True:
surcharge = 1.50
return surcharge
taxifare = calculate_taxi_fare()
info = get_taxi_info()
peak1 = peakornot()
taxifare = calculate_taxi_fare()
if info[6] == True:
payable = ((info[0] + (info[1] * taxifare()) + (info[2] * taxifare())) * peak1[0]) + info[7]
print ("The total fare is $" + str(payable))
elif info[6] == False:
payable = ((info[0] + (info[1] * taxifare()) + (info[2] * taxifare())) * peak1[0]) + info[7]
print ("The total fare is $" + str(payable))
The function calculate_taxi_fare returns a float, so on this line taxifare is a float
taxifare = calculate_taxi_fare()
Therefore you cannot say taxifare() because it looks like a function call, so you can just use for example
info[1] * taxifare
I am trying to figure out the best way to split up this function into two separate functions. One being Main() and the other being determineStatus(). I have to use Main() to call determineStatus. The code does exactly what I want it to do just not sure a effective way to split it up.
Not really sure a way to split it up without getting tons of errors.
message="How many current credit hours do you have?"
def determineStatus(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Please use whole numbers only. Not text nor decimals.")
continue
else:
return userInput
hours = determineStatus(message)
F=30
J=60
S=90
Max=200
if hours <= Max:
if hours < F:
print("You are classified as a Freshman")
if hours > F and hours < J:
print("You are classified as a Sophmore")
if hours >= J and hours < S:
print("You are classified as a Junior")
if hours >= S and hours < Max:
print("You are classified as a Senior")
else:
print("With",hours," hours you are either an Alumni, 2nd Degree seeking student or lying about your hours.")
determineStatus(message)
A right data structure is a great code-cutting tool.
# python 3.x
CLASSIFIER = [
# (min, max, status)
(0, 30, 'Freshman'),
(30, 60, 'Sophomore'),
(60, 90, 'Junior'),
(90, 200, 'Senior'),
]
def classify(hours):
assert hours >= 0, 'WTF, negative hours'
for (lower, upper, status) in CLASSIFIER:
if lower <= hours < upper:
return status
return 'Alumni, 2nd Degree seeking student or lying about your hours'
def ask(message):
while True:
try:
return int(input(message))
except ValueError:
print('Try entering a non-negative whole number again.')
def main():
hours = ask('How many hours? ')
print('With %d hours, you are %s' % (hours, classify(hours)))
# Optional: auto-invoke main() if we're being executed as a script.
if __name__ == '__main__':
main()
I would do it this way.
Create a module
F = 30
J = 60
S = 90
Max = 200
def determineStatus(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Please use whole numbers only. Not text nor decimals.")
continue
else:
return userInput
def calculateStatus(hours):
if hours <= Max:
if hours < F:
return "You are classified as a Freshman"
if hours > F and hours < J:
return "You are classified as a Sophmore"
if hours >= J and hours < S:
return "You are classified as a Junior"
if hours >= S and hours < Max:
return "You are classified as a Senior"
else:
return "With {0} hours you are either an Alumni, 2nd Degree seeking student or lying about your hours.".format(hours)
Now create a little script:
import temp
message = "How many current credit hours do you have?"
# You can repeat the lines below by using a while loop
hours = temp.determineStatus(message)
print temp.calculateStatus(hours)
For your multiple ifs, you get a warning from the Department of Redundancy Department!
If hours is not smaller than J, there's no need in checking it's greater than or equal to J.
Also, if hours = F, you'll return that the student is lying.
Finally, you won't return anything for hours = Max.
Here's an optimized determine_status function :
statuses = [
(30, 'Freshman'),
(60, 'Sophomore'),
(90, 'Junior'),
(200, 'Senior')
]
def determine_status(hours):
for max_hours, status in statuses:
if hours < max_hours:
return "You are classified as a %s" % status
return "With %d hours you are either an Alumni, 2nd Degree seeking student or lying about your hours." % hours
print(determine_status(0))
# You are classified as a Freshman
print(determine_status(30))
# You are classified as a Sophomore
print(determine_status(55))
# You are classified as a Sophomore
print(determine_status(75))
# You are classified as a Junior
print(determine_status(100))
# You are classified as a Senior
print(determine_status(205))
# With 205 hours you are either an Alumni, 2nd Degree seeking student or
# lying about your hours.
I'm very new to coding, and am working on an assignment in Python 3.5.2 and am getting a 'display_results not defined' error. Am I placing it in the wrong section?
Thanks in advance.
hourly_pay_rate = 7.50
commission_rate = 0.05
withholding_rate = 0.25
def startup_message():
print('''This program calculates the salesperson's pay.
Five values are displayed.
Hourly pay, commission, gross pay, withholding, and net pay.\n''')
def main():
startup_message()
name = input('Enter name: ')
sales_amount = float(input('Enter sales amount: '))
hours_worked = float(input('Enter hours worked: '))
hourly_pay_amount = hours_worked * hourly_pay_rate
commission_amount = sales_amount * commission_rate
gross_pay = hourly_pay_rate + commission_rate
withholding = gross_pay * withholding_rate
net_pay = gross_pay - withholding
display_results#<-----'not defined' error for calculations
def display_results(): #(parameters)
print('Hourly pay amount is: ', \
format(hourly_pay_amount, ',.2f'))
print('Commission amount is: ', \
format(commission_amount, ',.2f'))
print('Gross pay is: ', \
format(gross_pay, ',.2f'))
print('Withholding amount is: ', \
format(withholding, ',.2f'))
print('Net pay is: ', \
format(net_pay, ',.2f'))
main()
input('\nPress ENTER to continue...')
First, to call display_results, you need to provide an empty set of parentheses:
display_results()
It appears you have an indentation error as well, as it seems you intended to call display_results() from inside the call to main:
def main():
startup_message()
# ...
net_pay = gross_pay - withholding
display_results()
Without the indentation, you were attempting to access the name display_results immediately after defining main, but before you actually defined display_results.
Look at this very short program:
def main():
r = 2 + 2
show_result
def show_result():
print("The result of 2+2 is {}", format(r))
main()
This program will not work!! However, if you can fix all the bugs in this program you will have understood how to fix most of the problems in your longer example.
Here is an annotated solution:
def main():
r = 2 + 2
show_result(r) # Must indent. Include brackets and pass the
# variable
def show_result(r): # Include a parameter list.
print("The result of 2+2 is: {}".format(r)) # format is a string method
main()
You need to indent and pass parameters to display_results and use the correct syntax for format strings. In your case something like:
print('Hourly pay amount is: {.2f}'.format(hourly_pay_amount))
Your display_result is unindented. Correct the indentation and it should work
def main():
startup_message()
name = input('Enter name: ')
sales_amount = float(input('Enter sales amount: '))
hours_worked = float(input('Enter hours worked: '))
hourly_pay_amount = hours_worked * hourly_pay_rate
commission_amount = sales_amount * commission_rate
gross_pay = hourly_pay_rate + commission_rate
withholding = gross_pay * withholding_rate
net_pay = gross_pay - withholding
display_results()#<-----'not defined' error for calculations
Indent and execute () the function.
def main():
startup_message()
name = input('Enter name: ')
sales_amount = float(input('Enter sales amount: '))
hours_worked = float(input('Enter hours worked: '))
hourly_pay_amount = hours_worked * hourly_pay_rate
commission_amount = sales_amount * commission_rate
gross_pay = hourly_pay_rate + commission_rate
withholding = gross_pay * withholding_rate
net_pay = gross_pay - withholding
display_results() #<-----'not defined' error for calculations