试图在python中递增1,但在连接str和int时出错

2024-09-30 18:29:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在每次单击时将订单号增加1,并声明订单=1,然后是一个全局变量。我一直得到一个错误:TypeError:只能将str(而不是“int”)连接到str,无法找出原因。这是我所指部分的代码:

for order in prodplan:
    order += 1

有什么想法吗?谢谢


Tags: 代码in订单声明for错误order原因
1条回答
网友
1楼 · 发布于 2024-09-30 18:29:28

and declared order=1 and then a global variable

这意味着您已将顺序声明为整数,如果我错了,请纠正我;我想你做过类似的事情

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

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

相关问题 更多 >