2

嗨,我是 python 新手,我正在通过制作一个简单的计算器来练习。该程序允许我输入膳食、税收和小费的数值,但在计算时出现此错误:

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

4 回答 4

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

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

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

我建议您不要为此使用浮点数,因为它会产生舍入错误。

于 2012-12-20T10:41:50.210 回答
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'>
于 2012-12-20T10:42:02.853 回答
0

在 python 中,输入默认是一个字符串。在相乘之前,您必须将其转换为整数。

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

应该做的伎俩。

将字符串解析为浮点数或整数

于 2012-12-20T10:44:15.840 回答
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
于 2018-12-30T04:15:19.030 回答