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")
Related
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)
This problem I'm having is that I cant use that list I have just created and stored inside current_pizza_list.
pizza_1 = ['8.00','Pepperoni']
print('Input 1 for ', pizza_1[1])
current_pizza = input('What pizza would you like:')
current_pizza_list = ('pizza_' + str(current_pizza) + '[1]')
pizza_ammount = input('How many', str(current_pizza_list) ,' pizzas would you like:')
num = 5
pizza_name = 'pizza_' + str(num)
print('Our pizza choices are ' + pizza_name + '!')
#What you created above is a variable. That is not a list. Below is a list:
#pizzas = ['pepperoni', 'extra cheese', 'cheese', 'veggie']
current_pizza = input('What pizza would you like: ')
current_pizza_name = ('pizza_' + str(current_pizza) + '[1]')
pizza_ammount = int(input('How many ' + current_pizza_name + "'s would you like?: "))
print('You would like ' + str(pizza_ammount) + ' ' + current_pizza_name + ' pizzas!')
Here is your output:
Our pizza choices are pizza_5!
What pizza would you like: 5
How many pizza_5[1]'s would you like?: 10
You would like 10 pizza_5[1] pizzas!
Now you've stated that you want a list, but in your example there is not list, so i'm not sure what you mean, but below is an example of a list of pizzas and attaching a number to each pizza after we access it:
pizza_list = [1, 2, 3, 4, 5, 6, 7, 8]
print('Our pizza choices are: ')
for pizza in pizza_list:
print('\t' + str(pizza))
pizza_choice = int(input('Which pizza would you like to select?: '))
if pizza_choice in pizza_list:
current_pizza = 'pizza_' + str(pizza_choice)
else:
print('We do not have that pizza')
pizza_amount = int(input('How many ' + current_pizza + "'s would you like?: "))
print('You would like ' + str(pizza_amount) + ' ' + current_pizza + " pizza's.")
Above we have a list, which I do not see in your code example called pizza list. If the user selects a pizza within the list we can attach that pizza number to the end of the pizza_ string. We then ask the user how many pizza's they want. The pizza_list can server as your list. Here is the output:
Our pizza choices are:
1
2
3
4
5
6
7
8
Which pizza would you like to select?: 5
How many pizza_5's would you like?: 20
You would like 20 pizza_5 pizza's.
I'd suggest
pizza_name = 'pizza_%d' % num
Here the digit will be added to the string.(assuming num is an integer)
The same thing can be done for floats and strings as well with minor modifications:
result = 'format_string goes here: %05.2f' % 2.123
foo = 'bar_%s' % 'baz'
The one with the float probably needs a little explanation: the %05.2f means that the float will be formatted to have 5 places in total, padded with leading zeros and 2 decimal digits after the dot.
def die():
first = str(randint(1, 6))
second = str(randint(1, 6))
total = first + second
print "You have rolled a " + first + " and a " + second + ", for a total score of " + total + "."
Standard die throwing game, but I'm struggling to print the values for individual die as well as the total. Treating as a string for individual, but then sum leads to concatenation rather than actual sum.
Thanks
Keep your variables as numbers and let print do the formatting:
def die():
first = randint(1, 6)
second = randint(1, 6)
total = first + second
print "You have rolled a", first, "and a", second, ", for a total score of", total, "."
Or you could do some formatting using str.format to have more control over the default inter-parameter spacing in the above:
print "You have rolled a {} and a {}, for a \
total score of {}.".format(first, second, total)
There are two ways to address your problem (and more still!). Firstly, you need to make sure you keep your integers as type int when adding them together, and then cast them to a string when you print them out.
You can do this like the below, using the str() casting method and + concatenation.
def die1():
"""Roll and print two dice using concat."""
first = randint(1, 6) # keep these as integers
second = randint(1, 6)
total = first + second # so addition works
# but now cast to str when printing
print "You have rolled a " + str(first) + " and a " + str(second) + ", for a total score of " + str(total) + "."
But a handier way is to use the str.format() method to put placeholders in your string, and then let python cast and format the integer values for you. If you have big numbers with 4 or more digits, an advantage of this would be that you can use a string formatting code like "my big number: {0:d,}".format(1000000) to make your string output like "my big number: 1,000,000", which is much more readable.
def die2():
"""Roll and print two dice using str.format()."""
first = randint(1, 6)
second = randint(1, 6)
total = first + second
# or use the str.format() method, which does this for you
print "You have rolled a {0} and a {1}, for a total score of {3}.".format(first, second, total)
You can use casting to change the structure of the var. You can either use them as strings and for total use this line:
total = int(first) + int(second)
or use them as int and cast them to string in the print by using str(first) and str(second)
Best
print "You have rolled a " + str(first)
This would convert the int to a string, hence concatenating it.
Also, you can do
total = int(first) + int(second) to address the first issue.
You have two solutions:
Convert the numbers back to int before adding them:
def die():
first = str(randint(1, 6))
second = str(randint(1, 6))
total = str(int(first) + int(second))
print ("You have rolled a " + first + " and a " + second + ", for a total score of " + total + ".")
Convert the numbers into str before printing them:
def die():
first = randint(1, 6)
second = randint(1, 6)
total = first + second
print ("You have rolled a " + str(first) + " and a " + str(second) + ", for a total score of " + str(total) + ".")
Either solution will work perfectly fine.
This would also work. Don't convert first and second to str until after you perform sum on them. Then remember to cast them as str in your print statement.
def die():
first = randint(1, 6)
second = randint(1, 6)
total = str(first + second)
print ("You have rolled a " + str(first) + " and a " + str(second) + ", for a total score of " + total + ".")
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")
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))