Home > Back-end >  How can I run code If any one of if else statements is true?
How can I run code If any one of if else statements is true?

Time:04-16

Which condition keyword will run If one of if else statement run and it will run?

example:

int num = MyMathLibrary.random(1, 10);

if (num == 3){
    // do something
} else if (num == 7){
    // do something
} else if (num == 2){
    // do something
} runiftrue {
    // this "runiftrue" will run if any of if/else if statement is true
    // it means, if num = 3, or num = 7, or num = 2 it will run, but if num = 1 it will not run
}

before I use this:

int num = MyMathLibrary.random(1, 10);

boolean LastRun = false;


if (num == 3){
    LastRun = true;
    // do something
} else if (num == 7){
    LastRun = true;
    // do something
} else if (num == 2){
    LastRun = true;
    // do something
} 
    if (LastRun) {
        // this line of code will run if any of if/else if statement is true
        // it means, if num = 3, or num = 7, or num = 2 it will run, but if num = 1 it will not run
    }

but this way to do that is really not clever, and takes a lots of time to add a "boolean LastRun = true". Are there any more clever, easier and clearer way to do that?

CodePudding user response:

  1. Conditions aren't correct. If num==10, it will already be covered in num>3. If num> 3 or num<7 basically covers all the cases in universe so your assumption that if(LastRun) won't get executed when num==1, is false
  2. Local LastRun variable will override global one and the condition if(LastRun) will never get executed
  3. assuming you get all above things right and you are doing something additional things in if elseif section along with LastRun=true, LastRun=true will be the efficient way as you won't have to evaluate all conditions again. If you are not doing anything else apart from assigning LastRun=true in those if else, you can have a single if(condition1 || condition2 || condition3){}

    Edit:
  4. as answered by Gaurav Sharma, declare and initialize LastRun=true, and in else make it false

CodePudding user response:

#run a statement if one condition is true
import random

num = random.randint(1, 10)

condition = True

if (num > 3):
    print("Hello World")
    # do something
elif (num < 7):
    print("Hello World")
    # do something else
elif (num == 10):
    print("Hello World")
    # do something
else:
    condition = False

if(condition == True):
    print("Some statement was executed")

I hope this works for you!!

  • Related