Function call missing required positional argument: - python

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

Related

Banking Code assignment, calling methods within a class

Being relatively new to coding, some of the small issues I have not yet learn to tweak out. In this code my goal is to print the account's name, plus their balance based off of a withdraw, deposit, or simply checking. The name and values will print, however, they are not in a line, as well as "none" prints at the end, and i cannot seem to rid it. I need suggestions on how to fix. I believe the problem stems somewhere within the methods and calling them but am not sure.
class Account:
def __init__(self, name, balance):
self.name = name
self.balance = balance
def Withdraw(self):
if Amount1 > self.balance:
self.withdraw = "You have exceeded your balance."
print (self.withdraw)
elif Amount1 < self.balance:
self.withdraw = (self.balance - Amount1)
print (self.withdraw)
def Deposit(self):
self.deposit = (self.balance + Amount2)
print (self.deposit)
def CheckBalance(self):
self.check = self.balance
print (self.check)
account1 = Account("Barbara", 500.00)
account2 = Account("Joe", 150.00)
account3 = Account("Frank", 20.00)
Action = input("What would you like to do; check balance(c), deposit(d), or withdraw(w)? ")
if Action == "w":
Amount1 = int(input("What amount would you like to withraw?"))
print (account1.name + str(account1.Withdraw()))
print (account2.name + str(account2.Withdraw()))
print (account3.name + str(account3.Withdraw()))
if Action == "d":
Amount2 = int(input("What amount would you like to deposit? "))
print (account1.name + str(account1.Deposit()))
print (account2.name + str(account2.Deposit()))
print (account3.name + str(account3.Deposit()))
if Action == "c":
print (account1.name + str(account1.CheckBalance()))
print (account2.name + str(account2.CheckBalance()))
print (account3.name + str(account3.CheckBalance()))
This is the code i have running so far

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?

Why are my classes not working properly? even though they work when only one class is active

so my classes won't recognize each other but when left to work alone they do work as seen in the consult printing at the bottom of the post. However the deposit and transfer are popping up the ram location, however, they do work fine when done separately just as shown in the consult action in the bottom part.
<function cashier.deposit at 0x0000023A9B656048>
import datetime
now = datetime.datetime.now()
class account:
owner = "name"
pin = "1823"
balance = 800
def __init__(self, transfer, withdraw, deposit, consult):
self.transfer = transfer
self.withdraw = withdraw
self.deposit = deposit
self.consult = consult
class cashier:
def __init__(self, withdraw, deposit, transfer, consult):
self.transfer = transfer
self.consult = consult
self.withdraw = withdraw
self.deposit = deposit
def deposit(self):
print("Please type pin to proceed")
if account.pin == 1823:
print("who would you like to send money to?")
else:
print("Invalid pin")
def transfer(self):
pass
def withdraw(self):
withdrawal = input("How much money do you want to withdraw? (there is a limit up to 10,000$ a day!)")
account.balance -= int(withdrawal)
if int(withdrawal) > 10000:
print("withdrawals cannot be larger than 10,000 a day!")
exit()
elif int(withdrawal) > account.balance:
print("your account does not have enough funds to complete your transaction")
else:
print("Transaction succesfull!\nPlease collect your money")
print('Today is', now)
print("Hello %s!\nWhat can I do for you today?" % account.owner)
action = input("Use commands such as withdraw, deposit, transfer or consult to continue!\n")
if action == "withdraw":
print(cashier.withdraw)
if action == "consult":
print("Your account's balance is %s $" % str(account.balance))
if action == "transfer":
print(cashier.transfer)
if action == "deposit":
print(cashier.deposit)
else:
print("Uknown command, exiting programm")
exit()
The various functions of cashier do not return anything, so the prints are just printing the string representation of the function. You could have the functions return a string like so:
class Cashier: # PEP8 calls for CamelCase here
def deposit(self):
pin = input("Please type pin to proceed")
if Account.pin == pin:
return "who would you like to send money to?"
else:
return "Invalid pin"
def transfer(self):
pass
def withdraw(self):
withdrawal = input("How much money do you want to withdraw? (there is a limit up to 10,000$ a day!)")
Account.balance -= int(withdrawal)
if int(withdrawal) > 10000:
return "withdrawals cannot be larger than 10,000 a day!"
elif int(withdrawal) > Account.balance:
return "your Account does not have enough funds to complete your transaction"
else:
return "Transaction successful!\nPlease collect your money"
Edit: I removed the initializer, as these weren't doing anything. You need to instantiate your cashier with cashier = Cashier(), then call the functions of Cashier with cashier.withdraw().
There's a fundamental misunderstanding on how classes work here (and OOP in general). You should read through the Python docs on building classes before you go any further.
To use your classes, you need to instantate them like this
Cashier = cashier()//I don't think you should ask for the transfer details while instantiating. But you can do that by adding the parameter in the bracket
Now you can use the functions on the Cashier variable like:-
Cashier.deposit(deposit_money)
I think if you don't want to instantiate and want a function which does not actually store data, you can use a static function but I don't think that is what you want to do

Desk Price Calculation in 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)

making a piggy bank program in python

I'm a beginner to Python and programming, and I'm trying to make a simple piggy bank that will be able to deposit or withdraw pennies, nickels, dimes, and quarters. I don't know how to loop the code or how to store the data if I enter a coin to be able to keep adding to the total number of coins in the bank. I can only do it so it runs and tells me if I add, for example, 100 pennies, that my bank has 100 pennies. but then it resets. How do I do this? my code is probably awful but here's what I have so far based off my current knowledge of python (added empty parts like the "return" and pennies_previous so anyone reading can understand my thought process, and the withdrawstep() function has not been added yet):
print "Welcome to the Piggy Bank!"
def depositstep():
deposit = raw_input("What would you like to deposit? (P for pennies, N for nickels, D for dimes, Q for quarters): ").upper()
if deposit == 'P':
pennies_previous =
pennies_instance = raw_input("How many pennies would you like to deposit?: ")
pennies_total = int(pennies_instance) + pennies_previous
print "There are %s pennies in your bank"% (pennies_total)
return execute()
elif deposit == 'N':
N = raw_input("How many nickels would you like to deposit?: ")
return
elif deposit == 'D':
D = raw_input("How many dimes would you like to deposit?: ")
return
elif deposit == 'Q':
Q = raw_input("How many quarters would you like to deposit?: ")
return
else:
return "Sorry. Please Type P for pennies, N for nickels, D for dimes, or Q for quarters."
def execute():
exc = raw_input("Would you like to deposit or withdraw money? (D for deposit, W for withdraw): ").upper()
if exc == 'D' or exc == 'DEPOSIT':
return depositstep()
elif exc == 'W' or exc == 'WITHDRAW':
return withdrawstep()
else:
return "Sorry. Please type D for deposit or W for withdrawal."
print execute()
You should store your total amount of pennies in the original variable.
pennies_previous= int(pennies_instance) + pennies_previous then the amount of pennies will be stored there.
If you are looking to make the bank continue to store the value of the bank for each session, then you are going to want to save the bank's value to a file. You could do it like this:
1. First, make a file with a name like bankvalue.txt.
2. Then, add these lines before every return:
value = open(bankvalue.txt, 'w') # that opens your bankvalue.txt file in write mode
value.write('\n'pennies_previous) #You should use the answer above for the pennies_previous
value.close() #saves the file
3.Then, in order to tell a person their balance you would use the readline() function
I hope that was what you were looking for
I would use a python dictionary instead of variables:
do so as:
bank = {'pennies':0, 'nickles':1, 'dimes':0, 'quarter':0}
to increase either of those you do
bank['pennies'] += int(pennies_instance) # not need the pennies_previous
Then you need to write that to a file which you could do:
f = open('filename','w')
f.write(bank.items())
f.close
But that don't preserve the python structure. But you can use json module, which is simple as:
import json
f = open('filename','wb')
json.dump(bank,f)
f.close()
And at the start of the script you need to fetch the data from the file, you do this with
f = open('bank.dat','rb')
bank = json.load(f)
It would look like this:
import json
f = open('bank.dat','rb')
bank = json.load(f)
f.close()
## you code goes here.
f = open('bank.dat','wb')
json.dump(bank,f)
f.close()
There are some other problems in your code that should be addressed too.
1) In the 'else' part of your code, if the user inputs the wrong letter it terminates, instead it should call the function again.
2) You don't need to return a string and print it in the 'print execute()', you could just print it in place and don't return anything.

Categories