codeYah
codeYah

Reputation: 133

Simple Python Calculator

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

Upvotes: 2

Views: 3054

Answers (5)

sudip paudel
sudip paudel

Reputation: 1

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

Upvotes: -1

Israel Manzo
Israel Manzo

Reputation: 237

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

Upvotes: 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

Upvotes: 0

avasal
avasal

Reputation: 14854

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'>

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838216

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.

Upvotes: 1

Related Questions