首页 > 解决方案 > 在列表程序中,打印语句没有正确连接为浮点数

问题描述

下面是我的代码,但我无法打印最后几行。我试过重新排列它们,从字符串切换到浮点数等。我不知道这只是一个小故障还是一个连接问题。如果是这样,我将如何使最后几行用浮点数打印?

N = []
C= []
Holiday = []
totC = 0
name = input("enter name").upper()
while name != "XXX":
    cost = int(input("enter amount to spend >0 and <=10"))
    while cost <=0 or cost >10:
        print("invalid cost")
        cost = int(input("enter amount to spend >0 and <=10"))
    gift = name + " " + str(cost)
    N.append(name)
    C.append(cost)
    Holiday.append(gift)
    totC = totC + cost
    name = input("enter name").upper()

print(Holiday)
print(N)
print(C)
print(totC)
print("Total cost is "  + totC)
print("Average cost is" + av)
print("Number of names is " + len(N))
print("Number of costs is " + len(C))

标签: python

解决方案


忘记将所有这些值转换为字符串。你不需要这样做。print相反,请将您的陈述写成:

print("Total cost is", totC)
print("Average cost is", av)
print("Number of names is", len(N))
print("Number of costs is", len(C))

或者,如果您使用的是 Python 3.6 或更新版本,您可以使用f-strings,例如:

print(f"Total cost is {totC}")
print(f"Average cost is {av}")
print(f"Number of names is {len(N)}")
print(f"Number of costs is {len(C)}")

推荐阅读