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
Related
I'm working on a small personal project in Python 3 where you put in a name and get there weekly wages. I want to add a feature where an admin can come in and add a person to the workers, including their wages. Here's what I have as for people so far:
worker = input("Name: ")
if worker == "Anne":
def calcweeklywages(totalhours, hourlywage):
'''Return the total weekly wages for a worker working totalHours,
with a given regular hourlyWage. Include overtime for hours over 40.
'''
if totalhours <= 40:
totalwages = hourlywage * totalhours
else:
overtime = totalhours - 40
totalwages = hourlywage * 40 + (1.5 * hourlywage) * overtime
return totalwages
def main():
hours = float(input('Enter hours worked: '))
wage = 34
total = calcweeklywages(hours, wage)
print('Wages for {hours} hours at ${wage:.2f} per hour are ${total:.2f}.'
.format(**locals()))
main()
elif worker == "Johnathan":
def calcweeklywages(totalhours, hourlywage):
'''Return the total weekly wages for a worker working totalHours,
with a given regular hourlyWage. Include overtime for hours over 40.
'''
if totalhours <= 40:
totalwages = hourlywage * totalhours
else:
overtime = totalhours - 40
totalwages = hourlywage * 40 + (1.5 * hourlywage) * overtime
return totalwages
def main():
hours = float(input('Enter hours worked: '))
wage = 30
total = calcweeklywages(hours, wage)
print('Wages for {hours} hours at ${wage:.2f} per hour are ${total:.2f}.'
.format(**locals()))
main()
I want to add a part where if someone types in a code or something that they're an admin, it will let them add a person or edit an existing persons information.
I am not sure how you intend to deploy it, but even from the coding standpoint as it stands it will not behave the way you expect it to. I am guessing you are doing this just to learn. So, let me point out a couple of places where you have understood the basics wrong and a purely pedagogic example of how it could be done. Bear in mind that I strongly discourage from using this in any real context.
You have defined the function calcweeklywages twice in your code. When in fact it has to be defined just once. If you want to use the code, you call it, like you have done so in the main() program. The function works exactly the same for both your workers, so to get different weekly wages you pass different wages. But, how do you link their respective wages to their names (or some representation of them in your code)?
This is a good example where object oriented programming is used. A brief and entertaining primer is here. As for the code, it will look like this,
class Employee:
def __init__(self, Name, Wage = 0, Hours = 0):
self.Name = Name
self.Wage = Wage
self.Hours = Hours
def calcweeklywages(Employee, totalhours):
'''Return the total weekly wages for a worker working totalHours,
with a given regular hourlyWage. Include overtime for hours over 40.
'''
hourlywage = Employee.Wage
if totalhours <= 40:
totalwages = hourlywage * totalhours
else:
overtime = totalhours - 40
totalwages = hourlywage * 40 + (1.5 * hourlywage) * overtime
return totalwages
# In your main body, you just test the functionality
EmployeeList = []
EmployeeList.append(Employee("Anne", 34))
EmployeeList.append(Employee("Johnathan", 30))
while(True):
action = input('Exit? (y/n): ')
if(action == 'y'):
break
else:
name = input('Enter the employee\'s name: ')
for Employee in EmployeeList:
if(Employee.Name == name):
Person = Employee
hours = int(input('Enter the number of hours worked: '))
print('Wages for', hours, 'hours at', Person.Wage,'per hour is', calcweeklywages(Person, hours))
EDIT: I am sorry, I forgot about the admin part. But here goes,
class Employee:
def __init__(self, Name, Wage = 0, Hours = 0, Admin = False, code = ''):
self.Name = Name
self.Wage = Wage
self.Hours = Hours
self.Admin = Admin
self.code = code
def calcweeklywages(Employee, totalhours):
'''Return the total weekly wages for a worker working totalHours,
with a given regular hourlyWage. Include overtime for hours over 40.
'''
hourlywage = Employee.Wage
if totalhours <= 40:
totalwages = hourlywage * totalhours
else:
overtime = totalhours - 40
totalwages = hourlywage * 40 + (1.5 * hourlywage) * overtime
return totalwages
# In your main body, you just test the functionality
EmployeeList = []
EmployeeList.append(Employee("Anne", 34))
EmployeeList.append(Employee("Johnathan", 30))
EmployeeList.append(Employee("Mr. Admin", 50, 0, True, 'Open Sesame'))
while(True):
action = int(input('Enter action :\n 1. Exit.\n 2. Add new employee.\n 3. Compute weekly wage\n'))
if(action == 1):
break
elif(action == 2):
AdminName = input('Enter operator name : ')
Flag = False
for EmployeeInst in EmployeeList:
if((EmployeeInst.Name == AdminName) & (EmployeeInst.Admin)):
code = input('Enter code :')
if(code != EmployeeInst.code):
break
NewName = input('New Employee name? :')
NewWage = int(input('New employee wage? :'))
EmployeeList.append(Employee(NewName, NewWage))
Flag = True
if(not Flag):
print('Wrong Credentials')
break
elif(action == 3):
name = input('Enter the employee\'s name: ')
for Employee in EmployeeList:
if(Employee.Name == name):
Person = Employee
hours = int(input('Enter the number of hours worked: '))
print('Wages for', hours, 'hours at', Person.Wage,'per hour is', calcweeklywages(Person, hours))
else:
print('Input out of range')
break
But again, the session is not persistent between different kernel runs. There is no real "security", this is just an exploration of Python's object oriented code. Please do not use this for any real application. There is a lot more that goes with all this. You need to store it in a secure file, have some GUI front end etc etc. There are far wiser users who will guide you to implement the system as a whole. All the best with your studies. Cheers.
Having errors when running a program for counting ice skating scores
the errors are as followed when running in python 3.7.0
Errors when loading in python 3.7.0
. Any help appreciated thank you
Here is the task I was given and I am required to use def and sub procedures:
Program 1
A program is to be written to process scores by competitors in an
ice-skating competition. Each skater receives a score in the range
0.0-6.0 from each of the 6 judges. A skater’s overall score is calculated from the total of the 6 scores minus the best and the worst
scores.
Create a modular program which makes use of parameter passing to
implement the specification above.
def get_scores(score,totalscore,checknumber):
loops = 0
for loops in range(0,6):
checknumber = validatescore(checknumber)
score[loops]=float(checknumber)
maxi = find_max(score)
mini = find_min(score)
totalscore = totalscore + calculate_score(score,totalscore,maxi,mini)
return score[loops],totalscore,checknumber
def find_min(score):
min = 100
for counter in range (0,len(score)):
if score[counter] < min:
mini = score[counter]
return mini
def find_max(score):
max = 100
for counter in range (0,6):
if score[counter] < max:
maxi = score[counter]
return maxi
def calculate_score(score,totalscore,maxi,mini):
for loops in range(0,6):
totalscore = totalscore + score[loops]
totalscore = totalscore - maxi - mini
return totalscore,maxi,mini
def displaydetails (totalscore,maxi,mini):
print("The competitor scored: ",totalscore, "The max was :",maxi," The min was :",mini)
def validatescore(checknumber):
valid = False
checknumber = 0
print("Please enter the score of the competitor")
checknumber = float(input())
while valid == False:
if checknumber < 0.0 or checknumber > 6.0:
print("Invalid mark - please enter a whole number between 0.0 and 6.0")
checknumber = float(input())
else:
valid = True
return checknumber
totalscore = 0.0
score = [0.0] * 6
checknumber = 0.0
score,totalscore,checknumber = get_scores(score,totalscore,checknumber)
displaydetails(totalscore,maxi,mini)
The question is to find the fixed amount you need to pay to a credit card company when -
bal= the amount you need to pay at the beginning of 0th month
N = it is the monthly fixed amount to be to paid to the credit card company such that at the end of the year, you will have paid the total amount
int = interest rate of the credit card company
bal = int(raw_input("Enter balance"))
rate = int(raw_input("enter rate"))
lower_b = bal/12
upper_b = (bal + ((rate*bal)/1200))/12
N= (lower_b+upper_b)/2
def Credit(bal,rate,N):
global upper_b
global lower_b
i=1
k=bal
while (i<13):
print(N)
paid = N
bal = bal - paid
print("Balance remains to be paid is %s" %(round(bal,2)))
Interest = rate * bal /1200
print("The interest added on is %s" %(round(Interest,2)))
bal=bal+Interest
print ("The amount that needs to be payed is %s " %(round(bal,2)))
i=i+1
if bal==0:
return N
elif 50 < bal < 2000 :
lower_b = N
upper_b = upper_b
N = (upper_b +lower_b)/2
return Credit(k,rate,N)
elif -2000<bal< -50:
upper_b = N
lower_b = lower_b
N = (lower_b +upper_b)/2
return Credit(k,rate,N)
elif -50 < bal < 50:
return N
else:
return bal
result=Credit(bal,rate,N)
print(result)
My code never terminates. The problem is the value of N defined in the code is not changing. It remains fixed N = upper_b +lower_b)/2
Using recursion would not be the ideal approach, you also have logic errors including needing to get the interest rate for the month, your initial upper bound should be greater than the principal plus the interest. You can use a while loop with an inner for loop resetting the balance after each unsuccessful inner loop:
balance = int(raw_input("Enter balance"))
int_rate = float(raw_input("enter rate"))
int_rate /= 100
lower_b = balance / 12.
upper_b = ((balance * (1 + (int_rate / 12.0)) ** 12) / 12.0)
payment = (lower_b + upper_b) / 2
def Credit(bal, rate, low, high, pay):
new_b = bal
# calculate monthly interest rate
month_int = rate / 12
while abs(new_b) > 0.001: # use epsilon
# always reset balance
new_b = bal
for _ in range(12): # loop over 12 month range
new_b -= pay # deduct pay
new_b += month_int * new_b
# if we still have a balance we need to take more so set low to current payment
if new_b > 0:
low = pay
# else we took to much so set high to current payment
else:
high = pay
pay = (low + high) / 2.0
return "Lowest monthly payment over 12 months: {}".format(pay)
print(Credit(balance, int_rate, lower_b, upper_b, payment))
Folks,
I am getting my head stuck in knots here with problem 3 from PS1 in MIT6.00. I have written a couple of functions (one bisection search, and one function modelling the credit card debt). The problem is that it converges on a solution that gives a slightly positive remaining credit card balance. I could lower the tolerance in the bisection search, but I wanted to know if there was some more elegant way of making this optimiser return only negative results.
Cheers,
Aiden
code:
import numpy as np
def bisection(a, b, fun, tol, var = None):
"""Note that this only works if you put the independant variable
as the first argument in the parameter """
#def tstr(x):
# return 2*(x**2) - 3*x + 1
#sol = bisection(0,0.9,tstr,0.1)
c = (a+b)/2.0
if var != None:
arga = var[:]
argc = var[:]
arga.insert(0,a)
argc.insert(0,c)
else:
arga = a
argc = c
if (b-a)/2.0 <= tol:
#Debugging print statement 1:
#print 'SOL1: c = ', c
if var != None:
return [c] + fun(argc)
else:
return c
if fun(argc)[0] == 0:
if var != None:
return [c] + fun(argc)
else:
return c
elif fun(arga)[0]*fun(argc)[0] < 0:
b = c
else:
a = c
return bisection(a, b, fun, tol, var)
"""
Now we have defined a version of the paidOff function to work
with the bisection method"""
def paidOffBis(args):#(Pay, Bal, Apr):
"""Tester for Bisection Implementation"""
# TEST SIZE OF args:
if (type(args) != list)|(np.size(args) != 3):
print 'Incorrect size or type of input, input size:', np.size(args), '-', args
return None
Pay, Bal, Apr = args
Mpr = Apr/12.0
Baln = Bal
Nm = 0
for n in range(12):
Baln = Baln*(1 + Mpr) - Pay
if (Baln < 0)&(Nm == 0):
Nm = n + 1
if Baln < 0:
return [Baln, Nm]
else:
return [Baln, Nm]
Out_Bal = float(raw_input('Enter the outstanding balance on your credit card: '))
Apr = float(raw_input('Enter the annual credit card interest rate as a decimal: '))
varin = [Out_Bal, Apr]
#(Out_Bal*(1 + (Apr/12.0))**12.0)/12.0
sol = bisection(Out_Bal/12.0, Out_Bal, paidOffBis, 0.01, varin)
print 'RESULT'
print 'Monthly payment to pay off debt in 1 year: $%.2f' % sol[0]
print 'Number of months needed:', sol[2]
print 'Balance: $%.2f' % sol[1]
To ensure a balance less than or equal to zero you need to set your conditional statements correctly - you need to keep searching till that criteria is met. You asked for ... a more elegant way .... Using descriptive names for your variables and keeping it simple would certainly improve your code. Here is one way to craft a solution using a bisection search.
annualInterestRate = .1
balance = 1000
def balance_after_one_year(balance, annualInterestRate, payment):
'''Calculate the balance after one year of interest and payments.
balance --> int or float
annualInterestRate --> float between 0 and 1
payment --> float
returns float
'''
for _ in xrange(12):
balance = (balance - payment) * (1 + annualInterestRate / 12.0)
return balance
def min_payment(balance, annualInterestRate, tolerance = .01):
'''Find the minimum payment to pay off a loan.
Uses a bisection search.
Ensures balance is not positive.
balance --> float, int
annualInterestRate --> float less than one
tolerance --> float
'''
# we want the tolerance to be negative
# this isn't strictly a tolerance, it is a lower limit
tolerance = -abs(tolerance)
hi = balance
lo = 0
while True:
payment = (hi + lo) / 2.0
tmp_balance = balance_after_one_year(balance, annualInterestRate, payment)
if tmp_balance < tolerance:
hi = payment
# ensure balance is not positive
elif tmp_balance > 0:
lo = payment
else:
return payment, tmp_balance
Usage:
min_pmt, final_balance = min_payment(balance, annualInterestRate)
print 'minimum payment', min_pmt
print 'final balance', final_balance
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()