I’m trying to check if “event” is equal to any of the possible combinations of strings

Question:
I’m trying to check if “event” is equal to any of the possible combinations of strings.
Ex. View Red Cars, View Blue Cars, View White Cars.
Below is an example of what I tried to do:

# Car.colors = [Red, Blue, White, Grey, Black]
if event == "Start":
        start()
elif event == f"View {[i for i in Car.colors]} Cars":
        view_cars()
elif event == f"Back":
        back()

From a quick look, I think this should work:

# Car.colors = [Red, Blue, White, Grey, Black]
for color in Car.colors:
        if event == f"View {color} Cars":
                run()
3 Likes

bruh you stole it ;-; lol jk, nice job

Sorry, I forgot to include that it’s an elif statement, so I can’t have a for loop in the middle of it.

Hm. How about this then?

# Car.colors = [Red, Blue, White, Grey, Black]
event_split = event.split()
if event_split[0] == "View" and event_split[1] in Car.colors and event_split[2] == "Cars":
        run()

Note that this will error if an event is shorter than 3 words.
EDIT:
New method that won’t crash on short event strings:

# Car.colors = [Red, Blue, White, Grey, Black]
event_split = event.split()
if len(event_split) == 3 and event_split[0] == "View" and event_split[1] in Car.colors and event_split[2] == "Cars":
        run()
1 Like

It still wouldn’t work because I can’t assign a variable in between elif statements.

I updated the code above to more accurately represent what i’m trying to do.

Hmm. Then this should work (Made before your update):

# Car.colors = [Red, Blue, White, Grey, Black]
if len(event.split()) == 3 and event.split()[0] == "View" and event.split()[1] in Car.colors and event.split()[2] == "Cars":
        run()
1 Like

How about this one?

# Car.colors = [Red, Blue, White, Grey, Black]
if event == "Start":
        start()
elif len(event.split()) == 3 and event.split()[0] == "View" and event.split()[1] in Car.colors and event.split()[2] == "Cars":
        run()
elif event == f"Back":
        back()
1 Like

Not the cleanest solution but it works. Thanks!

Happy to help! As for making it cleaner, I suppose you could do this:

# Car.colors = [Red, Blue, White, Grey, Black]
event_split = event.split()
if event == "Start":
        start()
elif len(event_split) == 3 and event_split[0] == "View" and event_split[1] in Car.colors and event_split[2] == "Cars":
        run()
elif event == f"Back":
        back()

Though this does require assigning the variable.

1 Like

clean?

match event.split():
    case ["Start"]:
        start()
    case ["Back"]:
        back()
    case ["View", c, "Cars"] if c in Car.colors:
        run()
2 Likes

Doesn’t quite work unfortuantly…

I had used the UK spelling (colours) and wrote view_cars instead of run. That’s all, right?

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.