Home > Mobile >  How to keep checking for correct input in a loop
How to keep checking for correct input in a loop

Time:07-29

I am trying to make a def that draws squares and I want it To check after every square if there is any input and if the input equals the word flower. If it does, I want it to stop running the def, but if it doesn't I want it to keep on going. In the code you can see what I have now.

def drawImage(width, height, img_rgb, pixel_lenght, x, y, lvl, answer):
    start(width, height)
    for i in range(int(height/pixel_lenght)):
        for j in range(int(width/pixel_lenght)):
            c = random.randint(1, lvl)
            if c == 1:
                t.color(getPixelColor(x, y, img_rgb))
                pixel(pixel_lenght)
            t.penup()
            t.forward(pixel_lenght)
            t.pendown()
            x  = 1
            ### What I have for the check is in the following three lines ###
            if input == 'flower':
                print('great')
                return
        nextRow(pixel_lenght, width)
        x = 0
        y  = 1

If you think to have a solution please submit it, I would really appreciate it.

CodePudding user response:

You need to check for input in a separate thread and then you can simply set a flag to stop the other function:

import threading

running = True


def check_input():
    global running
    while running:
        user_input = input()
        if user_input == "flower":
            running = False


threading.Thread(target=check_input).start()


def draw_image(...):
    for ...
        for ...
            ...
            if not running:
                return
            

draw_image(...)

Also, following PEP8 variable and function names should be in snake_case

  • Related