'Type error in this code for my ingredient multiplier

This is a picture of the error I'm getting when running the code:

image

I can't figure out what it thinks is wrong. I assume it has something to do with the way I used float, but I don't know how to fix it.

Link to code

#ask the user the name of their ingredients
ingname1 = input('Enter ingredient 1: ')
amount1 = float(input('Ounces of ' + ingname1 + '(to the nearest 0.1 ounce): '))
ingname2 = input('Enter ingredient 2: ')
amount2 = float(input('Ounces of ' + ingname2 + '(to the nearest 0.1 ounce): '))
ingname3 = input('Enter ingredient 3: ')
amount3 = float(input('Ounces of ' + ingname3 + '(to the nearest 0.1 ounce): '))
#ask the user how many ounces of each ingredient they need
servings = int(input('Number of servings: '))
print('To make your salad you will need: ')
ounces1 = amount1 * servings
ounces2 = amount2 * servings
ounces3 = amount3 * servings
# print total amount of ingredient in ounces needed for the given amount of servings
print(str(ounces1) + ' ounces of ' + ingname1 + ',')
print(str(ounces2) + ' ounces of ' + ingname2 + ',')
print(str(ounces3) + ' ounces of ' + ingname3 + '.')


Solution 1:[1]

You cannot concatenate strings with floats. Try converting ounces to a string before concatenating them. Use this:

#ask the user the name of their ingredients
ingname1 = input('Enter ingredient 1: ')
amount1 = float(input('Ounces of ' + ingname1 + '(to the nearest 0.1 ounce): '))
ingname2 = input('Enter ingredient 2: ')
amount2 = float(input('Ounces of ' + ingname2 + '(to the nearest 0.1 ounce): '))
ingname3 = input('Enter ingredient 3: ')
amount3 = float(input('Ounces of ' + ingname3 + '(to the nearest 0.1 ounce): '))
#ask the user how many ounces of each ingredient they need
servings = int(input('Number of servings: '))
print('To make your salad you will need: ')
ounces1 = amount1 * servings
ounces2 = amount2 * servings
ounces3 = amount3 * servings
# print total amount of ingredient in ounces needed for the given amount of servings
print(str(ounces1) + 'ounces of' + ingname1 + ',') # use str() here
print(str(ounces2) + 'ounces of' + ingname2 + ',')# use str() here
print(str(ounces3) + 'ounces of' + ingname3 + ',')# use str() here

Solution 2:[2]

This is due to how you are formatting the strings. Python supports multiple ways of formatting

f"string"
"string {}" % value
"string".format()

and for print() only you can use commas instead see: https://docs.python.org/3/tutorial/inputoutput.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abhyuday Vaish
Solution 2 bfvtv vxyfbd