【问题标题】:TypeError, using a number to calculate in print [duplicate]TypeError,使用数字在打印中计算 [重复]
【发布时间】:2017-08-20 19:31:24
【问题描述】:

我怎样才能使这条线工作? print('州平均人口:', totalPop/50)

它不会让我,因为 50 是一个 int。

def main ():
file = open ('StateCensus2010.txt', 'r')
name = file.readline()
abb = file.readline()
pop = file.readline()
minPop = pop
minName = name
maxPop = pop
maxName = name
totalPop = pop
totalPop += pop   
for state in range (49):
    name = file.readline()
    abb = file.readline()
    pop = file.readline()
    if pop < minPop:
        minPop = pop
        minName = name
    if pop > maxPop:
        maxPop = pop
        minName = name
print(' State with MAX population:',maxName, maxPop)
print('State with MIN population:', minName, minPop)
print('Average state population:', totalPop/50)

【问题讨论】:

  • 你能展示你的完整代码吗?即什么是 totalPop?
  • 究竟是什么错误?发布完整的回溯。
  • totalPop 是一个整数时效果很好。请发布实际的错误消息,包括完整的回溯。
  • TypeError: unsupported operand type(s) for /: 'str' and 'int' 是回溯。刚刚包含完整的代码
  • pop 是一个字符串,所以totalPop 也是一个字符串。

标签: python typeerror


【解决方案1】:

您应该使用print('Average state population: {}'.format(totalPop/50))print('Average state population:', str(totalPop/50)),但最好使用第一个。这使用了string formatting,它会自动将类型转换为字符串。

【讨论】:

  • 仍然得到回溯错误 "TypeError: unsupported operand type(s) for /: 'str' and 'int'" ):
  • 那是因为totalPop 是一个字符串。在执行除法之前将其转换为 int(可能使用int)。
  • @DW42 它需要比这更早进行转换,所有代表数字的字符串也是如此。
  • 是的,我只是不知道在哪里转换它,或者是否有其他方法。
  • 你可以做类似print('Average state population: {}'.format(int(totalPop)/50))的事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 2020-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多