2

Hi I am new to python and I am practicing by making a simple calculator. The program lets me input numerical values for meal, tax, and tip but when doing the calculation I get this error:

Traceback (most recent call last):
  File "C:/Users/chacha04231991/Desktop/pytuts/mealcost.py", line 5, in <module>
    meal = meal + meal * tax
TypeError: can't multiply sequence by non-int of type 'str'

The is the code:

meal = raw_input('Enter meal cost: ')
tax = raw_input('Enter tax price in decimal #: ')
tip = raw_input('Enter tip amount in decimal #: ')

meal = meal + meal * tax
meal = meal + meal * tip

total = meal
print 'your meal total is ', total
avasal
  • 14,350
  • 4
  • 31
  • 47
codeYah
  • 133
  • 1
  • 2
  • 5

5 Answers5

1

You need to convert your inputs from strings to numbers, e.g. integers:

meal = int(raw_input('Enter meal cost: '))
tax = int(raw_input('Enter tax price in decimal #: '))
tip = int(raw_input('Enter tip amount in decimal #: '))

You could also use the decimal type if you need to enter fractional monetary amounts.

from decimal import Decimal 
meal = Decimal(raw_input('Enter meal cost: '))
tax = Decimal(raw_input('Enter tax price in decimal #: '))
tip = Decimal(raw_input('Enter tip amount in decimal #: '))

I would advise you not to use floats for this because it will give rounding errors.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • It works fine using float but when I try decimal is gives this error: Traceback (most recent call last): File "C:/Users/chacha04231991/Desktop/pytuts/mealcost.py", line 4, in tax = decimal(raw_input('Enter tax price in decimal #: ')) NameError: name 'decimal' is not defined – codeYah Dec 20 '12 at 11:05
  • @codeYah: `decimal` with a small `d` is the name of the module. The type `Decimal` has a capital `D`. – Mark Byers Dec 20 '12 at 11:49
1

when you use raw_input, the input you get is of type str

>>> meal = raw_input('Enter meal cost: ')
Enter meal cost: 5
>>> type(meal)
<type 'str'>

you should convert it to int/float before performing action

>>> meal = int(raw_input('Enter meal cost: '))
Enter meal cost: 5
>>> type(meal)
<type 'int'>
avasal
  • 14,350
  • 4
  • 31
  • 47
0

Input is a string by default in python. You will have to convert it to an integer before multiplying.

int(meal)
int(tax)
int(tip)

should do the trick.

Parse String to Float or Int

Community
  • 1
  • 1
0

This is simple and also I wrote this code depending on the user operand input as string..

def calculator(a, b, operand):
    result = 0
    if operand is '+':
      result = a + b
    elif operand is '-':
      result = a - b
    elif operand is '*':
      result = a * b
    elif operand is '/':
      result = a / b
    return result

calculator(2, 3, '+')
output -> 5
Israel Manzo
  • 217
  • 3
  • 6
-1

By default, python assumes all input as string value. So we need to convert string values to numbers through either float or int.