'Adding to a value in a loop counter in Python
I’m trying to get it add 1 to streak every time the loop runs, but it keeps the same number. I’m trying to make a counter every time it sees red.
from time import sleep
import pyautogui
streak = 0
r = 1
def color():
pix = pyautogui.pixel(500, 285)
red = pix[0]
print (red)
if red == 222:
x = streak + r
print (x)
while True:
color()
sleep(5)
Solution 1:[1]
This code allows you to know how many times you have seen red.
from time import sleep
import pyautogui
r = 0
def color():
global r
pix = pyautogui.pixel(950, 540)
color_var = pix[0]
print(color_var)
if color_var > 222:
r += 1
if r > 1:
print(f"I have seen red {r} times")
else:
print(f"I have seen red {r} time")
while True:
color()
sleep(1)
Solution 2:[2]
your problem is easy you need add 1 to streak inside the if, instead you are creating a new var and adding the value in it you never change the streak init value
this line x = streak + r
should be like this streak = streak + r
Solution 3:[3]
the most simple way is to use :
number += othernumber
example :
number += 1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Peter Mortensen |
Solution 2 | WhiteAB |
Solution 3 | sigmarule69 |