I'm new to python and had a question about to to use more functions in a code besides def main():
My code below works, but I am trying to add new def's to their respective areas.
So like a new def called (def calcPay():), to where the hours enter are calculated (regPay, overtimePay, and total) as 3 separate items.
&
Also add a new def called (def displayOutput():), the function would receive all three of the values from (overtimePay, regPay, and totalPay) and print the message below.
If someone could explain to me how to use new functions besides main, that would be greatly appreciated.
Thanks, here is my code:
def main():
try:
hoursWorked = float(input("How many hours did you work? "))
if hoursWorked > 40:
overtimePay = (hoursWorked - 40) * 15
regPay = 40 *10
totalPay =( overtimePay + regPay)
else:
regPay = hoursWorked * 10
overtimePay = 0
totalPay = (regPay + overtimePay)
print("You earned",'${:,.2f}'.format(regPay),"in regular pay",'${:,.2f}'.format(overtimePay),
"in overtime for a total of",'${:,.2f}'.format(totalPay))
except:
print("Sorry, that wasn't a valid number. Ending program")
main()
You can declare your functions outside of the main function declaration and then use them in the main function (or inside of other functions in the main function).
So you could do something like:
def calcPay(hours):
# Does logic
return [400, 30, 430]
def displayOutput(regPay, overtimePay, totalPay):
# Prints formatted string
def main():
hoursWorked = float(input("How many hours did you work? "))
pay = calcPay(hoursWorked)
displayOutput(pay[0], pay[1], pay[2])
main()
Have a look at these similar questions:
What does it mean to call a function?
How to correctly define a function?
Basic explanation of Python functions?
There's nothing special about the function named main. You can name functions whatever you want.
When you "call" a function you're just jumping from one block of code to another. When the function returns it goes back to the line that called it.
def something():
print('something')
def other():
print('else')
def a_value():
return 100
something()
other()
x = a_value()
print(x)
# ~~~~~ output
something
else
100
In your example a good use of a function would be to calculate the employee's pay.
def total_pay(hours_worked, hourly_rate, overtime_after=40):
base_pay = min(overtime_after, hours_worked) * hourly_rate
overtime_pay = max(0, hours_worked - overtime_after) * (hourly_rate * 1.5)
return base_pay + overtime_pay
This function allows us to define the three things that determine a worker's pay. The base_pay will be, at most, the number of hours before overtime is applied. The overtime_pay will be from 0 to "some other limit" that's not defined here. Overtime is given time and a half (1.5).
Related
I'm currently working on a unit conversion calculator, and wanted to make it smoother by calling the math functions from a different file. Currently, Celsius -> Fahrenheit (CF) is put in 'func.py', like this:
# This file has all the math functions that get called by main.py when needed.
# Also, VARIABLES!
num = 0
typ = 0
def CF():
tota = (num * 9/5) + 32
print("Answer: " + str(tota) + " degrees Fahrenheit")
And the code to call it in main.py looks like this:
if (typ == str('C-F')):
num = int(input("Enter the temperature in Celcius: "))
num = num
CF()
I figure that I imported something wrong, but I've edited the import function several times now. I'm not looking for some type of complete correction, I wish for somebody to tell me what I did wrong, so that I can fix it. I used repl.it, if it helps. Even if someone can tell me that it's possible, it'll help.
I couldn't find anything on websites like GeeksforGeeks, which is my main source on research.
This is very odd:
def CF():
You're relying on num being defined at module scope within its module.
Much better to spell it this way, so you're passing in an argument:
def cf(num):
Over in main.py you're doing this, which isn't helpful:
num = num
Much better to pass it in:
cf(num)
The big concept you've been missing is you have two different modules,
and each one has a num variable.
They are different.
Changing one won't automatically affect the other.
Use function parameters instead.
You need to work with function parameters and returns (see this for a tutorial).
# func.py
def CF(num):
return (num * 9/5) + 32
# main.py
if (typ == str('C-F')):
num = int(input("Enter the temperature in Celcius: "))
tota = CF(num)
print("Answer: " + str(tota) + " degrees Fahrenheit")
It says that "salary" is not defined or that i can't multiply this.
I want to have it with the def command so please just let it in this form just correct the mistakes, im completely new to it so just let it as easy as it is. Thank you very much :)
def computepay(Hours,RatePerHour):
if float(Hours)-40<0:
salary=float(Hours)*float(RatePerHour)
else:
salary=40.0*float(RatePerHour)+(float(Hours)-40.0)*float(RatePerHour*1.5)
Hours=input("Hours:\n")
RatePerHour=input("RatePerHour:\n")
computepay(Hours,RatePerHour)
print("Salary:")
print(salary)
I expect that someone could help me how this little program works correct
You need to return salary and then assign this to a variable. Here's an improved version of your code:
def compute_pay(hours: float, rate_per_hour: float) -> float:
if hours - 40 < 0:
salary = hours * rate_per_hour
else:
salary = 40 * rate_per_hour + (hours - 40.0)* rate_per_hour * 1.5
return salary # This is the line you are missing!
hours = input("Hours:\n")
rate_per_hour=input("RatePerHour:\n")
computer_salary = computepay(float(hours), float(rate_per_hour)) # You also need to assign the output of a function to a variable, I've given it a different name from salary just to show you that this is a different variable from the one inside your function. Also, cast to float here so you don't have to do it all over your function.
print(f"Salary: {computer_salary}")
The concept you need to learn here is called scope.
You needed to return the calculated salary.
Also, simpler if you performed the float conversion on input.
def computepay(Hours,RatePerHour):
if float(Hours)-40<0:
salary=Hours*RatePerHour
else:
salary=40.0*RatePerHour+ (Hours-40.0)*(RatePerHour*1.5)
return salary # return value
Hours = float(input("Hours:\n")) # float conversion
RatePerHour = float(input("RatePerHour:\n")) # float conversion
salary = computepay(Hours,RatePerHour)
print("Salary:")
print(salary)
Here is the correction, and some explications follow.
def computepay(Hours,RatePerHour):
salary = 0
if float(Hours)-40<0:
salary=float(Hours)*float(RatePerHour)
else:
salary=40.0*float(RatePerHour)+(float(Hours)-40.0)*float(RatePerHour) *1.5) #<=== here you multiply with out turning rateperhour as float
return salary
Hours=input("Hours:\n") RatePerHour=input("RatePerHour:\n")
salary = computepay(Hours,RatePerHour)
print("Salary:")
print(salary)
First, salary is a variable enclosed inside your function, it's not a avaliable outside of it.
Second, you get an error because you multiply a string by an integer. Convert it to float before.
float(RatePerHour*1.5) #wrong
float(RatePerHour) *1.5 # correct
I am trying to figure out how to pass arguments in Python and why my code is not working. Why is it saying that the arguments are not defined? I need the arguments in from each function to be able to speak to one another. I could only solve this problem by putting the variables in the defined main function, which is not how I wanted to design the program.
#make computer program that takes amount of doughnuts that customer
#wants to order.
#second, multiply the number of doughnuts the customer wants to order
#by the price and the sales tax.
#next, print the price of the doughnut with the sales tax
DOUGHNUT=1.75
SALES_TAX=0.08625
def getNumDoughnuts(numDoughnuts):
numDoughnuts= raw_input("How many donuts would you like to order?")
return numDoughnuts
def calculateDoughnutPrice(numDoughnuts, doughnutPrice):
doughnutPrice=DOUGHNUT*float(numDoughnuts)
return doughnutPrice
def calculateSalesTax(doughnutPrice, priceWithTax):
taxAmount= (doughnutPrice*(SALES_TAX))
priceWithTax= taxAmount+doughnutPrice
return priceWithTax
def displayPrice(priceWithTax):
print(priceWithTax)
def main():
getNumDoughnuts(numDougnuts)
calculateDoughnutPrice(numDoughnuts, doughnutPrice)
calculateSalesTax(doughnutPrice, priceWithTax)
displayPrice(priceWithTax)
main()
In main, numDougnuts is indeed not defined when you call getNumDoughnuts. OTOH, the latter function ignores its argument and returns a value, which main in turn ignores. And so forth -- you need to distinguish arguments from return values!
So putting things in proper order your program would become:
DOUGHNUT = 1.75
SALES_TAX = 0.08625
def getNumDoughnuts():
numDoughnuts = raw_input("How many donuts would you like to order?")
return numDoughnuts
def calculateDoughnutPrice(numDoughnuts):
doughnutPrice = DOUGHNUT * float(numDoughnuts)
return doughnutPrice
def calculateSalesTax(doughnutPrice):
taxAmount = doughnutPrice*(SALES_TAX)
priceWithTax = taxAmount + doughnutPrice
return priceWithTax
def displayPrice(priceWithTax):
print(priceWithTax)
def main():
numDoughnuts = getNumDoughnuts()
doughnutPrice = calculateDoughnutPrice(numDoughnuts)
priceWithTax = calculateSalesTax(doughnutPrice)
displayPrice(priceWithTax)
main()
See the difference between arguments and return values? Arguments are what gets into a function (and their values must be defined at the time you call that function). A return value is what gets out of the function -- and usually needs to be bound to a variable, or otherwise used, by the function's caller.
Also, of course, you need to call main, or else nothing happens!-)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have written a Python program that I expect to accept a "y" input from a user, and if the user inputs "y", do some simple calculations and print the results.
However it is not executing beyond
the user input even if that input is "y". Please help me locate the errors in the program.
The code is:
#This function is to get the user to input the data needed to use in the rest of the program
#It should return the 3 variables name, hrs_wrkd, and payrate
def get_info(name,hrs_wrkd,payrate):
print('is this working?');
name = input('What is the last name of the employee?');
hrs_wrkd = float(input('How many hours did',name,' work last week?'));
payrate = float(input('How much does',name,' get paid?'));
return name,hrs_wrkd,payrate
#This function should be to calculate the employee's regular pay hours
#It accepts arguments from get_info
def calculate_reg_pay(hrs_wrkd,payrate):
reg_hrs = hrs_wrkd
reg_pay = reg_hrs * payrate
OT_hrs = 0
OT_pay = 0
return reg_hrs,reg_pay,OT_hrs,OT_pay
#This function should calculate the Overtime pay for the employee
#It accepts arguments from the get_info function as well
def calculate_OT_pay(hrs_wrkd,payrate):
reg_hrs = hrs_wkrd - 40
reg_pay = reg_hrs * payrate
OT_hrs = hrs_wrkd - reg_hrs
OT_pay = OT_hrs * (payrate * 1.5)
return reg_hrs,reg_pay,OT_hrs,OT_pay
#This function decides which calculation to use, either OT or regular pay
#It also accepts srguments from get_info
def calc_employee(hrs_wrkd,payrate):
if hrs_wrkd <= 40:
calculate_reg_pay(hrs_wrkd,payrate)
else:
calculate_OT_pay(hrswrkd,payrate)
#This function should print the single employee information after it was calculated
#It gets its arguments from the calc_employee function
def print_employee(reg_pay,OT_pay,name):
print(name,'earned $',format(reg_pay,'.2f'),' worth of regular pay and ',format(OT_pay,'.2f'),' in overtime this week.')
#This function is supposed to calculate the running total of the hours and pay for overtime and regular pay for the company
# It accepts its arguments from the calc_employee function also
def running_total(reg_hrs,reg_pay,OT_hrs,OT_pay,total_reg_hrs,total_reg_pay,total_OT_hrs,total_OT_pay):
total_reg_hrs = total_reg_hrs + reg_hrs
total_reg_pay = total_reg_pay + reg_pay
total_OT_hrs = total_OT_hrs + OT_hrs
total_OT_pay = total_OT_pay + OT_pay
#This function is supposed to print out the running total for the company, but I realized that it isnt in the proper position when called
def print_totals(total_reg_hrs,total_reg_pay,total_OT_hrs,total_OT_pay):
print('The total regular hours worked was',total_reg_hours)
print('The total regular pay was $',format(total_reg_pay,'.2f'))
print('The total overtime hours worked was',total_OT_hours)
print('The total overtime pay was $',format(total_OT_pay,'.2f'))
# So here I am defining the main loop that will activate everytime the user selects Yes
#It calls most of the other functions
def main_loop():
get_info
calc_employee
print_employee
running_total
#Here I am defining the main program where I put the loop control
def main():
loop_control = input("Would you like to enter an employee's name, payrate and hours? y to do so")
if loop_control == "y":
main_loop
else:
print_totals(total_reg_hrs,total_reg_pay,total_OT_hrs,total_OT_pay)
#Here we call the main function
main()
You need to call your functions. This does nothing but reference the function object:
main_loop
Add () to call a function:
main_loop()
Same in your main_loop() function:
def main_loop():
get_info()
calc_employee()
print_employee()
running_total()
Not that that'll work, because your functions take parameters; you need to pass those in in a function call to work. get_info() takes parameters it then ignores; remove those parameters in the function signature:
def get_info():
print('is this working?');
name = input('What is the last name of the employee?');
hrs_wrkd = float(input('How many hours did',name,' work last week?'));
payrate = float(input('How much does',name,' get paid?'));
return name,hrs_wrkd,payrate
Next you want to assign return values; get_info() returns a few things, but you never assign any of them:
name, hours_worked, payrate = get_info()
Now you can pass these to other function calls:
calc_employee(hours_worked, payrate)
etc.
You'll have quit a few more to fix, that is outside the scope of this answer though. Don't forget to use return on function calls too! calc_employee doesn't return anything, for example, it simply ignores what the functions it delegates to return, for example.
So first let me say that I am a novice at Python and functions seem to be out of my comprehension for the moment but where I am having trouble is having 3 functions be able to call each other. Here is my code(yes I know it is terribly wrong but you should see where I am going):
def menu():
count=gearboxes
cost=subtotal
return subtotal
def quantity():
gearboxes=raw_input("How many gearboxes would you like to order? ")
return menu()
def subtotal(cost):
if (gearboxes<=10):
cost=gearboxes*100.0
print cost
elif (gearboxes>10 and gearboxes<20):
cost=(gearboxes-10)*80.0+1000.0
print cost
elif (gearboxes>20):
cost=(gearboxes-20)*70.0+1000.0+800.0
print cost
else:
print "wtf m8"
return menu()
def summary():
print "="*80
print "%60s %20f %20f" % ("motors",count,cost)
print "="*80
print quantity()
print subtotal(menu)
print summary(menu)
There is it and any help would be greatly appreciated if you could explain also kind of how functions call on each other.
Thanks!
fixed version(still working)
def quantity():
motors=raw_input("How many motors would you like to order? ")
gearboxes=raw_input("How many gearboxes would you like to order? ")
sensors=raw_input("How many sensor boards would you like to order? ")
return int(motors),int(gearboxes),int(sensors)
def subtotal(motors,gearboxes,sensors):
if motors<=10 and gearboxes<=15:
motorCost=motors*100
gearboxCost=gearboxes*50
sensorCost=sensors*66
return motorCost, gearboxCost, sensorCost
if motors>10 and motors<=20 and gearboxes>15 and gearboxes<=30:
motorCost=(motors-10)*80+1000
gearboxCost=(gearboxes-15)*40+750
sensorCost=sensors*66
return motorCost, gearboxCost, sensorCost
elif motors>20 and gearboxes>30:
motorCost=(motors-20)*70+1000+800
gearboxCost=(gearboxes-30)*30+750+600
sensorCost=sensors*66
return motorCost, gearboxCost, sensorCost
def summary(motors,gearboxes,sensors,motorCost,gearboxCost,sensorCost):
print "="*80
print "%60s %20d %20d" % ("motors",motors,motorCost)
print "%60s %20d %20d" % ("gearboxes",gearboxes,gearboxCost)
print "%60s %20d %20d" % ("sensor boards",sensors,sensorCost)
print "="*80
def menu():
a,b,c=quantity()
d,e,f=subtotal(a,b,c)
summary(a,b,c,d,e,f)
return
menu()
I made some changes to your code. Treat a function like a question. When you call the function; you're asking the question. What you pass to return is the answer to the question. So when someone asks for the subtotal of some number of gearboxes; we return cost, whatever that may be.
We can then store the return values (the answers) in variables and use them later. For example, to pass to another function. Try to follow how information flows through the program.
def quantity():
count=raw_input("How many gearboxes would you like to order? ")
return int(count)
def subtotal(count):
if count<=10:
cost=count*100.0
return cost
elif count>10 and count<20:
cost=(count-10)*80.0+1000.0
return cost
elif count>20:
cost=(count-20)*70.0+1000.0+800.0
return cost
def summary(count, cost):
print "="*80
print "%60s %20f %20f" % ("motors",count,cost)
print "="*80
def menu():
items = quantity()
sub = subtotal(items)
summary(items, sub)
if __name__ == '__main__':
menu()
"subtotal" already calls menu() so I'm not sure what you are asking since you are already calling one function within the other.
Also, I can't see what your program is supposed to do - if your function names would be verbs (print_menu, get_menu, set_menu, throw_menu_on_moon, calculate_subtotal, ...) it would be better to understand for humans.
Also, the names you use (on the right hand side of =) within a function must be known there, so for example
def menu():
count=gearboxes
makes no sense (because "gearboxes" is unknown - on the other hand, "count" is fine since it defines new variable - since it is on the left hand side of =)...
Note that variables are only known within the function you defined them in, so
def f():
gearboxes = 2
def menu():
count=gearboxes
would make no sense either.
But
def f():
return 2
def menu():
gearboxes=f()
count=gearboxes
would make perfect sense.
Read the
def calculate_subtotal(gearbox_count):
as "to calculate subtotal of gearbox count do".
If you then say anywhere outside:
calculate_subtotal(5)
^^^^^^^^^^^^^^^^^^^^^
then the underlined part will be replaced by the result returned.
Otherwise, in Python the lines (in a block) are executed one after another - if you want to do multiple things in sequence, you can just write them one line each, one after another.
"return" is not "goto", "return" gives back the result - and control - to the caller of the function. Then the result is placed into the program "instead of the call".