I would like to know how to break a loop as soon as its condition breaks.Its a little difficult to explain I will attach some code that will explain it well.I think I have to use things like break and continue but I am not sure where in my code should I place or maybe I need to do something else.your help would be greatly appreciated.
while 1:
if image1 appears on screen:
# do some task(it includes multiple if statements in it too)
else:
#do task 1
#do task 2
#do task 3
I want as soon as image1 appears on screen else loop should exit even if it's incomplete.like if image1 appears when else loop is doing task 2 it should exit without completing it and move to the if loop.
with my current code if image1 appears on screen the else loop only exits when all 3 tasks are done.
I want to exit the else loop not the if loop and
by exit or break I mean shift from else loop to if loop
You can use a return, like this:
if image1 appears on screen:
#do some task**
return
else:
press arrow key up for 2secs**
press arrow down key for 2sec**
UPD
I suggest this code is a part of some function.
Otherwise you will have to put it inside some function since return can be called from inside a function only.
It is also a good practice to define and use functions.
If image1 appears on screen, the else part will not execute (that's how if-else functionality works).
You can just add "break" in the end of the if (before the else)
if image1 appears on screen:
do some task**
break
else:
press arrow key up for 2secs**
press arrow down key for 2sec**
Use break where you want to stop the loop -
if image1 appears on screen:
#do some task**
break
else:
press arrow key up for 2secs**
press arrow down key for 2sec**
You can also check this
Use a break in if condition
#loop
if image1 appears on screen:
do some task**
break # this will break the loop at running iteration
else:
press arrow key up for 2secs**
press arrow down key for 2sec**
#loop
Related
I am trying to automate android game using python but I end up in a situation where I have to keep pressing CTRL key and use mouse wheel to zoom out.
I installed Pynput and tried this command
keyboard.press('a')
time.sleep(3)
keyboard.release('a')
But it doesn't keep pressing a key for 3 seconds but press only once.
Can anyone pls tell me a simple script, where it will keep pressing CTRL key and use mouse wheel to zoom out?
I'm assuming you want the key to be pressed over and over again rather than being held down (which is what I think your code above is doing).
You got two options that I know of. The easiest, by far, is to use floats alongside sleep, and do something like this:
timer = 0
while timer < 3:
time.sleep(0.1)
timer += 0.1
keyboard.press('a')
This will press the 'a' key every 0.1 seconds until 3 seconds is reached.
Otherwise, you could import the 'threading' module which lets you run code in paralel, and therefore run a loop and a timer simultaneously. This is probably a huge can of worms for what you're trying to do. The code below presses the 'a' key as fast as possible until the three second timer ends, it doesn't exit threads or anything though, which is why this is probably a bad approach:
global_timer = 0
def keep_pressing_a():
while global_timer <= 3:
keyboard.press('a')
def count_to_three():
global global_timer
keep_counting = True
while keep_counting:
time.sleep(1)
global_timer += 1
if global_timer >= 3:
keep_counting = False
threading.Thread(target=count_to_three).start()
threading.Thread(target=something).start()
I'm currently working on a school project and I'm stuck with this problem.
The problem is in this line of code:
if pressed[pygame.K_SPACE]:
a = 1
while a == 1:
gameDisplay.blit(bulletIMG, (x,y))
I know what that problem is, the loop will go on forever.
Is there a way to break out of this loop? or should I try a different approach.
If I understand you correctly, you want to have the user press a button and an image displays permanently:
display_image = False
while game_running:
if pressed[pygame.K_SPACE]:
display_image = True
if display_image:
gameDisplay.blit(bulletIMG, (x,y))
now the image will always be displayed because the flag will always be true once the user hits the space bar (the key is bringing the flag outside the game loop).
I'm playing around trying to emulate some Ctrl-P-like behaviour in Vim. What I have so far:
User calls my function.
A window is opened with a list of items in it.
A prompt is displayed under the list of items.
I want the user to be able to use the up and down arrows to select from the items but without leaving the prompt (in which they can also type).
I have got 1-3 mostly under control but am struggling with #4. I have got as far as this:
python << EOF
import vim
def MyWindow():
# Create a new window at the bottom
vim.command("below new")
vim.current.buffer.append("123")
vim.current.buffer.append("234")
vim.current.buffer.append("345")
vim.command("redraw")
vim.command("setl cursorline")
vim.command("echon '>> ' | echoh None")
while True:
vim.command("let x = getchar()")
character_code = vim.eval("x")
if character_code == "13":
# Exit by pressing Enter
break
elif character_code == "\x80kd": # Down
vim.command("keepj norm! j")
vim.command("redraw")
EOF
command! MyWindow python MyWindow()
Now the first down arrow keypress works perfectly, but subsequent down arrow kepresses don't, even though the code in the "if down key pressed" case is executed. Any ideas?
I just realised I can make it work by doing this:
elif character_code == "\x80kd": # Down
vim.command("keepj norm! j")
vim.command("setl cursorline") # <-- This fixed it
vim.command("redraw")
But I have no idea why or if this is a sensible thing to do.
envface1=pygame.image.load(p1)
envface2=pygame.image.load(p2)
envface1=pygame.transform.scale(envface1,(768,400))
envface2=pygame.transform.scale(envface2,(768,400))
start = timeit.default_timer()
window.blit(txt[0],(0,0))
window.blit(envface1,(0,400))
window.blit(envface2,(800,400))
pygame.display.flip()
display=False
while not display:
#delete the print will make it no responding
print
keys=pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
display=True
print "1"
if keys[pygame.K_RIGHT]:
display=True
print "2"
end=timeit.default_timer()
print end-start
pygame.quit()
For this part of code, I am trying to make something that user can choose the picture they like and print the result out. But in the while loop, when I delete the line with "print" only and run it, the program will down and make it no responding. Why would this happen?
As Cyber explained, you have a while loop that runs while display is false. However, since you don't modify display at all inside the loop, you've effectively created an infinite loop.
Your observation that the program will not respond is caused by the fact that nothing happens in the infinite loop unless a key is pressed.
I'm using the Graphics and Myro packages in the Calico IDE, can anyone figure a way for me to hit the 'q' key and have the program terminate? Currently when I hit the 'q' key I have to click the mouse on my window to terminate.
def main():
win = Window(800,500)
bg = Picture("http://www.libremap.org/data/boundary/united_states/contig_us_utm_zone_14_600px.png")
bg.draw(win)
while True:
char = win.getKeyPressed()
if char == 'q':
win.close()
break
x, y = win.getMouse()
MPO = Rectangle(Point(x,y), Point(x+10,y+10))
MPO.fill = Color("white")
MPO.draw(win)
I've never heard of Calico before, but from 5 seconds looking at the docs, I see this:
getMouse() - waits until user clicks and returns (x, y) of location in window
So, I'm willing to bet this is why you have to click on your window before hitting the Q key has any effect—because you're program is stuck waiting inside the getMouse() call, just as the docs say it should be.
Even if the docs didn't explain this, you could probably figure it out pretty quickly by adding some printing/logging and/or running in a debugger, to see where it's bogged down when it's not responding to your keypresses.
For example, the quick&dirty way to do this:
while True:
print 'Before getKeyPressed'
char = win.getKeyPressed()
print 'After getKeyPressed, got', char
if char == 'q':
print 'About to close because of q'
win.close()
print 'Closed'
break
print 'Before getMouse'
x, y = win.getMouse()
print 'After getMouse, got', x, y
… and so on.
Of course in real life, you don't want to add a print statement for every single line of code. (And, when you do want that, you want a smarter way of instrumenting than manually writing all those lines.) But you can add a few to narrow it down to the general area, then zoom in and add a few more within that area, and so on, until you find the culprit.
Meanwhile, if you change your code to use getMouseNow() instead of getMouse(), that will solve the problem, but only by busy-looping and redrawing the window over and over as fast as possible, whether or not you've done anything.
What you really need here—as for any GUI app—is an event loop. I can see that there are functions called onMouseDown and onKeyPress, which looks like exactly what you need here.