Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given two "if" statements, execute some code if none of them is executed

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.

like image 363
breakshooter Avatar asked May 11 '18 13:05

breakshooter


People also ask

Can IF statement have 2 conditions in Excel?

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.

How do you write an IF THEN statement in Excel with multiple conditions?

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.

Can there be 2 if statements in Python?

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.

Can we use 2 if statements in Java?

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.


2 Answers

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")
like image 187
LoicM Avatar answered Oct 29 '22 19:10

LoicM


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.

like image 28
brandizzi Avatar answered Oct 29 '22 18:10

brandizzi