这段代码中if语句哪里有问题?

这段代码中,当visits的值为1时,为啥执行的还是visits>=4的while循环函数?

这段代码中if语句哪里有问题?
这段代码中if语句哪里有问题?

代码在这儿:

i = 1

while i == 1:

printSiteInfo()

global visits

if visits == 0:

GPIO.output(R,0)

GPIO.output(Y,0)

GPIO.output(G,0)

if visits == 1:

GPIO.output(R,1)

GPIO.output(Y,0)

GPIO.output(G,0)

if visits == 2:

GPIO.output(R,1)

GPIO.output(Y,1)

GPIO.output(G,0)

if visits == 3:

GPIO.output(R,1)

GPIO.output(Y,1)

GPIO.output(G,1)

if visits >= 4:

t = 0

while(t <= visits):

GPIO.output(R,0)

GPIO.output(Y,0)

GPIO.output(G,0)

time.sleep(0.5)

GPIO.output(R,1)

GPIO.output(Y,1)

GPIO.output(G,1)

time.sleep(0.1)

t = t + 1

time.sleep(20)


回答:

代码不全,看不出问题所在。

我还想问执行了 visits >= 4 分支,那 visits == 1 分支执行了没有?

有一个简单的办法,你在前面增加加 print 语句打印 visits 的值,就能清晰的看到结果了。

i = 1

while i == 1:

printSiteInfo()

global visits

print('i=', i, 'visits=', visits, 'id(visits)', id(visits))

if visits == 0:

print('in==0', 'i=', i, 'visits=', visits, 'id(visits)', id(visits))

GPIO.output(R,0)

GPIO.output(Y,0)

GPIO.output(G,0)

if visits == 1:

print('in==1', 'i=', i, 'visits=', visits, 'id(visits)', id(visits))

GPIO.output(R,1)

GPIO.output(Y,0)

GPIO.output(G,0)

if visits == 2:

print('in==2', 'i=', i, 'visits=', visits, 'id(visits)', id(visits))

GPIO.output(R,1)

GPIO.output(Y,1)

GPIO.output(G,0)

if visits == 3:

print('in==3', 'i=', i, 'visits=', visits, 'id(visits)', id(visits))

GPIO.output(R,1)

GPIO.output(Y,1)

GPIO.output(G,1)

if visits >= 4:

print('in>=4', 'i=', i, 'visits=', visits, 'id(visits)', id(visits))

t = 0

while(t <= visits):

GPIO.output(R,0)

GPIO.output(Y,0)

GPIO.output(G,0)

time.sleep(0.5)

GPIO.output(R,1)

GPIO.output(Y,1)

GPIO.output(G,1)

time.sleep(0.1)

t = t + 1

time.sleep(20)

根据输出结果再分析


回答:

第4行代码

global visits

你使用了global 用的是上方的visits 值可能为 4

例子如下:

c = 1 # global variable

def add():

print(c)

add()

打印出来的结果是 1


回答:

continue

i = 1

while i == 1:

printSiteInfo()

global visits

if visits == 0:

# ...

continue

if visits == 1:

# ...

continue

以上是 这段代码中if语句哪里有问题? 的全部内容, 来源链接: utcz.com/p/937762.html

回到顶部