Is it best to write long if statements?

Hello, this may be a very simple question, but since I'm new to programming and python, and I really want to find out, I ask.

I am making a program that takes input from a user from his "Playing Card". And the program accepts only the right lawsuit.

For instance:

Diamonds, hearts, clubs, spades

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

This is what I 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 whether there is a better way to write this than to go through this tedious process of creating a completely new β€œif” statement for each costume.

+5
source share
4 answers
 if suit in ("Diamonds","Hearts","Clubs","Spades"): return "Accepted" else: return "Wrong input" 

Just use in to verify ownership, if suit not in the tuple, your else clause will be executed.

membership operators

You can also change the logic with not in :

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

If you want to also check the value:

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

Using set {"Diamonds","Hearts","Clubs","Spades"} is a more effective way to verify membership.

+7
source

You can use in to check if suit in the list contains a tuple or a set of accepted masks:

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

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

+8
source

You can use the in operator:

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

I don't know if this is suitable for your needs, but sometimes an alternative approach using a dictionary can help with long sequences if ... elif :

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

Source: https://habr.com/ru/post/1201279/


All Articles