Search code examples
trafficlight

Traffic light program using while loop in python


I am trying to run this code in python and I want the code to stop looping when the user enters 30, here I have used break to stop the loop, is there any other way? Any suggestion would be helpful.

`x = input("Enter value: ")
stop_light = int(x)
while True:
    if stop_light >= 1 and stop_light < 10:
        print('Green light')
        stop_light += 1
    elif stop_light < 20:
        print('Yellow light')
        stop_light += 1
    elif stop_light < 30:
        print("Red light")
        stop_light += 1
    else:
        stop_light = 0
    break`

Solution

  • Hm I'm not quite sure what you actually want to achieve. Your version does not loop since the break statement will always be met after the first iteration. Additionally, you only ask for user input once before the loop actually starts.

    Here is what I suppose you want to do, so I moved the user input part inside the loop and added the break condition to the pythonic "switch" statement. This will just ask the user for input for as long as he doesn't enter 30.

    while True:
        x = input("Enter value: ")
        stop_light = int(x)
        if stop_light == 30:
            break
        elif stop_light >= 1 and stop_light < 10:
            print('Green light')
            stop_light += 1
        elif stop_light < 20:
            print('Yellow light')
            stop_light += 1
        elif stop_light < 30:
            print("Red light")
            stop_light += 1
        else:
            stop_light = 0