Why only first (true) condition always prints? | SoloLearn: Learn to code for FREE!

+4

Why only first (true) condition always prints?

#If I add one statement two times (once in if and another in elif) why only it prints the first one? #(Python) #Eg - x = 5 y= 6 z= 7 if (x == 6 or y !=5): print ("Hi") elif (z == 7): print ("Yo") elif (z == y): print ("Hello") else: print ("Nothing") Why only first condition prints whereas both 1st and 2nd is true? If we want to print both the true codition what can we do for it?

4/7/2018 8:33:41 AM

Aditya Rawat

5 Answers

New Answer

+3

Syntax for if else : if condition: Statement. else: Statement. Syntax for elif or else if statement : if condition: statement elif condition: statement else: statement ( Note: You can use as many as elif statements in between if and else . But you cannot use if and else more than once.)

+2

Because there is elif statement. If one of them(most top) is true then it is stopped from doing later elif. If you want to make it to work like you want then change each of elif for if. You can translate elif - "if there is not condition upper which is true then try to do this condition."

+2

If the if statement evaluates to False then the else statement is executed. Here , in the first if statement , the condition evaluates to true , so print("Hi") is executed and the program ignores the elif and else statements.

+2

Also this is not the way of writing if statements in Python. You should not include parenthesis

+2

Vinyas Amin I thought it was conditional It was because of my C# habbit😐