简单的Python计算器

时间:2012-12-20 10:40:26

标签: python python-2.7

嗨,我是蟒蛇新手,我正在练习一个简单的计算器。 该程序允许我输入膳食,税和小费的数值,但在进行计算时我得到这个错误:

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'

代码是:

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

4 个答案:

答案 0 :(得分:1)

您需要将输入从字符串转换为数字,例如整数:

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 #: '))

如果您需要输入小数货币金额,也可以使用decimal类型。

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 #: '))

我建议你不要使用浮动因为它会产生舍入错误。

答案 1 :(得分:1)

当您使用raw_input时,您获得的输入类型为str

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

在执行操作之前,您应将其转换为int / float

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

答案 2 :(得分:0)

默认情况下,输入是python中的字符串。在乘法之前,您必须将其转换为整数。

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

应该这样做。

Parse String to Float or Int

答案 3 :(得分:0)

这很简单,我还根据用户操作数输入为字符串编写了此代码。

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