hey i don't know how to programm this constellation :
string = " "
if "abc" in string:
print ("abc is in string")
if "def" in string:
print ("def is in string")
else:
print ("abc and def are not contained in string")
It should go to "else" only if the 2 conditions aren't true. But if both substrings are contained in string; it should print both.
The multiple IF conditions in Excel are IF statements contained within another IF statement. They are used to test multiple conditions simultaneously and return distinct values. The additional IF statements can be included in the “value if true” and “value if false” arguments of a standard IF formula.
Another way to get an Excel IF to test multiple conditions is by using an array formula. To complete an array formula correctly, press the Ctrl + Shift + Enter keys together. In Excel 365 and Excel 2021, this also works as a regular formula due to support for dynamic arrays.
We can have a if...elif...else statement inside another if...elif...else statement. This is called nesting in computer programming. Any number of these statements can be nested inside one another.
Use two if statements if both if statement conditions could be true at the same time. In this example, both conditions can be true. You can pass and do great at the same time. Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.
You could simply define a boolean for each of your condition It keeps the code simple
abc = "abc" in string
def_ = "def" in string
if abc :
print("abc in string")
if def_ :
print("def in string")
if not (abc or def_) :
print("neither abc nor def are in this string")
Another option is to use a variable that is true only if a condition is satisfied before. This variable (let us call it found
) will be false by default:
found = False
However, in each of the if
statements, we set it to True
:
if "abc" in string:
print ("abc is in string")
found = True
if "def" in string:
print ("def is in string")
found = True
Now we only have to check the variable. If any of the conditions where met, it will be true:
if not found:
print ("abc and def are not contained in string")
That is only one of the options to solve this, but I have seen this pattern used many times. Of course, you can choose other approach if you feel it would be better.
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