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:
- Conditions aren't correct. If
num==10
, it will already be covered innum>3
. Ifnum> 3 or num<7
basically covers all the cases in universe so your assumption thatif(LastRun)
won't get executed whennum==1
, is false - Local LastRun variable will override global one and the condition
if(LastRun)
will never get executed - 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 assigningLastRun=true
in those if else, you can have a singleif(condition1 || condition2 || condition3){}
Edit: - as answered by Gaurav Sharma, declare and initialize
LastRun=true
, and inelse
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!!