【问题标题】:Trying to increment by 1 in python but getting error about concatenating str and int尝试在 python 中增加 1,但在连接 str 和 int 时出现错误
【发布时间】:2020-07-16 22:37:37
【问题描述】:

我试图将订单号每次点击增加 1,并声明 order=1,然后声明一个全局变量。我不断收到一个错误:TypeError: can only concatenate str (not "int") to str并且不知道为什么。这是我所指部分的代码:

for order in prodplan:
    order += 1

有什么想法吗?谢谢!!

【问题讨论】:

  • 你能发帖prodplan
  • prodplan 是一个空集合,我将订单的值附加到
  • 在每个 for 循环中,order 被迭代器 prodplan 的下一个值更改。所以你覆盖了全局变量order。在 for 循环中更改顺序到另一个变量,例如for x in prodplan:
  • order 似乎是一个字符串(str)。发布您的完整代码和回溯
  • 将 for 循环中的 order 变量更改为 x 有效,谢谢!!

标签: python string integer concatenation


【解决方案1】:

并声明 order=1 然后是全局变量

这意味着您已将 order 声明为整数,如果我错了,请纠正我;我假设你做过这样的事情

order=1 #global scope
prodplan=["list of string values"]
for order in prodplan: #order defined again; local scope
     order += 1  # here the order is a string value, adding with integer will cause error

由于python有全局变量作用域和局部作用域;您在两个地方声明顺序的错误会给 python 解释器造成混淆。正确的方法可能是

order=1
prodplan=["list of string values"]
for i in prodplan:
     order += 1  # here the order is a int value, adding with integer will be fine

通过这种方式,您可能可以获得所需的点击次数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    相关资源
    最近更新 更多