python – How to check multiple values ​​of a variable with an if statement?

Question:

Hey! I'm working on a big project. But let me explain my question with another example…

Let's say I need to create a program that only knows how to lose its temper)

But the user can write the word "exit" in different ways, for example, "EXIT", "VYHOD", "Exit", "exit" or "ds[jl" (in the 'Latin' layout), etc.

Then the code would look something like this

vyhod = input('Введите слово "выход" для выхода из программы:')
if vyhod == 'выход':
    exit(0)
if vyhod == 'Выход':
    exit(0)
if vyhod == 'ВЫХОД':
    exit(0)

etc…

So here's how you can cut it all down. For example, I tried to do this:

if vyhod == "выход", "Выход", "ВЫХОД":
    exit(0)

so

if vyhod == "выход"; "Выход"; "ВЫХОД":
        exit(0)

but this is invalid syntax)

Answer:

It is possible like this:

if vyhod in ["выход", "Выход", "ВЫХОД"]:
    exit(0)

But in general, it's better to lowercase the string and check only 1:

if vyhod.lower() == "выход":
    exit(0)
Scroll to Top