I am a beginner to Python and i'm having a hell of a time trying to get this program to work. I need to pass local variables to other modules and I've tried multiple things and I can't get it to work. It's just a Extremely simple program that calculates commission. I've literally spent hours trying to get it to work. I'm using the latest version of Python.
import os
def main():
input_salesperson_data()
commission = calculate_commission(sales_amount)
determine_bonus(years_worked, commission)
output_commission(name, commission)
def input_salesperson_data():
name = (input("\n\t\tWhat is the full name of the salesperson: "))
sales_amount = float(input("\n\t\tWhat is the sales amount of the salesperson: "))
years_worked = int (input("\n\t\tHow many years has the salesperson worked for the company: "))
return(name, sales_amount, years_worked)
def calculate_commission(sales_amount):
commission_rate1 = 0.15
commission_rate2 = 0.25
commission_rate3 = 0.30
if sales_amount <= 20000:
commission = sales_amount * commission_rate1
elif sales_amount > 20000 and sales_amount <= 40000:
commission = sales_amount * commission_rate2
else:
commission = sales_amount * commission_rate3
return(commission)
def determine_bonus(sales_amount, years_worked, commission):
if years_worked > 20:
commission *= 2
return(commission)
def output_commission(name, commission):
os.system("cls")
print("\n\n\t\t\t SALESPERSON COMMISSION REPORT")
print("\n\t\t\tSalesperson Name: ", name)
print("\t\t\tCommission Amount: ", format(commission, ',.2f'))
input("\n\t\tPress enter to exit...")
os._exit(1)
main()
def main():
information = input_salesperson_data()
commission = calculate_commission(information[1])
determine_bonus(information[2], commission)
output_commission(information[0], commission)
In python, the scope of the variable is contained in the function; however, in input_salesperson_data(), you're returning a tuple, but not saving it. information will save what is returned by input_salesperson_data(), and you can access what you need as shown above.
Also, in calculate_commission(), you can simple return commission. Additionally, you don't need to manually exit the program.
Finally, change:
def determine_bonus(sales_amount, years_worked, commission):
to
def determine_bonus(years_worked, commission):
as sales_amount is completely irrelevant.
Related
I cannot get Pytest to test anything involving this code. It always says no tests ran when I use the code below. I'm trying to just get it to test and from there I can tinker with the rest, I'm just a bit stuck on this and can't figure it out. The code runs well, exactly as intended it's just when I try to pytest with it that I'm reciving a problem.
import datetime
tday = datetime.date.today()
balance = 1000.0
amount = float
transaction_list = []
class Account(amount):
def get_balance(self):
print("\n This is your account balance: " + str(balance))
def deposit(self, amount):
global balance
amount = float(input("\n How much would you like to deposit? "))
if amount > 10000:
print("\n Do you want to swim in the vualt? ")
transaction_list.append("You deposited " + str(amount))
balance = balance + amount
print("\n You're balance is now " + str(balance))
def withdrawl(self, amount):
global balance
amount = float(input("\n How much do you wanna take out? "))
while amount > balance:
amount = float(input("\n You don't have enough funds. Enter a new value "))
transaction_list.append("\n You withdrew " + str(amount))
balance = balance - amount
print("\n You're balance is now " + str(balance))
class Transaction(amount):
def transaction(self):
print("\n")
print(" " + str(card_number) + " " + str(tday))
print("\n Recipt: HM21-1926\n")
print("\n Account: Chequing. Primary\n")
print("\n Here is your transaction history!\n")
for i in transaction_list:
print(i)
print("\n Account Balance: " + str(balance))
print("\n Limited time offer: get a personal loan starting at Prime + 1.99%*")
print("\n Offer valid until September 2, 2022.")
print("\n Conditions apply & approval required. Ask us for details.\n")
account = Account()
transaction = Transaction()
if __name__ == "__main__":
mike_lane = Account()
print(repr(mike_lane))
print(str(mike_lane))
The code below is the code I'm trying to use pytest on. I don't know if there is something wrong with what I'm trying to test or if there is something wrong with the main code. I'm just starting out with programming and this is a bit complicated for me still (However, I have to learn to do this for the class so I'm not able to come back to learn TDD later on)
import bank_program
def test_deposit():
account = Account(100)
assert balance.amount == 1100
def test_depos():
with pytest.raises(ValueError):
assert amount = Account("ABC")
def test_transactions():
account = Account(100)
assert tday() >= now
As mentioned in the title I am getting a TypeError: 'float' object is not callable when using my code.
The code runs once correctly with the information that I want but fails to run the second time using for fare in fares.
Error message is here:
File "/Users/dty2004/Desktop/AS 91373.py", line 71, in <module>
discounted_price(destination_fare)
TypeError: 'float' object is not callable
Code is here:
# Define the lists required for storing discount and discount_price
fare_auck = ["Auckland"]
fare_well = ["Wellington"]
fare_roto = ["Rotorua"]
# Make the lists into a 2D list
fares = [fare_auck, fare_well, fare_roto]
# Define the menu() function, which gives us the basic interface for
launching functions
def menu(destination, discounted_price, discount, saver_type,
original_price):
print("***** Waikato Air *****")
print("These saver fares for tomorrow only!")
print("Destination: {}".format(destination))
print("Discounted Price: ${:.2f}".format(discounted_price))
print("Percentage Discount: {:.2f}%".format(discount))
print("This fare is a: {}".format(saver_type))
print("Original Price: ${:.2f}".format(original_price))
print("") # Added an empty string to format the function to look nice
consecutively
# Define the function for destination determination
def destination_determiner():
if fares[0][0] == "Auckland":
travel_location = "Auckland"
fares[0].insert(0, "placeholder")
return travel_location
elif fares[1][0] == "Wellington":
travel_location = "Wellington"
fares[1].insert(0, "placeholder")
return travel_location
elif fares[2][0] == "Rotorua":
travel_location = "Rotorua"
fares[2].insert(0, "placeholder")
return travel_location
# Define the function for determining the type of saver fare this is
def saver_type(discount):
if discount < 20 and discount > -1:
saver_type = "Quick Saver"
return saver_type
elif discount >= 20 and discount <= 50:
saver_type = "Smart Saver"
return saver_type
elif discount > 50 and discount < 101:
saver_type = "Super Saver"
return saver_type
else:
print("Sorry that input is invalid")
# Define the function for determining the original_price
def original_price_calc(discount, discounted_price):
original_price = discounted_price * (discount / 100 + 1)
return original_price
# Define the function for getting discounted_price from user input
def discounted_price(destination):
discounted_price = float(input("Please input the discounted price to
{}".format(destination_fare)))
fare.append(discounted_price)
# Define the same function for getting discount from user input
def discount(destination):
discount = float(input("Please input the discount in percentage to
{}".format(destination_fare)))
fare.append(discount)
# Run the entire code, formatted into a print statement
for fare in fares:
destination_fare = destination_determiner()
discounted_price(destination_fare)
discount(destination_fare)
discounted_price = fare[2]
discount = fare[3]
menu(destination_fare, discounted_price, discount, saver_type(discount),
original_price_calc(discount, discounted_price))
This runs once using accepted values in this example of 100 and 30:
Please input the discounted price to Auckland100
Please input the discount in percentage to Auckland30
***** Waikato Air *****
These saver fares for tomorrow only!
Destination: Auckland
Discounted Price: $100.00
Percentage Discount: 30.00%
This fare is a: Smart Saver
Original Price: $130.00
I'm unsure as to why this works the first time but not the second.
Also bear in mind I am a student and so may not have much knowledge on more advanced python commands.
Thanks in advance.
You're reassigning discounted_price to a variable here:
# Run the entire code, formatted into a print statement
for fare in fares:
destination_fare = destination_determiner()
discounted_price(destination_fare) # still a function
discount(destination_fare)
discounted_price = fare[2] # now a float!!!!
discount = fare[3] # same with this (overrides discount from earlier)
menu(destination_fare, discounted_price, discount, saver_type(discount),
original_price_calc(discount, discounted_price))
Rename the variable to something else
for fare in fares:
destination_fare = destination_determiner()
discounted_price(destination_fare)
discount(destination_fare)
discounted_price_value = fare[2]
discount_value = fare[3]
menu(destination_fare, discounted_price_value, discount_value,
saver_type(discount_value),
original_price_calc(discount_value, discounted_price_value))
I'm brand new to python, and programming in general, so this is probably something extremely simple, but I'm persistently getting this syntax error at the end of the line defining my function for minPayment. I can't see any problem with it... here is the program so far.
Problem set 1: credit card balance calculator
print 'Month 1'
OutstandingBalance = raw_input(float('enter your balance'))
AnnualInterestRate = raw_input(float('enter rate as a decimal(%/100)'))
MinimumMonthlyPaymentRate = raw_input(float('enter minimum monthly payment rate as a decimal(%/100)'))
def minPayment:
minPayment = MinimumMonthlyPaymentRate * OutstandingBalance
print 'minimum payment='minPayment
return minPayment
def accIntrst:
accIntrst = (AnnualInterestRate/12.0) * OutstandingBalance
print 'accrued interest = 'accIntrst
return accIntrst
def balPaid:
balPaid = accIntrst - minPayment
print 'balance paid = 'balPaid
return balPaid
def remBal:
remBal = OutstandingBalance - balPaid
print 'remaining balance = 'remBal
return remBal
Any feedback is greatly appreciated!
Add parentheses to your functions. Python syntax dictates so.
So, instead of def minPayment:, write def minPayment(): instead.
def main():
totalprofit = 0
stockname = input("Enter the name of the stock or -999 to quit: ")
while stockname != "-999":
sharesbought, purchasingprice, sellingprice, brokercommission = load()
amountpaid, amountofpaidcommission, amountstocksoldfor, amountofsoldcommission, profitorloss = calc(sharesbought, purchasingprice, sellingprice, brokercommission)
output(stockname, amountpaid, amountofpaidcommission, amountstocksoldfor, amountofpaidcommission, profitorloss)
stockname = input("Enter the name of the next stock (or -999 to quit): ")
totalprofit += profitorloss
print("\n Total profit is: ", format(totalprofit, '.2f'))
def load():
sharesbought = int(input("Number of shares bought: "))
purchasingprice = float(input("Purchasing price: "))
sellingprice = float(input("Selling price: "))
brokercommission = float(input("Broker commission: "))
return sharesbought, purchasingprice, sellingprice, brokercommission
def calc(sharesbought, purchasingprice, sellingprice, brokercommission):
amountpaid = sharesbought * purchasingprice
amountofpaidcommission = amountpaid * (brokercommission/100)
amountstocksoldfor = sharesbought * sellingprice
amountofsoldcommission = amountstocksoldfor * (brokercommission/100)
profitorloss = (amountpaid + amountofpaidcommission) - (amountstocksoldfor - amountofsoldcommission)
return amountpaid, amountofpaidcommission, amountstocksoldfor, amountofsoldcommission, profitorloss
def output(stockname, amountpaid, amountofpaidcommission, amountstocksoldfor, amountofsoldcommission, profitorloss,):
print("\n Stock name: ", stockname, sep = '')
print("Amount paid for the stock: ", format(amountpaid, '.2f'))
print("Commission paid to broker when the stock was bought: ", format(amountofpaidcommission, '.2f'))
print("Amount the stock sold for: ", format(amountstocksoldfor, '.2f'))
print("Commission paid to broker when the stock was sold: ", format(amountofsoldcommission, '.2f'))
print("Profit or loss: ", format(profitorloss, '.2f'))
main ()
The objective of the first function is to allow a user to input the followings as many times as she or he wants until the user decides is done:
Stock name
Shares bought
Selling price
Broker commission
My main problem is then in the main function. I am skeptical whether I am using the while loop correctly or if it's correct at all. I tried to run the program but it won't output anything.
Also, shouldn't I add this at the end of the program with the values inputted to call all the functions above:
def main()
load()
calc()
output()
Or is it fine within the while loop?
I think a while loop is perfectly appropriate for this use case, where you want to loop an indeterminate number of times, stopping when some condition is not met.
There is one obvious problem, on this line:
stockname +=1
This doesn't make any sense. Since stockname is a string, you can't add one to it. Instead, you should be asking the user for the next stock name (or a "special" value to signal they're done). Try replacing that line with something like:
stockname = input("Enter the name of the next stock (or -999 to quit): ")
The rest of your code appears correct, if rather verbose. Unless you think it's likely you'll call some of your other functions in some other place in your code, it might be simpler and cleaner to include all the logic in one function. Functions are nice, but you should balance the benefits of isolating each part of your code in its own function against the effort of passing lots of values between them.
Trying to create a program that determines discounts in a book shop, unsure about returning values from functions to main though, Help would be greatly appreciated
def main():
print (" Please enter the amount spent on the following items:")
Books = int(input("Books: "))
Magazines= int(input("Magazines: "))
Newspapers= int(input("Newspapers: "))
print (book_disc)
def discounts(Books, Magazines, Newspapers):
book_disc = Books - (Books *.2)
mag_disc = Magazines - (Magazines*.1)
news_disc = Newspapers
return discounts
return (book_disc, mag_disc, news_disc)
main()
Here's what I found:
You had some indentation issues
You are trying print (book_disc) before book_disc is defined (it's now been removed)
Your returns were out of order return (book_disc, mag_disc, news_disc) needed to be in your discounts() function
return discounts needed arguments
def main():
print (" Please enter the amount spent on the following items:")
Books = int(input("Books: "))
Magazines= int(input("Magazines: "))
Newspapers= int(input("Newspapers: "))
def discounts(Books, Magazines, Newspapers):
book_disc = Books - (Books *.2)
mag_disc = Magazines - (Magazines*.1)
news_disc = Newspapers
return (book_disc, mag_disc, news_disc)
return discounts(Books, Magazines, Newspapers)
main()