简体   繁体   中英

Printing strings of variables and using them in mathematical equations

I've asked a question once before and this is about the same topic. I've simplified my previous code (from the other question I asked), but I always get confused with strings, integers and floats. I'm trying to set variables in if and else statements and then use those variables in another variable to print out or I could simply print out the math itself. This is the code:

# This program asks for the size of pizza and how many toppings the customer would like and calculates the subtotal, tax and total cost of the pizza.
print ('Would you like a large or extra large pizza?')
sizeOfPizza = input()
print() # Blank space to separate text out
print ('How many toppings would you like? (1, 2, 3 or 4)')
numberOfToppings = input()
print() # Blank space to separate text out
if sizeOfPizza == 'large':
    sizeOfPizzaCost = 6
else:
    sizeOfPizzaCost = 10 
if numberOfToppings == '1':
    numberOfToppingsCost = 1
elif numberOfToppings == '2':
    numberOfToppingsCost = 1.75
elif numberOfToppings == '3':
    numberOfToppingsCost = 2.50
elif numberOfToppings == '4':
    numberOfToppingsCost = 3.35
subtotal = (sizeOfPizzaCost) + (numberOfToppingsCost)
finalCost = (subtotal) * 1.13
print("The subtotal is $ " + str(subtotal))
print('Tax is 13%')
print('The total cost is $ ' str(finalCost))
input()

I just don't understand how to apply math with the variables and print them because I keep getting a syntax error whether I add (float(my_var) or like (int(my_var). It would be a lot easier to instead of making variables and calling them, I'd just print out the math within the print() function.

Sorry if the solution is quite simple. I'm still new to Python (v3.5.0) and I don't use it that often.

Thanks :)

You can also use the string .format method. This way you don't need to cast the float/int/etc as str .

Instead of:

print("The subtotal is $ " + str(subtotal))
print('Tax is 13%')
print('The total cost is $ ' + str(finalCost))

Do this:

print('The subtotal is $ {}'.format(subtotal))
print('Tax is 13%')
print('The total cost is $ {}'.format(round(finalCost,2))

You can chain these together, so something like this is possible:

print("""
      The subtotal is $ {} which is based on a {} 
      pizza with a base price of {} and {} toppings x {}.
      Adding 13% tax for a total of {}.
      """.format(subtotal, sizeOfPizza, sizeOfPizzaCost, numberOfToppings, numberOfToppingsCost, finalCost))

You have a syntax error in your code. Your line here:

print('The total cost is $ ' str(finalCost))

Is missing the '+'. It should be this:

print('The total cost is $ ' + str(finalCost))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM