如何修复Python中有关非int和float的这个类型错误?
我正在使用Visual Studio代码上的Python 3,我正在进行的项目是在接收到用户的地球重量后计算用户的月球重量,然后在给定增加和一段时间后,输出他们的体重随时间的变化 这是我多次收到的错误消息,无论我重新编码了多少次:如何修复Python中有关非int和float的这个类型错误?,python,python-3.x,syntax,Python,Python 3.x,Syntax,我正在使用Visual Studio代码上的Python 3,我正在进行的项目是在接收到用户的地球重量后计算用户的月球重量,然后在给定增加和一段时间后,输出他们的体重随时间的变化 这是我多次收到的错误消息,无论我重新编码了多少次: TypeError: can't multiply sequence by non-int of type 'float' 每当我使用input()和/或sys.stdin.readline()函数时,就会发生这种情况,但所有相关变量都是整数或浮点数,无论我是否尝试
TypeError: can't multiply sequence by non-int of type 'float'
每当我使用input()和/或sys.stdin.readline()函数时,就会发生这种情况,但所有相关变量都是整数或浮点数,无论我是否尝试在输入周围使用float()函数将它们转换为浮点数
这是我的密码:
# this programs converts your terra weight to your lunar weight, then it takes increase over a period of time
# error whether I use float() or not
terraWeight = float(input("Terra Weight: "))
ask = input("Is this in LBS or KG? ")
# converts pounds to kilograms
# 2.204... is used to convert lbs to kgs
if ask == "lbs" or "LBS":
initial = terraWeight / 2.2046223302272
# didn't need this, but assignment error popped up
x = 0
# or replace input() with sys.stdin.readline()
increase = input("Increase: ")
period = input("Period: ")
# gets lunar weight over time
def lunarWeight():
global increase
global period
global x
global initial
print("Earth Weight = %s kgs." % terraWeight)
year = 0
lunarWeight = initial * 0.165
print("Moon Weight = %s kgs. \n" % lunarWeight)
postIncrease = lunarWeight * increase
for x in range(0, period):
year += 1
lunarWeight += postIncrease
print("Year %s = %s kgs." % (year, lunarWeight))
lunarWeight()
终端指向“我的代码”的此部分:
postIncrease = lunarWeight * increase
在第28行。我不确定问题出在哪里,我尝试过调试,但仍然收到相同的错误消息。我看到其他帖子也有同样的问题,但他们在使用列表时遇到了问题,我很确定我没有使用列表。有什么建议吗
我认为你应该这样写:
increase = float(input("Increase: "))
period = int(input("Period: "))
句点用于
范围()
中,因此它应该是整数增加
是一个字符串,如果ask==“lbs”或“lbs”,则将其转换为int或float:
将始终被视为真。它被解析为(ask==“lbs”)或“lbs”
。你应该做询问(“lbs”,“lbs”)
取而代之。@MichaelBianconi随后收到此错误消息:TypeError:'str'对象不能被解释为整数
@Tenajayong那么您将其转换错误。调试后我收到此错误消息:'float'对象不能被解释为整数
您是否同时转换了句点和递增变量?@TenajaYoung周期应该在Into,我现在有了。我将句点转换为浮点数而不是整数。谢谢