Multiplication error in Python 2 - python

I can't get my head around a multiplication problem I'm having in Python 2.7. I'm sure the answer is very simple! As you can tell from the simplicity of my code I am a beginner (see below).
from __future__ import division
goAgain = 'yes'
while goAgain == 'yes':
meal = raw_input('How much did your meal cost? ')
tip = raw_input('Do you want to tip a set PRICE or a PERCENTAGE of your total bill? ').upper()
print
if tip == 'PRICE':
tip = raw_input('How much do you want to tip? ')
bill = int(meal) + int(tip)
print 'As your meal cost ' + str(meal) + ' and your tip is ' + str(tip) + ', your total bill is ' + str(bill) + '.'
elif tip == 'PERCENTAGE':
tip = raw_input('What percentage would you like to tip? ')
tip = int(tip) / 100
print 'Your tip is ' + str(tip)
bill = (int(meal) * int(tip)) + int(meal) # This is where my problem is
print 'The bill is ' + str(bill)
print 'As your meal cost ' + str(meal) + ' and you tipped ' + str(tip) + ' percent, your total bill is ' + str(bill) + '.'
else:
tip = raw_input("Sorry, I didn't catch that! Do you want to tip a set PRICE or a PERCENTAGE of your total bill? ").upper()
The issue I'm having is that the program always tells me that my total bill is the same price as the meal variable, despite (what I can see) that I'm adding the meal and the tip values together.

You divide tip by hundred, getting a number less than 1 (which is quite reasonable). Then when you are multiplying it, you cast it to an integer. (int(meal) * int(tip)) + int(meal)
If you cast a number between 0 and 1 to an int, you get zero.
Instead, if you want to cast the result to an integer, you could do this:
bill = int(int(meal)*tip) + int(meal)
or you might want to try casting to float throughout instead of int. It might give more appropriate results.

The problem (as #khelwood already pointed out) is that dividing two integers with / in Python 2 always gives an integer, so your effective tip rate is zero.
The root of the problem is that you're using Python 2. Division in Python 2 is unintuitive, but continues to work this way for reasons of backward compatibility. You can resolve it once and for all by switching to Python 3, or by adding the following at the top of your script(s):
from __future__ import division
You'll then always get a float when you use / to divide two numbers. (There's also //, which will also give you an integer result.)

Since you have used:
tip = int(tip) / 100
tip is now a float:
>>> tip = int(tip) / 100
>>> type(tip)
<type 'float'>
So when you do:
(int(meal) * int(tip)) + int(meal)
you convert your float (that is <1) to an int, so it will become 0:
>>> int(0.7)
0
So (int(meal) * int(tip)) + int(meal) is (int(meal) * 0) + int(meal) = int(meal).
In order to achieve what you want, you don't have to cast tip:
bill = (int(meal) * tip) + int(meal)
However, you could cast the result if you want:
bill = int((int(meal) * tip) + int(meal))

Related

Can't fix int and float error in economic simulator

I'm making an economic simulator type thing in python and when trying to calculate total cost when buying something i keep getting either an int error or a float error please help.
can only concatenate str (not "float") to str
import time
money = 1
moneyfo = "{:.2f}".format(money)
woodinv = 0
woodsalea = 1
woodprice = (woodsalea / 2)
woodpricefo = "{:.2f}".format(woodprice)
amntw = 0
float(amntw)
buywcost = 0
print ("Prducts are wood food and stone")
print ("Prices are wood(" + woodpricefo + ")")
bos = input("""Buy Or Sell
""")
if bos == ("Buy"):
btyp = input("""Wood, Food, Or Stone?
""")
if btyp == ("Wood"):
amntw = input("0-100")
buywcost = float(amntw) * woodprice
buywcostfo = "{:.2f}".format(buywcost)
print ("That will be" + float(buywcostfo) + "you have" + money + "would you like to buy")
It's just like the error says--you can only concatenate strings to other strings--i.e. when combining strings using the + operator, you must actually combine strings.
Here is my edited version of the code. I think you avoid the error in question, though I would also recommend making it more readable by adding comments and using more descriptive variable names.
import time
money = 1
moneyfo = "{:.2f}".format(money)
woodinv = 0
woodsalea = 1
woodprice = (woodsalea / 2)
woodpricefo = "{:.2f}".format(woodprice)
amntw = 0
float(amntw)
buywcost = 0
print ("Prducts are wood food and stone")
print ("Prices are wood(" + woodpricefo + ")")
bos = input("""Buy Or Sell""")
if bos == ("Buy"):
btyp = input("""Wood, Food, Or Stone?""")
elif btyp == ("Wood"):
amntw = input("0-100")
buywcost = float(amntw) * woodprice
buywcostfo = "{:.2f}".format(buywcost)
print ("That will be" + str(float(buywcostfo)) + "you have" + str(money) + "would you like to buy")
Your errors are here:
print ("That will be" + float(buywcostfo) + "you have" + money + "would you like to buy")
You need to convert numbers to strings before adding them to other strings:
print ("That will be" + str(float(buywcostfo)) + "you have" + str(money) + "would you like to buy")
Also, this isn't doing what you probably intend:
float(amntw)
You have to save the result of the conversion to a float - it doesn't change the number in-place:
amntw = float(amntw)
However, as you do this:
amntw = 0
float(amntw)
Assuming your intent was to make amntw the float equivalent of 0 you can simply set it directly as a float value:
amntw = 0.0
In your print statement you are casting the type to a float and so you are trying to concatenate a string and a float in 2 different places, python does not allow this.
Change this line:
print ("That will be" + float(buywcostfo) + "you have" + money + "would you like to buy")
Option 1:
print ("That will be" + buywcostfo + "you have" + str(money) + "would you like to buy")
Option 2, Python also has a feature called f strings which allow you to put variables directly inside the string:
print(f"That will be {buywcostfo} you have {money} would you like to buy")
only you have to change the last line as follows
print ("That will be " + str(float(buywcostfo)) + " you have " + str(money) + " would you like to buy")
you can choose print formattings as given here
Not sure why you're initializing variables before they're being used. That's not necessary in python.
amntw = 0 # You don't need any of this
float(amntw) # float() isn't doing anything here without assignment
buywcost = 0 # It's just making your code messy
And don't do str(float(buywcostfo)) as others are suggesting. That would be redundant. Since buywcostfo is already a string, you would be casting a string to a float and back to a string again.
buywcost = float(amntw) * woodprice # buywcost is now a float
buywcostfo = "{:.2f}".format(buywcost) # buywcostfo is a string
print("That will be" + float(buywcostfo) ...) # now it's a float again - can't add to string
You should read up on f-strings. They can make your life easier and really clean up your code a lot.
# This way unless the variables buywcostfo and moneyfo are needed elsewhere,
# they can be removed completely.
print(f"That will be {buywcost:.2f} you have {money:.2f} would you like to buy")

Python syntax errors - coin machine problem

I know these are very basic questions but cannot figure out what I'm doing wrong. I'm just beginning to learn python and don't understand why I am getting a syntax error every time I try to subtract something.
When I try to run this:
```#def variables - input cash entered and item price in float parentheses
cash = float(400)
price = float(215)
#change calculation
def cash_owed(cash - price)```
I get a
SyntaxError: invalid syntax with the ^ pointing to the - sign.
I can't find any information about why using a subtraction sign would return a syntax error in this context. What am I doing wrong?
I am trying to create a coin machine program where the cash is entered in integers representing cents (i.e $5 = 500) returns the required change in the most convenient coin denominations. This is the rest of the code that I wrote, but I can't even get past that first syntax error.
cash = float(400)
price = float(215)
#change calculation
def cash_owed(cash - price)
c = cash_owed
#display amount recieved, cost of item, required change
print ("Amount recieved : " + str(cash)) \n
print ("Cost of item : " + str(float)) \n
print("Required change : " + str(c)) \n
#calculate toonies owed
def calculate_toonies(c//200)
round(calculate_toonies)
print("Toonies x " + str(calculate_toonies))
c = c%200
#calculate loonies owed
def calculate_loonies(c//100)
round(calculate_loonies)
print("Loonies x " + str(calculate_loonies))
c = c%100
#calculate quarters owed
def calculate_quarters(c//25)
round(calculate_quarters)
print("Quarters x " + str(calculate_quarters))
c = c%25
#calculate dimes owed
def calculate_dimes(c//10)
round(calculate_dimes)
print("Dimes x " + str(calculate_dimes))
c = c%10
#calculate nickles owed
def calculate_nickles(c//5)
round(calculate_nickles)
print("Nickles x " + str(calculate_nickles))
c = c%5```
Your function definition is wrong. The parameter cannot do an operation & should contain a colon.
Change
def cash_owed(cash - price)
To
def cash_owed(cash, price):
new_price = cash - price
You have to put a colon after function
You can try this:
def cash_owed(cash, price):
return(cash - price)

Doing some coding homework for computer science but cannot for the life of me figure it out

#Alrighty lets give this a shot.
#So it no longer works and i can't figure out why....
coach = 550
entry = 30
students = 45
maxstudents = 45
discount = 0
moneydiscount = 0
cost = 0
studentcost = 0
Run = True
while Run == True:
students = int(input("Please input number of students going on the trip:"))
if students > 45 or students <=0:
print("Wrong number of students detected. Please consult your Principal or try again.")
elif students < 45:
print("Number of students =")
print(students)
print("The cost per student will be:")
ticket_cost = (students * 30)
num_free_tickets = int(students / 10)
moneydiscount = (num_free_tickets * 30)
cost = str(round(coach + ticket_cost - moneydiscount, 2))
studentcost = str(round(5 + cost / students, 2))
profit = (students * 5)
#this makes sure it is in payable amounts^
print(student_cost)
print("profit is:")
print(profit)
else:
print("This input is not numerical, please only insert numerical values")
it gives me this error:
Traceback (most recent call last):
File "C:\Users\littl\Desktop\Folders\Home-Ed Work\Computer Science\Python Homework Post- Summer\06-11-17\Students.py", line 28, in
studentcost = str(round(5 + cost / students, 2))
TypeError: unsupported operand type(s) for /: 'str' and 'int'
so i know its to do with:
studentcost = str(round(5 + cost / students, 2))
but because the line above is near identical and works im at a loss...
try using int() around cost and students. For example int(cost). The problem is that students and cost are of type string, which is incompatible with an int without a cast.
str() creates a text string, you cannot do math operations on that. You need for example an integer type. In your case you already have that:
cost = round(coach + ticket_cost - moneydiscount, 2)
studentcost = round(5 + cost / students, 2)
If you have text containing a number you can convert it:
some_value = int("1")
High Level Answer: This is a type problem that can be solved by casting a variable to an int or float that can be used in math.
Since this is homework im not going to just hand you the answer. But I found two problems. First try adding a type print statement.
cost = str(round(coach + ticket_cost - moneydiscount, 2))
print("student: ", type(students))
print("cost:", type(cost))
student_cost = str(round(5 + (cost) / students, 2))
1) That should reveal where your problem is (it did for me). You will need to add 3 little letters somewhere.
2) 2nd after you fix that you might want to check all your variable names for consistency. You will notice the error after you fix your line 28 problem. Try and digest the error you got.
unsupported operand type(s) for /: 'str' and 'int'
the / (divide) operand/operation doesn't work between a string and an int...Now look at the print debug statements. Let me know if you need additional help.
Yes Python is dynamic and it does its best in order to convert int to float or int to long on the fly, but when you are adding str to int ("1" + 2), there is no way to tell if you want the output to be string "12" or int 3,
so the intentional decision was made to raise an exception in such case.
In your code you don't need to convert every intermediate result to str. Just print it at the end as is..
This works:
coach = 550
entry = 30
students = 45
maxstudents = 45
discount = 0
moneydiscount = 0
cost = 0
studentcost = 0
Run = True
while Run == True:
students = int(input("Please input number of students going on the trip:"))
if students > 45 or students <=0:
print("Wrong number of students detected. Please consult your Principal or try again.")
elif students < 45:
print("Number of students =")
print(students)
print("The cost per student will be:")
ticket_cost = (students * 30)
num_free_tickets = int(students / 10)
moneydiscount = (num_free_tickets * 30)
cost = str(round(coach + ticket_cost - moneydiscount, 2))
studentcost = round(5 + float(cost)/float(students), 2)
profit = (students * 5)
#this makes sure it is in payable amounts^
print(studentcost)
print("profit is:")
print(profit)
else:
print("This input is not numerical, please only insert numerical values")

Coin Change Maker Python Program

I am in a beginner programming course. We must do an exercise where we make a change maker program. The input has to be between 0-99 and must be represented in quarters, dimes, nickles, and pennies when the input is divided down between the four. I wrote a code that involved loops and whiles, but he wants something more easy and a smaller code. He gave me this as a way of helping me along:
c=int(input('Please enter an amount between 0-99:'))
print(c//25)
print(c%25)
He told us that this was basically all we needed and just needed to add in the dimes, nickles, and pennies. I try it multiple ways with the dimes, nickles, and pennies, but I cannot get the output right. Whenever I enter '99', I get 3 for quarters, 2 for dimes, 1 for nickles, and 0 for pennies. If anyone would be able to help me, that would be wonderful!
I'm now sure about what you want to achieve. Using the modulo operator you could easily find out how many quarters, dimes, nickles and pennies.
Let's just say you input 99.
c=int(input('Please enter an amount between 0-99:'))
print(c//25, "quarters")
c = c%25
print(c//10, "dimes")
c = c%10
print(c//5, "nickles")
c = c%5
print(c//1, "pennies")
this would print out:
3 quarters
2 dimes
0 nickles
4 pennies
n = int(input("Enter a number between 0-99"))
q = n // 25
n %= 25
d = n // 10
n %= 10
ni = n // 5
n %= 5
c = n % 5
print(str(q) +" " + str(d) +" " + str(ni) + " " + str(c))
I hope this helps? Something like this but don't just copy it. Everytime you divide by 25 10 5 you must lose that part because it's already counted.At the end print what ever you want :).
The actual trick is knowing that because each coin is worth at least twice of the next smaller denomination, you can use a greedy algorithm. The rest is just implementation detail.
Here's a slightly DRY'er (but possibly, uh, more confusing) implementation. All I'm really doing differently is using a list to store my results, and taking advantage of tuple unpacking and divmod. Also, this is a little easier to extend in the future: All I need to do to support $1 bills is to change coins to [100, 25, 10, 5, 1]. And so on.
coins = [25,10,5,1] #values of possible coins, in descending order
results = [0]*len(coins) #doing this and not appends to make tuple unpacking work
initial_change = int(input('Change to make: ')) #use raw_input for python2
remaining_change = initial_change
for index, coin in enumerate(coins):
results[index], remaining_change = divmod(remaining_change, coin)
print("In order to make change for %d cents:" % initial_change)
for amount, coin in zip(results, coins):
print(" %d %d cent piece(s)" % (amount, coin))
Gives you:
Change to make: 99
In order to make change for 99 cents:
3 25 cent piece(s)
2 10 cent piece(s)
0 5 cent piece(s)
4 1 cent piece(s)
"""
Change Machine - Made by A.S Gallery
This program shows the use of modulus and integral division to find the quarters, nickels, dimes, pennies of the user change !!
Have Fun Exploring !!!
"""
#def variables
user_amount = float(input("Enter the amount paid : "))
user_price = float(input("Enter the price : "))
# What is the change ?? (change calculation)
user_owe = user_amount - user_price
u = float(user_owe)
print "Change owed : " + str(u)
"""
Calculation Program (the real change machine !!)
"""
# Variables for Calculating Each Coin !!
calculate_quarters = u//.25
# Using the built-in round function in Python !!
round(calculate_quarters)
print "Quarters : " + str(calculate_quarters)
u = u%0.25
calculate_dime = u//.10
round(calculate_dime)
print "Dime : " + str(calculate_dime)
u = u%0.10
calculate_nickels = u//.05
round(calculate_nickels)
print "Nickels : " + str(calculate_nickels)
u = u%0.5
calculate_pennies = u//.01
round(calculate_pennies)
print "Pennies : " + str(calculate_pennies
Code for the change machine works 100%, its for CodeHs Python
This is probably one of the easier ways to approach this, however, it can also
be done with less repetition with a while loop
cents = int(input("Input how much money (in cents) you have, and I will tell
you how much that is is quarters, dimes, nickels, and pennies. "))
quarters = cents//25
quarters_2 = quarters*25
dime = (cents-quarters_2)//10
dime_2 = dime*10
nickels = (cents-dime_2-quarters_2)//5
nickels_2 = nickels*5
pennies = (cents-dime_2-quarters_2-nickels_2)

Shoe size converter function

I am trying to make a shoe size converter function. But this program prints weird things like:
"You need function shoe_size at 0x030236F0> sized shoes"
What do I have to do? Here is my code:
def shoe_size(foot_size):
shoe_size = (foot_size + 1,5) * 3 / 2
return shoe_size
foot_size = (input("Enter your foot size: "))
print ("You need " + str(shoe_size) + " sized shoes")
There are a few errors or at least potential errors here check the changes I made to the input statement and you usually don't want a variable that is the same name as the function it is in so:
def shoe_size(given_size):
#foot_size = (foot_size + 1,5) * 3 / 2 #This multiples a tuple (, as .)
return (given_size + 1.5) * 3 / 2 #returning float (1.5 makes float)
foot_size = int(input("Enter your foot size: "))
#figured you wanted a type cast here: used int just change to float if halfs wanted
print ("You need " + str(shoe_size(foot_size)) + " sized shoes")
#this converts and prints the size: Your original was treating the function as a variable
You need to give the foot_size variable to your shoe_size method in your print statement:str(show_size(foot_size))
def shoe_size(foot_size):
shoe_size = (foot_size + 1.5) * 3 / 2
return shoe_size
foot_size = (input("Enter your foot size: "))
print ("You need " + shoe_size(foot_size) + " sized shoes")
This is the corrected script:
def shoe_size(foot_size):
shoe_size = (foot_size + 1.5) * 3 / 2
return shoe_size
foot_size = (input("Enter your foot size: "))
print ("You need " + str(shoe_size(foot_size)) + " sized shoes")

Categories