# Profit and Loss
# Function to calculate Profit.
def Profit(costPrice, sellingPrice):
profit = (sellingPrice - costPrice)
return profit
# Function to calculate Loss.
def Loss(costPrice, sellingPrice):
Loss = (costPrice - sellingPrice)
return Loss
if __name__ == "__main__":
input(costPrice, sellingPrice)
if sellingPrice == costPrice:
print("No profit nor Loss")
elif sellingPrice > costPrice:
print(Profit(costPrice,
sellingPrice), "Profit")
else:
print(Loss(costPrice,
sellingPrice), "Loss")
The error code:
Traceback (most recent call last): File "C:/Users/sharv/PycharmProjects/FInal Robotic/Finals.py", line 18, in <module>
input(costPrice, sellingPrice) NameError: name 'costPrice' is not defined
Process finished with exit code 1
If you would like to input 2 values from the user, you will have to do it like that:
cost_price = input("Enter Cost Price: ")
sell_price = input("Enter Selling Price: ")
The input function in python takes as argument a string text to display to the user (An optional argument) and returns the inputed value from the user (as a str object). If you would like to convert those values into numbers, you will have to do something like:
# integer values
cost_price = int(input("Enter Cost Price: "))
sell_price = int(input("Enter Selling Price: "))
# OR:
# Floating point values
cost_price = float(input("Enter Cost Price: "))
sell_price = float(input("Enter Selling Price: "))
input(costPrice, sellingPrice)
Whoever told you input takes output variables as arguments is mistaken. If you want to input into the two variables, you'll do so as follows
costPrice = input()
sellingPrice = input()
You'll also likely want to convert them to numbers.
costPrice = float(input())
sellingPrice = float(input())
Related
Below is my code. the issue is in MAIN. The code works as a person trying to buy items into a cart and you can see the total price of those items. They have to enter in the price for each item that they want. If a person inputs a number to two decimal places, it rounds it to the nearest whole number.
import locale
class CashRegister:
def __init__(self):
mself.items = 0
self.price = int(float(0.00))
def addItems(self,price): #keeps track of total number of items in cart
self.price += price
self.items += 1
print(self.price)
def getTotal(self): #returns total price
return self.price
def getCount(self): #return the item count of the cart
return self.items
def clearCart(self): #clears cart for another user or checkout
self.items = 0
self.price = int(float(0.00))
def main():
user_name = input('What is your name?\n') #weclomes user
print("Hello",user_name)
locale.setlocale(locale.LC_ALL, 'en_US')
user_name = CashRegister() #user is using the cash register
while True:
line = input ("Would you like to add another food item to your cart? Choose y or n \n")
if line == "y":
** price = int(float(input("please input the price of the item\n")))
print(price)**
user_name.addItems(price) #user adds prices to cart
elif line == "n":
print("Your total checkout price:", locale.currency(user_name.getTotal()) )
# int(float(locale.currency(user_name.getTotal())))
print("Your total item count", user_name.getCount())
user_name.clearCart() #clears cart for another user/checkout
break
else:
print("Error")
if __name__ == '__main__':
main()
As soon as the person inputs the number, I printed it to see if that's where the problems lies. I'll enter 3.20 but it automatically converts it to 3. I have no idea how to force it to keep those decimals. I even tried printing it with the int/float and it still doesn't work.
The int() function always returns an integer. An integer never has any decimal points. So use only
float(input("please input the price of the item\n"))
instead of
int(float(input("please input the price of the item\n")))
So I basically created my functions ( def main(), load(), calc(), and print().
But I do not know how I can allow the user to input the information as many times as he/she wants until they want to stop. Like I they input 5 times, it would also output 5 times. I have tried putting the while loop in the def main() function and the load function but it won't stop when I want it to. Can someone help? Thanks!
def load():
stock_name=input("Enter Stock Name:")
num_share=int(input("Enter Number of shares:"))
purchase=float(input("Enter Purchase Price:"))
selling_price=float(input("Enter selling price:"))
commission=float(input("Enter Commission:"))
return stock_name,num_share,purchase,selling_price,commission
def calc(num_share, purchase, selling_price, commission):
paid_stock = num_share * purchase
commission_purchase = paid_stock * commission
stock_sold = num_share * selling_price
commission_sale = stock_sold * commission
profit = (stock_sold - commission_sale) - ( paid_stock + commission_purchase)
return paid_stock, commission_purchase, stock_sold, commission_sale, profit
def Print(stock_name,paid_stock, commission_purchase, stock_sold, commission_sale, profit):
print("Stock Name:",stock_name)
print("Amount paid for the stock:\t$",format(paid_stock,'10,.2f'))
print("Commission paid on the purchase:$", format(commission_purchase,'10,.2f'))
print("Amount the stock sold for:\t$", format(stock_sold,'10,.2f'))
print("Commission paid on the sale:\t$", format(commission_sale,'10,.2f'))
print("Profit(or loss if negative):\t$", format(profit,'10,.2f'))
def main():
stock_name,num_share,purchase,selling_price,commission = load()
paid_stock,commission_purchase,stock_sold,commission_sale,profit = calc(num_share, purchase, selling_price, commission)
Print(stock_name, paid_stock,commission_purchase, stock_sold, commission_sale, profit)
main()
You have to give the user some kind of way to declare their wish to stop the input. A very simple way for your code would be to include the whole body of the main() function in a while loop:
response = "y"
while response == "y":
stock_name,num_share,purchase,selling_price,commission = load()
paid_stock,commission_purchase,stock_sold,commission_sale,profit = calc(num_share, purchase, selling_price, commission)
Print(stock_name, paid_stock,commission_purchase, stock_sold, commission_sale, profit)
response = input("Continue input? (y/n):")
an even simpler way would be two do the following....
while True:
<do body>
answer = input("press enter to quit ")
if not answer: break
alternatively
initialize a variable and avoid the inner if statement
sentinel = True
while sentinel:
<do body>
sentinel = input("Press enter to quit")
if enter is pressed sentinel is set to the empty str, which will evaluate to False ending the while loop.
I'm in Grade 11 Computer Science at my highschool, and I'm just starting out in Python. I'm supposed to make a function called computepay that will ask the user their name, their wage, and their hours that week and automatically calculate the total, including any overtime and not error out when an incorrect input is included. I made different functions for all the inputs, but when I plug it all into my computepay function it tells me this:
TypeError: float() argument must be a string or a number
def mainloop(): #Creating a loop so it doesn't error out.
response = input('Make another calculation?[y/n]') #inputing loop
if response == 'n': #creating input for n
return
if response == 'y':
computepay()
else:
print("\n")
print ("Incorrect input. .")
mainloop()
def getname():
name = input ("What's your name?") #input of name
def getwage():
wage = input ("Hello there! How much money do you make per hour?") #input
try:
float(wage) #Making it so it does not error out when a float
except:
print ("Bad Input")
getwage()
def gethours():
hours = input ("Thanks, how many hours have you worked this week?")
try:
float(hours) #Making it so it does not error out when a float
except:
print("Bad Input")
gethours()
def computepay():
name = getname()
wage = getwage()
hours = gethours()
if float(hours) > float(40):
newhours = float(hours) - float (40) #figuring out the amount of overtime hours the person has worked
newwage = float (wage) * float (1.5) #figuring out overtime pay
overtimepay = float (newwage) * float (newhours) #calculating overtime total
regularpay = (float(40) * float (wage)) + overtimepay #calculating regular and overtime total.
print (name,",you'll have made $",round(regularpay,2),"this week.")
else:
total = float(wage) * float(hours)
print (name,",you'll have made $",round (total,2),"this week.")
mainloop() #creating the loop.
#-------------------------------------------------------------------------------
computepay()
None of these functions are returning anything
name = getname()
wage = getwage()
hours = gethours()
So they all end up being None
Try this
def getname():
return input("What's your name?") # input of name
def getwage():
wage = input("Hello there! How much money do you make per hour?") # input
return float(wage)
def gethours():
hours = input("Thanks, how many hours have you worked this week?")
return float(hours)
What the error message is telling you is that somewhere (on the line number reported in the part of the error message that you didn't show us) you are calling float and giving it an argument (i.e. an input) that is neither a number, nor a string.
Can you track down where this is happening?
Hint: Any Python function which doesn't return anything (with the return keyword) implicitly returns None (which is neither a string nor a number).
So first I'm trying to make a class, which holds an item's name, price, and quantity available. Then I wanted to make a function that will deduct the quantity sold to a buyer after they enter the amount they are buying, and then calculate the total price.
Now to add on top of that, I am trying to have the user select from a list of items.
The problem is it seem I seem to be getting errors around the time the program starts running the 'buy' function.
class Retail:
def __init__(self, price, unitsOnHand, description):
self.price = price
self.unitsOnHand = unitsOnHand
self.description = description
def buy (self):
print ("How many are you buying?")
quant = int(input("Amount: "))
unitsOnHand -= quant
subto = price * quant
total = subto * 1.08
print ("There are now ", unitsOnHand, " left")
print ("The total price is $", total)
box = Retail(4.95, 20, "Boxes")
paper =Retail(1.99, 50, "Big Stacks of Paper")
staples =Retail(1.00, 200, "Staples")
ilist = (box, paper, staples)
print ("Which are you buying? ", [box.description, paper.description, staples.description])
ioi = input("Please use the exact word name: ")
if ioi == 'box':
Retail.buy(ilist[0])
elif ioi == 'paper':
Retail.buy(ilist[1])
elif ioi == 'staples':
Retail.buy(ilist[2])
The error I get when I tried to run it is
Traceback (most recent call last):
File "C:/Users/XXXXXX/XXXX/Code/Retailclass", line 22, in <module>
Retail.buy(ilist[0])
File "C:/Users/XXXXXX/XXXX/Code/Retailclass", line 9, in buy
unitsOnHand -= quant
UnboundLocalError: local variable 'unitsOnHand' referenced before assignment
I'm guessing is that it doesn't see the values I already assigned to the item, and if that is the case, how do I get it to?
Others have pointed out your error, but the other thing that is wrong is your buy call needs to be done on an instance of the object, not the class itself. In other words, right now you are executing buy on the Retail class where you need to execute it on instance (objects) of the class.
I have another suggestion to help organize your code. Use a dictionary to map the keys to the various objects to make your loop a bit cleaner. Putting all that together (and some other checks), here is an updated version of your class:
class Retail(object):
def __init__(self, price, unitsOnHand, description):
self.price = price
self.unitsOnHand = unitsOnHand
self.description = description
def buy(self):
if self.unitsOnHand == 0:
print('Sorry, we are all out of {} right now.'.format(self.description))
return
print("How many are you buying? We have {}".format(self.unitsOnHand))
quant = int(input("Amount: "))
while quant > self.unitsOnHand:
print('Sorry, we only have {} left'.format(self.unitsOnHand))
quant = int(input("Amount: "))
self.unitsOnHand -= quant
subto = self.price * quant
total = subto * 1.08
print("There are now {} left".format(self.unitsOnHand))
print("The total price is ${}".format(total))
return
stock = {}
stock['box'] = Retail(4.95, 20, "Boxes")
stock['paper'] = Retail(1.99, 50, "Big Stacks of Paper")
stock['staples'] = Retail(1.00, 200, "Staples")
print("Which are you buying? {}".format(','.join(stock.keys())))
ioi = input("Please use the exact word name: ")
while ioi not in stock:
print("Sorry, we do not have any {} right now.".format(ioi))
print("Which are you buying? {}".format(','.join(stock.keys())))
ioi = input("Please use the exact word name: ")
stock[ioi].buy()
i am just writing a simple currency converter program, and the one problem that i am facing is that i can't think how to have the user change the content of the variable. Below is an the basic bit:
def D2Y():
def No():
newconv=float(input("What is the rate that you want to use: "))
amount=float(input("How much do you want to convert: $"))
conversionn=round(amount*newconv,2)
print("¥",conversionn)
return (rerun())
def Yes():
conrate2=float(97.7677)
amount=float(input("How much do you want to convert: $"))
conversion=round(amount*conrate2,2)
print("¥",conversion)
return (rerun())
def rerun():
rerun=int(input("Do you want to go again?\n1 - Yes\n2 - No\nChoice: "))
if rerun==1:
return (main())
else:
print("Thank you for converting")
conrate1=int(input("The currency conversion rate for Yen to 1 US Dollar is ¥97.7677 to $1\n1 - Yes\n2 - No\nDo you want to use this rate?: "))
if conrate1==1:
return (Yes())
else:
return (No())
I dont know how you do it. I dont mind if you get rid of the def functions.
Here's an approach that does away with the functions and allows you to modify the exchange rate:
rate = CONVERSION_RATE = 97.7677
while True:
print "The currency conversion rate for Yen to 1 US Dollar is ¥%.4f to $1" % rate
print 'Select an option:\n1)Modify Conversion Rate\n2)Convert a value to dollars\n0)Exit\n'
choice = int(raw_input('Choice: '))
if choice == 0:
print("Thank you for converting")
break
if choice == 1:
try:
rate = float(raw_input("What is the rate that you want to use: "))
except ValueError:
rate = CONVERSION_RATE
amount = float(raw_input("How much do you want to convert: $"))
print "¥", round(amount * rate,2)
print '\n\n'
In use, it looks like this:
The currency conversion rate for Yen to 1 US Dollar is ¥97.7677 to $1
Select an option:
1)Modify Conversion Rate
2)Convert a value to dollars
0)Exit
Choice: 2
How much do you want to convert: $1.00
¥ 97.77
...
Choice: 1
What is the rate that you want to use: 96.9000
How much do you want to convert: $1.00
¥ 96.9