I am getting an error in my program that says finddiscount() missing one required positional argument. I can't seem to figure out how to properly code the find discount function could someone please help? Im sure this is a simple error but I am new to python and especially new to functions. Thanks!
def finddiscount(discount):
if quantity >= 1 and quantity <= 9:
discount = "0%"
elif quantity >= 10 and quantity <= 19:
discount = "20%"
elif quantity >= 20 and quantity <= 49:
discount = "30%"
elif quantity >= 50 and quantity <= 99:
discount = "40%"
elif quantity >= 100:
discount = "50%"
print (discount)
def main():
quantity = int(input("How many packages where purchased?"))
price = float(input("How much is each item?"))
finddiscount()
return
def finddiscount(quantity):
if quantity >= 1 and quantity <= 9:
discount = "0%"
elif quantity >= 10 and quantity <= 19:
discount = "20%"
elif quantity >= 20 and quantity <= 49:
discount = "30%"
elif quantity >= 50 and quantity <= 99:
discount = "40%"
elif quantity >= 100:
discount = "50%"
print (discount)
main()
You are invoking the function like this
finddiscount()
But it is defined like this
def finddiscount(quantity):
So, you should be passing a value for the quantity parameter.
finddiscount(quantity)
You define the function as taking one parameter:
def finddiscount(discount):
(and later redefine it, but let's ignore that for now, since the second definition also takes one parameter).
But then you call it with no arguments:
finddiscount()
Presumably you wanted this:
finddiscount(quantity)
There are a number of other problems with your code. You shouldn't be defining all of this stuff inside a finddiscount function definition. And you definitely shouldn't be defining a local function named finddiscount inside a global function with the same name.
Also, you usually want your functions to actually return something, not just print a value and then do nothing. (For example, you might want to return the discount, so some later code can apply that discount to the price.)
But this will solve the problem you asked about.
You can avoid the cascade of if statements (and unexpected errors - what if quantity = 0? or 110?) like so:
import bisect
import sys
inp = raw_input if sys.hexversion < 0x3000000 else input
def type_getter(type_):
def getfn(prompt):
while True:
try:
return type_(inp(prompt))
except ValueError:
pass
return getfn
get_int = type_getter(int)
get_float = type_getter(float)
discount_points = [ 0, 10, 20, 50, 100]
discount_fractions = [.0, .0, .2, .3, .4, .5]
def discount_fraction(qty):
ndx = bisect.bisect_right(discount_points, qty)
return discount_fractions[ndx]
def main():
qty = get_int("How many were purchased? ")
price = get_float("How much is each?")
frac = discount_fraction(qty)
total = price * (1. - frac) * qty
print("Final cost is ${:0.2f}.".format(total))
if __name__=="__main__":
main()
Related
When I run the script, It allows me to input the two user inputs i have in getSales function and getIncrease function, but does my print function at the end seems to do nothing. This is for an extra credit assignment which starts out as just the functions being defined with comments and i have to fill in the rest. Please enlighten me stack overflow community!
def main():
monnthlySales = getSales()
#call to get sales
# This function gets the monthly sales
def getSales():
monthlySales = float(input('Enter the monthly sales $'))
salesIncrease = getIncrease() #call to get sales increase
return monthlySales
# This function gets the percent of increase in sales
def getIncrease():
salesIncrease = float(input('Enter percent of sales increase: '))
salesIncrease = salesIncrease / 100
return salesIncrease
# This function determines the storeAmount bonus
def storeBonus(monthlySales):
if monthlySales >= 110000:
storeAmount = 6000
elif monthlySales >= 100000:
storeAmount = 5000
elif monthlySales >= 90000:
storeAmount = 4000
elif monthlySales >= 80000:
storeAmount = 3000
else:
storeAmount = 0
return storeAmount
# This function determines the empAmount bonus
def empBonus(salesIncrease):
if salesIncrease >= 0.05:
empAmmount = 75
elif salesIncrease >= 0.04:
empAmmount = 50
elif salesIncrease >= 0.03:
empAmmount = 40
else :
empAmmount = 0
return empAmmount
# This function prints the bonus information
def print(storeAmount, empAmount):
print('The store bonus amount is $', storeAmount)
print('The employee bonus amount is $', empAmount)
if storeAmount == 6000 and empAmount == 75:
print('Congrats! You have reached the highest bonus amounts possible!')
main()
At least from what I can see, your logic is correct, the only thing that it's necessary to change is to change the word print for any kind of function, class, etc. Python have reserved words such as print,return,if, etc. That serve for a specific use.
The only thing that you have to do is to rename your function def print() into any word that is not a reserved word.
def printBonus(storeAmount, empAmount):
printBonus('The store bonus amount is $', storeAmount)
printBonus('The employee bonus amount is $', empAmount)
if storeAmount == 6000 and empAmount == 75:
print('Congrats! You have reached the highest bonus amounts possible!')
I hope this works for you
im new to coding and am learning python atm. I was writing this simple code for a discount system and it wont work for some weird reason. pls tell me whats wrong with this code
price = (input('Please type the value of your item.'))
if price >= 300:
price = (price + ((price) * (30/100) )
elif price >= 200 and < 300:
price = (price + ((price) * (20/100) )
elif price >= 100 and <200:
print('You need to pay' + price + '$ for your item')
price = (price + ((price) * (10/100) )
This statement isn't valid:
elif price >= 200 and < 300:
It would correctly be written as:
elif price >= 200 and price < 300:
Note that for this to work, price needs to be a numeric value; you need to convert your input() result to a float or int before trying anything mathematical with it!
However, specifying price < 300 isn't necessary in the first place, since this is an elif that can only happen if price >= 300 was false (hence price < 300 is logically implied to be true).
You can also simplify the arithmetic down; this:
price = (price + ((price) * (30/100) )
is really just the same (algebraically) as:
price = price * (1 + 30/100)
which is the same as:
price *= 1.3
Since you're going to end up with floating point numbers in most cases, you probably want to round this output to 2 decimal places:
print('You need to pay' + price + '$ for your item')
which you can do easily with an f-string:
print(f'You need to pay ${price:.2f} for your item')
All together:
price = float(input('Please type the value of your item.'))
if price >= 300:
price *= 1.3
elif price >= 200:
price *= 1.2
elif price >= 100:
price *= 1.1
print(f'You need to pay ${price:.2f} for your item')
change from this:
if price >= 300:
price = (price + ((price) * (30/100) )
elif price >= 200 and < 300:
price = (price + ((price) * (20/100) )
elif price >= 100 and <200:
to this:
if price >= 300:
price = (price + ((price) * (30/100) )
elif price >= 200 and price < 300:
price = (price + ((price) * (20/100) )
elif price >= 100 and price < 200:
I am doing a University project to create a plan ordering ticket program, so far these are what I have done:
First, this is the function finding the seat type:
def choosingFare():
print("Please choose the type of fare. Fees are displayed below and are in addtion to the basic fare.")
print("Please note choosing Frugal fare means you will not be offered a seat choice, it will be assigned to the ticketholder at travel time.")
listofType = [""] * (3)
listofType[0] = "Business: +$275"
listofType[1] = "Economy: +$25"
listofType[2] = "Frugal: $0"
print("(0)Business +$275")
print("(1)Economy +$25")
print("(2)Frugal: $0")
type = int(input())
while type > 2:
print("Invalid choice, please try again")
type = int(input())
print("Your choosing type of fare is: " + listofType[type])
if type == 0:
price1 = 275
else:
if type == 1:
price1 = 25
else:
price1 = 0
return price1, listofType[type]
And this is a function finding the destination:
def destination():
print("Please choose a destination and trip length")
print("(money currency is in: Australian Dollars: AUD)")
print("Is this a Return trip(R) or One Way trip(O)?")
direction = input()
while direction != "R" and direction != "O":
print("Invalid, please choose again!")
direction = input()
print("Is this a Return trip(R) or One Way trip(O)?")
if direction == "O":
print("(0)Cairns oneway: $250")
print("(2)Sydney One Way: $420")
print("(4)Perth One Way: $510")
else:
print("(1)Cairns Return: $400")
print("(3)Sydney Return: $575")
print("(5)Perth Return: $700")
typeofTrip = [""] * (6)
typeofTrip[0] = "Cairns One Way: $250"
typeofTrip[1] = "Cairns Return: $400"
typeofTrip[2] = "Sydney One Way: $420"
typeofTrip[3] = "Sydney Return: $575"
typeofTrip[4] = "Perth One Way: $510"
typeofTrip[5] = "Perth Return: $700"
trip = int(input())
while trip > 5:
print("Invalid, please choose again")
trip = int(input())
if trip == 0:
price = 250
else:
if trip == 1:
price = 400
else:
if trip == 2:
price = 420
else:
if trip == 3:
price = 574
else:
if trip == 4:
price = 510
else:
price = 700
print("Your choice of destination and trip length is: " + typeofTrip[trip])
return price, typeofTrip[trip]
And this is the function calculating the total price:
def sumprice():
price = destination()
price1 = choosingFare()
price2 = choosingseat()
sumprice = price1 + price2 + price
print("How old is the person travelling?(Travellers under 16 years old will receive a 50% discount for the child fare.)")
age = float(input())
if age < 16 and age > 0:
sumprice = sumprice / 2
else:
sumprice = sumprice
return sumprice
The error I have:
line 163, in <module> main()
line 145, in main sumprice = sumprice()
line 124, in sumprice
sumprice = price1 + price2 + price
TypeError: can only concatenate tuple (not "int") to tuple
Can someone help me? I am really stuck.
I can't return all the
These functions return 2 values each: destination(), choosingFare(), choosingseat().
Returning multiple values at once returns a tuple of those values:
For example:
return price, typeofTrip[trip] # returns (price, typeofTrip[trip])
So while calculating the sum of all prices, you need to access price, price1, price2 from the tuples:
sumprice = price1[0] + price2[0] + price3[0]
Alternatively: You can edit the code to return list/ dictionary or some other data structure as per your convenience.
First let me explain what happends when you write. return price, typeofTrip[trip].
The above line will return a tuple of two values.
Now for sumprice I think what you want is sum of all prices. So you just want to sum first element of returned values.
This should work for your case.
sumprice = price1[0] + price2[0] + price3[0]
So I've been trying to get this code to run:
def conference_call_discount(distance, basic_charge):
if(distance >= 50):
con_calc = basic_charge * 0.5
return con_calc
elif(distance < 50):
con_calc = 0
return con_calc
con_call = str(input("Is it a conference call? "))
from call_charge_functions import conference_call_discount
conference = conference_call_discount(dist, starting_cost)
if con_call == y:
print("your conference call discount is", conference)
else:
conference = 0
However I keep getting this error:
NameError: name 'y' is not defined
I don't know what's wrong
in this if:
if con_call == y:
You didn't set the value for y.
You should set a value for the y variable before comparing it.
def monday_availability(openhours_M): #openhours_M = number hours pool is open
hourone = int(input('Input the first hour in the range of hours the guard can work'))
hourlast = int(input('Input the last hour in the range of hours the guard'))
hour = 1
availability_M = []
while hour <= openhours_M:
if hour >= hourone & hour <= hourlast:
availability_M.append(1)
else:
availability_M.append(0)
return availability_M
Above is a function gathering the availability of a lifeguard and storing the hours a guard can work as a 1 in availability list or a 0 if they cannot. I return this list with the intent of adding it to a dictionary in the function below.
def guard_availability(guards, openhours_M, openhours_T, openhours_W,
openhours_R, openhours_F, openhours_S, openhours_Su):
continueon = 1
while continueon == 1:
name = input('Input guards name of lifeguard to update availability' )
availability = {}
days = {}
if openhours_M != 0:
monday_availability(openhours_M)
if openhours_T != 0:
tuesday_availability(openhours_T)
if openhours_W != 0:
wednesday_availability(openhours_W)
if openhours_R != 0:
thursday_availability(openhours_R)
if openhours_F != 0:
friday_availability(openhours_F)
if openhours_S != 0:
saturday_availability(openhours_S)
if openhours_Su != 0:
sunday_availability(openhours_Su)
days['Monday'] = availability_M
days['Tuesday'] = availability_T
days['Wednesday'] = availability_W
days['Thursday'] = availability_R
days['Friday'] = availability_F
days['Saturday'] = availability_S
days['Sunday'] = availability_Su
availability[name]= days
continueon = input('Enter 1 to add availability for another guard, 0 to stop: ')
return days
When I run this code, I get an error saying my availability lists are undefined even though I returned them in the functions above. Where is the error in my understanding of returning in functions, and how can I remedy this problem.
monday_availability(openhours_M) returns a value.
Returning a variable does not assign it to anything outside the scope of that function.
If you renamed return availability_M to use return foo and update the other uses only within that function accordingly, would the error make more sense?
Now, actually capture the result
availability_M = monday_availability(openhours_M)
Or even just
days['Monday'] = monday_availability(openhours_M)
Also, not seeing how that function has anything to do with Mondays. Try to write DRY code
You return the dic value in your function but don't assign it to any variable. You should do it like this:
if openhours_M != 0:
availability_M=monday_availability(openhours_M)
if openhours_T != 0:
availability_T=tuesday_availability(openhours_T)
if openhours_W != 0:
availability_W=wednesday_availability(openhours_W)
if openhours_R != 0:
availability_R=thursday_availability(openhours_R)
if openhours_F != 0:
availability_F=friday_availability(openhours_F)
if openhours_S != 0:
availability_S=saturday_availability(openhours_S)
if openhours_Su != 0:
availability_Su=sunday_availability(openhours_Su)