Skip to content Skip to sidebar Skip to footer

Using Or In Python For A Yes/no?

I'm wanting to have a 'y/n' in Python, which i've successfully done, but I want the user to be able to input a 'y' or a 'Y' and it accepts both. Here's a short if statement if yn =

Solution 1:

You're looking for

if yn in("y", "Y"):

Or better:

if yn.lower() == 'y':

Solution 2:

choose:

if yn in ["y","Y"]:
    breakif yn.lower() == "y":
    break

Solution 3:

It is or as in

if yn == 'y' or yn == 'Y':.

Although a better method would be

if yn in ['y', 'Y']:

or

if yn.lower() == 'y':.

Solution 4:

if yn in"yY":

is more succinct than

if yn in ['y', 'Y']:

or similar statements. It works because a string is a sequence in Python, just like a list or tuple.

It would evaluate to True if the user enters literally "yY", though.

Post a Comment for "Using Or In Python For A Yes/no?"