簡體   English   中英

如何在 Python 中修復關於非整數和浮點數的這個 TypeError?

[英]How do I fix this TypeError in Python concerning non-int and floats?

我正在Visual Studio Code上使用Python 3 ,我正在從事的項目是在接收到地球重量后計算用戶的月球重量,然后輸出他們的體重如何隨着時間的增加和一段時間的變化而變化。

這是我多次收到的錯誤消息,無論我重新編碼多少次:

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: "))


期間在range()使用,因此它應該是整數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM