Passing Arguments in Python - python

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!-)

Related

Call google-map Function in main python program and pass arguments in python

I need to defined a function that include two parameters. The arguments are supplied in main python program which calls the function in it. The function calls googlemapsapi to calculate travel time. The main program can call the function, but not taking arguments supplied. Function executed without the supplied arguments.
function:
def travel_time(origin,destination):
return value
print("Below is Drive Time");
now = datetime.now()
directions_result_drive = gmaps.directions(origin,
destination,
mode="driving",
departure_time=now
)
value=round(float((directions_result_drive[0]['legs'][0]['duration']
['value'])/3600),1)
Main program is as below:
from travel_function import travel_time
origin = input("origin is:",)
destination = input("destination is:",)
print(travel_time(origin,destination));
Based on argument supplied, it should give travel time. e.g. Origin=NewYork, Destination="Boston", value returned should be approx. 4 hours
Looks like the only problem is that the return statement is at the top, this should work:
def travel_time(origin, destination):
print("Below is Drive Time")
now = datetime.now()
directions_result_drive = gmaps.directions(
origin,
destination,
mode="driving",
departure_time=now
)
value = round(float((directions_result_drive[0]['legs'][0]['duration']['value'])/3600),1)
return value

How to use def *insert name here* (): functions?

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).

Python: variable is undefined when calling function containing the variable

I just started my first programming class a few weeks ago and I'm embarrassed to say I'm very stuck. We had to create a program that (in my Professor's words):
Simulate the roll of two dice. Use a randomly generated integer to represent the roll of each die in a function named point. Return the combined value of a roll. Use a loop in main to roll the dice five times and report each result.
So, I did my best and keep getting the same issue where it is telling me my variable total is not defined, even though I'm calling the function which contains the variable.
I submitted the below code to my professor, who in turn responded:
The dice program is close. Return the total of a roll. Call point in main and capture the returned value for printing.
So he is saying to call the function point in my main function (which, at least I think, I am) but it still won't read my vital variable to finishing this.
import random
min=1
max=6
def main():
for roll in range(5):
point()
print(total)
def point():
roll=random.randint(min, max)
roll2=random.randint(min, max)
total=roll+roll2
return total
main()
Inside the main function, this line:
point()
does not make total available in the current scope. Instead, it simply calls the function point and then discards its return value.
You need to capture this return value by assigning it to a variable named total:
def main():
for roll in range(5):
################
total = point()
################
print(total)
Now, when you do print(total), total will be defined and equal to the value of point().
You're trying to reference a variable that only exists within the scope of the point() function. But you don't need to since you return the value anyway.
Try this.
from random import randint
def rollD6():
return randint(1,6)
def point():
return rollD6()+rollD6()
def main():
for roll in range(5):
print point()
main()

Python program does not execute beyond first user input [closed]

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.

Creating a number of functions that need to be able to call each other in Python

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".

Categories

Resources