首页 > 解决方案 > 为什么,只要if子句成立,值就变了;如果在python中,值超出条件时将重新归零

问题描述

我希望每次调用对象函数时,将 s 的值添​​加到一个单元中,但是在这段代码中,只要添加了一个单元,它的值就会重置为零,并且只要条件成立它的值变为 1,退出时它的值为零,而我希望每次设置 if 子句时,将 s 添加到 1,例如 1、2 和 ..

 def objects(x,y,startx,starty,startw,starth,objectw,action=None):
  s=0
  if y < starty + starth :
      if x <= startx + startw and x + objectw > startx + startw  or x + objectw == startx + startw or x + objectw >= startx and x<= startx or x > startx and x + objectw < startx + startw:
  s+ =1

标签: python-3.x

解决方案


我不确定我是否理解,但请尝试在函数范围之外定义变量 s。就像现在一样,每次调用 objects() 函数时,它首先将 s 重新定义为 0。

s = 0
def objects(x,y,startx,starty,startw,starth,objectw,action=None):
  if y < starty + starth :
      if x <= startx + startw and x + objectw > startx + startw  or x + objectw == startx + startw or x + objectw >= startx and x<= startx or x > startx and x + objectw < startx + startw:
  s+=1

推荐阅读