Desk Price Calculation in Python - python

I have a little exercise I need to do in Python that's called "Desk Price Calculation". There need to be 4 functions which are used in the program.
My main problem is using the output of a function in another function.
def get_drawers():
drawers = int(input('How many goddamn drawers would you like? '))
return drawers
def get_wood_type():
print('The types of wood available are Pine, Mahogany or Oak. For any other wood, type Other')
wood = str(input('What type of wood would you like? '))
return wood
def calculate_price(wood_type, drawers):
wood_type = get_wood_type()
drawers = get_drawers()
wood_price = 0
drawer_price = 0
#wood price
if wood_type == "Pine":
wood_price = 100
elif wood_type == "Oak":
wood_price = 140
elif wood_type == "Mahogany":
wood_price = 180
else:
wood_price = 180
#price of drawers
drawer_price = drawers * 30
return drawer_price + wood_price
def display_price(price, wood, drawer_count):
price = calculate_price()
wood = get_wood_type()
drawer_count = get_drawers()
print("The amount of drawers you requested were: ", drawer_count, ". Their total was ", drawer_count * 30, ".")
print("The type of would you requested was ", get_wood_type(), ". The total for that was ", drawer_count * 30 - calculate_price(), ".")
print("Your total is: ", price)
if __name__ == '__main__':
display_price()

I guess you get an error like this (that should have been added to your question by the way) :
Traceback (most recent call last):
File "test.py", line 42, in <module>
display_price()
TypeError: display_price() missing 3 required positional arguments: 'price', 'wood', and 'drawer_count'
You defined your display_price() function like this :
def display_price(price, wood, drawer_count):
So it expects 3 arguments when you call it, but you call it without any.
You have to either :
redefine your function without argument (that would be the most logical solution since price, wood and drawer_count are defined in its scope.
pass these arguments to the call of this function, but that would be useless for the reason I mentionned in 1. Unless you remove these arguments definition.
PS: You'll have the same problem with calculate_price() since it expects two arguments, but you pass none to it.
About function's arguments :
When you define a function, you also define the arguments it expects when you call it.
For instance, if you define :
def f(foo):
# Do some stuff
a correct f call would be f(some_val) and not f()
Plus it would be useless to define f like this :
def f(foo):
foo = someval
# Do some other stuff
since foo is direcly redefined in the function's scope without even using the initial value.
This will help you to discover functions basics :
http://www.tutorialspoint.com/python/python_functions.htm

It would appear that you wanted to pass in some parameters to your method.
If that is the case, you need to move the "calculate" and "get" functions.
And, no need to re-prompt for input - you already have parameters
def calculate_price(wood_type, drawers):
# wood_type = get_wood_type()
# drawers = get_drawers()
wood_price = 0
drawer_price = 0
# ... other calulations
return drawer_price + wood_price
def display_price(wood, drawer_count):
price = calculate_price(wood, drawer_count)
### Either do this here, or pass in via the main method below
# wood = get_wood_type()
# drawer_count = get_drawers()
print("The amount of drawers you requested were: ", drawer_count, ". Their total was ", drawer_count * 30, ".")
print("The type of would you requested was ", wood, ". The total for that was ", drawer_count * 30 - price, ".")
print("Your total is: ", price)
if __name__ == '__main__':
wood = get_wood_type()
drawer_count = get_drawers()
display_price(wood, drawer_count)

Related

How can I take another variable from a def function and add it to another def function to get a new sum?

def room1(phone_charge):
phone_charge = 5
import random
randNum = random.randint(1,5)
print("An outlet! You quickly plug in your phone, but the wiring in the house is faulty and soon shorts out.\n")
positve = str(phone_charge + randNum)
print("Your phone is now " + positve + " % charged\n")
return(positve)
I need to add positive to another function
def room5(phone_charge):
import random
randomNUM = random.randint(1,30)
positve2= str(phone_charge + randomNUM)
print("Your phone is now " + positve2 + " % charged\n")
return(positve2)
I need to add postive to the room5 variable postive2
I tried returning variables and putting them in the next function but then my code that was written behind where I entered the returning variable it was no longer highlighted
Since the two functions return their values, you can add them together after calling.
p1 = room1(phone_charge)
p5 = room5(phone_charge)
print(f"Total is {p1 + p5}")
Since the two functions have the same functionality use one function with an extra parameter.
import random
def room(phone_charge, rand_range):
randNum = random.randint(1,rand_range)
print("An outlet! You quickly plug in your phone, but the wiring in the house is faulty and soon shorts out.\n")
positve = str(phone_charge + randNum)
print("Your phone is now " + positve + " % charged\n")
return positve
room1 = room(5, 5)
room5 = room(10, 30)
total = room1 + room5

How to print variable from subroutine

In my code below, I don't know why when the output total_cost is zero, and why the subroutine doesn't change that variable. Also are the parameters of my subroutine wrong, like should I add them outside the subroutine and then use those defined variables or something?
total_cost = 0
from datetime import date
def valid_integer():
not_valid = True
while not_valid:
try:
number = int(input())
not_valid = False
except ValueError:
print("You must enter a whole number")
return number
print("Welcome to Copington Adventure them park!")
print(
"\n""These are our ticket prices:"
"\n""Adult ticket over 16's £20 "
"\n""Child ticket under 16's £12 "
"\n""Senior ticket over 60's £11" )
print("How many adult tickets do you want?")
adult = int(input())
print("How many child tickets do you want?")
child = int(input())
print("How many Senior tickets do you want?")
senior = int(input())
print("Your total ticket price is:")
print(total_cost)
def entrance(child_total, adult_total, senior_total):
total_child = child * 12
total_senior = senior * 11
total_adult = adult * 20
total_cost = total_child + total_senior + total_adult
return total_cost
print(total_cost)
return exits the function, so any code after a return will not execute. Swap the order of these two lines:
return total_cost
print(total_cost)
The required reading on this is "scope". Code in a function has access to the variables in its own scope, and it has access to its parent scope, which is the file it was defined in. After a function call completes, the scope, and all variables created in it that aren't returned or stashed in a higher scope, tend to be destroyed.
Returned variables are passed back to the caller's scope. So the lifecycle is something like this:
def myfunction(a, b):
a = a * 2
print(a) #this will evaluate later when we call the function
b = a + b
return b
c = myfunction(1, 2) # jumps to the first line of the function with a=1 and b=2
# the function evaluates, which prints "2" and returns 4.
# The label "c" is then created in the outer scope, and 4 is assigned to it. So now c = 4
print(a) # this is an error, a is not part of this outer scope
print(b) # this is an error, b is not part of this outer scope
print(c) # outputs 4
print(myfunction(1, 2)) # what do you think this outputs?

Function call missing required positional argument:

I'm making a restaurant tab program for class and the teacher asked us to 'modularize' it from the original. However, I keep getting the error"
TypeError: computeTotal() missing 1 required positional argument: 'drinks')
I know it's a scope error but I'm not sure how to fix it since the variable is a global variable.
def getdrinks():
drinks = float(input('dollar amount for drinks: $'))
return drinks
def getapps():
apps = float(input('dollar amount for apps: $'))
return apps
def getMC():
mainCourse = float(input('dollar amount for main course: $'))
return mainCourse
def getdessert():
dessert = float(input('dollar amount for desserts: $'))
return dessert
def getPurchaseAmts():
getdrinks()
getapps()
getMC()
getdessert()
getPurchaseAmts()
def computeTotal(drinks, apps, mainCourse, dessert):
Total = (drinks + apps + mainCourse + dessert)
print ("Bill total (before tax and preTip): ",Total)
computeTotal()
drinks = getdrinks()
apps = getapps()
mainCourse = getMC()
dessert = getdessert()
You're confusing parameters with externally defined values.
Those parameters could be named completely different things, and even though they are currently the same as the others, that does not mean that their values are automatically passed into the function
For example,
def computeTotal(a, b, c, d):
total = (a + b + c + d)
print ("Bill total (before tax and preTip): ",total)
drinks = getdrinks()
apps = getapps()
mainCourse = getMC()
dessert = getdessert()
# this must be last, and you need to pass values into the function
computeTotal(drinks, apps, mainCourse, dessert)
And you can remove getPurchaseAmts() because it's not doing anything but making you repeat your inputs twice

nested function in python (taking the output from another function)

I have problem with getting output from another function to use in a function.
I don't know the syntax of function in python. How do i take a output of another function to use in a function when i define it.
def hero_attribute(hero_selection()): #This syntax isn't accepted
#This program will calculate the damge of hero with stats
global hero_str_result
global hero_agi_result
global hero_int_result
def hero_selection():
print """1. Life Stealer (strength hero)\n
2. Phantom lancer (agility hero)\n
3. Phantom Assassin (agility hero)\n
4. Wrait King (strength hero) \n
"""
print "Please enter hero selection: "
hero_num = int(raw_input("> "))
return hero_num
def hero_attribute(hero_selection()): #This syntax isn't accepted
if hero_num == 1: # Life stealer
hero_str = 25
hero_agi = 18
hero_int = 15
#Hero growth stats
str_growth = 2.4
agi_growth = 1.9
int_growth = 1.75
elif hero_num == 2: # Phantom lancer
hero_str =
hero_agi = ?
hero_int = ?
#Hero growth stats
str_growth = 2.4
agi_growth = 1.9
int_growth = 1.75
elif hero_num == 3: # Phantom Assassin
hero_str = ?
hero_agi = ?
hero_int = ?
#Hero growth stats
else: #Wraith King
hero_str = ?
hero_agi = ?
hero_int = ?
#hero growth stats
str_growth = ?
agi_growth = ?
int_growth = ?
return (hero_str,hero_agi,hero_int,str_growth,agi_growth,int_growth)
def hero_type(hero_num):
if hero_num == 1:
hero_type = "str"
elif hero_num == 2
hero_type = "agi"
elif hero_num == 3
hero_type = "agi"
else:
hero_type = "str"
#the function will ask user what to do with the hero
def hero_build():
print "What do you want to do with the hero?"
print """1. Build hero with stat
2. Build hero with item (not yet)
3. Build hero with level
"""
user_choice = int(raw_input("> "))
if user_choice == 1:
print "You want to build hero with stats!"
print "Please enter number of stats that you want to add: "
hero_stats = int(raw_input=("> "))
hero_str, hero_agi, hero_int,str_growth,agi_growth,int_growth = hero_attribute() #This function will take the result of hero_str, hero_agi,hero_int
hero_str_result = hero_str + str_growth * hero_stats
hero_agi_result = hero_agi + agi_growth * hero_stats
hero_int_result = hero_int + int_growth * hero_stats
return hero_str_result, hero_agi_result, hero_int_result
print "This is the result of your build: ", hero_build()
A function is a piece of code that receive arguments, and to those arguments you assign a name. For example:
def square(x):
return x * x
this function computes the square of a number; this unknown number in the body of the function will be called x.
Once you have a function you can call it, passing the values you want as arguments... for example
print( square(12) )
will print 144 because it will call the function square passing x=12 and 12*12 is 144.
You can of course pass a function the result of calling another function, e.g.
def three_times(x):
return 3 * x
print( square( three_times(5) ) )
will display 225 because the function three_times will be passed 5 and it will return 3*5, the function square will be passed 15 and will return 15*15.
In the function definition (the def part) you will always just have names for the parameters. What you want to pass to the function will be written at the call site.
What you want is to be able to pass a function as argument. This, however, is already incorporated into python from design: you simply pass it as you pass any other argument.
Example:
def apply(f,x):
return f(x)
def sq(x):
return x*x
def cb(x):
return x*x*x
apply(sq,2)
4
apply(cb,2)
8
Apply is defined with its first argument being a function. You know that only when you actually read the definition of apply. There you see that f is treated as a function, as opposed to x which is treated "as a number".

How do I use a function to CALL another function?

I have this code that works when it's not in the function form, but doesn't when it is one.
I am able to call grade(), but get an error when award() is added.
Here is what I have so far
def award(firstplace, secondplace):
print("")#return
print("The Player of the Year is: " + firstplace)
print("The Runner Up is: " + secondplace)
def grade():
count = 0
playeroftheyear = 0
runnerup = 0
firstplace = (" ")
secondplace = (" ")
for results in range (0,5):
name = input("Player Name: ")
fieldgoal = input("FG%: ")
fieldgoal = int(fieldgoal)
if fieldgoal > playeroftheyear:
runnerup = playeroftheyear
secondplace = firstplace
playeroftheyear = fieldgoal
firstplace = name
elif fieldgoal > runnerup:
runnerup = fieldgoal
secondplace = name
award(firstplace, secondplace)
return
grade()
In your code, firstplace, like secondplace exists only in grade, but not in award. Hence, when you try to access it from award, you get the error.
You need to pass secondplace and firstplace as a parameter:
def award(firstplace, secondplace):
print("")
print("The Player of the Year is: " + firstplace)
print("The Runner Up is: " + secondplace)
def grade():
...
award(firstplace, secondplace)
return
grade()
Functions set up a new namespace. names that you define inside a function can't be used outside the function unless you explicitly say they can be with the global keyword.
In this case, you're defining names inside of grade (firstplace, secondplace, etc.), but those names are not available to award because they only live inside the grade function. To let them out, you could add:
global firstplace
global secondplace
at the top of your grade function. However, that's definitely not the best approach. The best approach would be to pass them as arguments:
def award(firstplace, secondplace):
...
And then you call award like so:
award(firstplace, secondplace)

Categories