A better way to check inputs

Hi,

So I find that checking user input with multiple if-statements like so is very annoying, ugly, and there seems like a better alternative.

import os

user_input = input(">> ")

if user_input == "clear":
    os.system("clear")
elif user_input == "hello":
    print("hi!")
else:
    print("Option not found")

This can be mitigated by using functions, but is there a way to completely wipe out the if-statements in the first place?

There’s probably a way to do this using classes and methods, but I don’t often use them because I am never sure I’m using them how they’re actually supposed to be used.

Thanks!

IIRC, python has case statements now, but other than that, you could do this:

import os

def clear():
  os.system("clear")

def hello():
  print("hi!")

options = {"clear": clear, "hello": hello}

user_input = input(">> ")

if user_input in options.keys():
  options[user_input]()
else:
  print("Option not found")

There’s probably a better way than this though.

3 Likes

I think I remember seeing this a couple months ago. This is a huge improvement though, so I’ll probably try this out. Thank you!

Match/case I guess:

user_input = input(">> ")

match user_input:
    case "clear":
        # Using a print statement because it's faster
        print("\033c", end="", flush=True)
    case "hello":
        print("hi!")
    case _:
        print("Option not found")
1 Like

Wait, this is a Python feature now? I think I’ll research this a bit more. Thanks for the reply!

Currently the line options[user_input] only returns the function object.

You need to call the function like this:

options[user_input]()

Looks weird but works

2 Likes

Yep I forgot about that, let me fix that.

Edit: fixed now, can’t believe I forgot that.

1 Like

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