Andre
Andre

Reputation: 1661

Better way, of writing a Long "if" statements?

Hello this might be a very basic question, but because I am new to programming and python and I really want to learn, am asking.

I am making a program that takes input from the user, of the "Playing Card" Suit he has. And the program only accepts the correct suit.

For example;

Diamonds, Hearts, Clubs, Spades

if the user enters anything else, such as "Triangles" the program returns "Wrong input".

This is what I have got so far:

if suit == "Diamonds":
    return "Accepted"
if suit == "Hearts":
    return "Accepted"
if suit == "Clubs":
    return "Accepted"
if suit == "Spades":
    return "Accepted"
else:
    return "Wrong input"

My question was, is there a better way to write this than going through this tedious process of making a whole new "if" statement for each Suit.

Upvotes: 5

Views: 463

Answers (4)

Padraic Cunningham
Padraic Cunningham

Reputation: 180481

if suit in ("Diamonds","Hearts","Clubs","Spades"):
    return "Accepted"
else:
    return "Wrong input"

Just use in to check for membership, if suit is not in the tuple, your else clause will be executed.

membership operators

You can also reverse the logic using not in:

if suit not in ("Diamonds","Hearts","Clubs","Spades"):
    return "Wrong input"
else:
    return "Accepted"

If you want to check for a value also:

if suit  in ("Diamonds","Hearts","Clubs","Spades") and value in ("Ace","king","Queen"....):
    return "Accepted"
else:
    return "Wrong input"

Using a set {"Diamonds","Hearts","Clubs","Spades"} is a more efficient way to check for membership

Upvotes: 7

Sylvain Leroux
Sylvain Leroux

Reputation: 52040

I don't know if this suits your needs, but sometime an alternative approach using dictionary might help with long sequences of if ... elif:

states = {"Diamonds": "accepted",
          "Hearts":   "accepted",
          "Clubs":    "accepted",
          "Spades":   "accepted"}
return states.get(suit,"wrong input")

Upvotes: 2

hlt
hlt

Reputation: 6317

You can use in to check if suit is in a list, tuple or set of accepted suits:

if suit in {"Diamonds", "Hearts", "Clubs", "Spades"}:
    return "Accepted"
else:
    return "Wrong input"

You can also use a tuple (with (...)), list ([...]) or frozenset instead of the set ({...}).

Upvotes: 8

fredtantini
fredtantini

Reputation: 16566

You can use the in operator:

accepted = ['Diamonds', 'Hearts', 'Clubs', 'Spades']
if suit in accepted:
  return "accepted"
else:
  return "wrong input"

Upvotes: 2

Related Questions