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.
The limit is 7. However, it is possible to circumvent the limitation over the number of nested conditional formulas by cascading them. This article will look at the different methods for nesting multiple IF statements in Excel.
Using either “&&” or “||” i.e. logical AND or logical OR operator or combination of can achieve 3 conditions in if statement JavaScript.
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
({...}
).
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
You can use the in
operator:
accepted = ['Diamonds', 'Hearts', 'Clubs', 'Spades']
if suit in accepted:
return "accepted"
else:
return "wrong input"
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With