用户输入产生“不能将序列与‘float’类型的非整数相乘”

2024-09-30 07:25:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个初学者在这里以及编程的Python,我目前正在使用代码学院来帮助我学习。所以我决定冒险去做一个自己的程序,一直被错误信息困住:不能用“float”类型的非int乘以sequence

这个程序非常简单,是一个小费计算器,它要求用户输入信息,让程序确定小费的金额和账单的总额。到了数学的时候,一切都还可以。我知道这不“漂亮”,但我真的在想怎么做。任何帮助都将不胜感激!你知道吗

到目前为止,我掌握的情况如下:

print ("Restuarant Bill Calculator")
print ("Instructions: Please use only dollar amount with decimal.")

# ask the user to input the total of the bill
original = raw_input ('What was the total of your bill?:')
cost = original
print (cost)

# ask the user to put in how much tip they want to give
tip = input('How much percent of tip in decimal:')
tipamt = tip * cost      
print "%.2f" % tipamt

# doing the math
totalamt = cost + tipamt
print (totalamt)

Tags: oftheto程序inputasktotaldecimal
2条回答

你的问题是你在使用input()raw_input()混合。这是初学者常犯的错误。input()将代码作为Python表达式进行求值,并返回结果。raw_input()但是,只需获取的输入并将其作为字符串返回即可。你知道吗

所以当你这么做的时候:

tip * cost 

你真正要做的是:

2.5 * '20'

当然,这毫无意义,Python将引发一个错误:

>>>  2.5 * '20'
Traceback (most recent call last):
  File "<pyshell#108>", line 1, in <module>
    '20' * 2.5
TypeError: can't multiply sequence by non-int of type 'float'
>>> 

您需要首先使用raw_input()获得成本,然后将其转换为整数。然后使用taw_input()以字符串形式获取提示,并将输入转换为float:

#ask the user to input the total of the bill

# cast input to an integer first!
original = int(raw_input('What was the total of your bill?:'))
cost = original
print (cost)

#ask the user to put in how much tip they want to give

# cast the input to a float first!
tip = float(raw_input('How much percent of tip in decimal:'))
tipamt = tip * cost      
print "%.2f" % tipamt

#doing the math
totalamt = cost + tipamt
print (totalamt)

忘记将str转换为float:

original = raw_input('What was the total of your bill?:')
cost = float(original)
print (cost)

#ask the user to put in how much tip they want to give
tip = input('How much percent of tip in decimal:')
tipamt = tip * cost      
print("%.2f" % tipamt)

#doing the math
totalamt = cost + tipamt
print (totalamt)

相关问题 更多 >

    热门问题