+ 1
INDENTATION PROBLEM AND OUTPUT PROBLEM
What is the output of this code? num = 7 if num > 3: print("3") if num < 5: print("5") if num ==7: print("7") CAN SOMEONE EXPLAIN WHY IT WILL JUST PRINT 3 AND 3 AND 7? I GET THAT IT WILL NOT PRINT 5 BUT WHY WON'T IT PRINT 3 ON ONE LINE AND 7 ON NEXT LINE.
3 Respuestas
+ 2
Actually what is happening here is called nesting if statements..
The first condition, num > 3 is met and it prints 3.
The second statement runs only when num < 5, which is false,and it will not run.
The third statement runs whem num == 7, and this is true.
But wait,
The 3rd condition is only checked if the num < 5 and num > 3.
If you want to print 3 and 7.
You will need to write
num = 7
if num > 3:
print(3)
if num < 5:
print(5)
if num < 5:
print(7)
+ 1
Hey there Shevangae Singh !
See according to your code , num has the value of 7.
The first condition is that if num is greater than 3 then print 3. Since 7 is greater than 3, 3 will be printed.
The second condition is that if num is less than 5 then print 5. But since 7 is greater than 5, not lesser, 5 is not printed.
The third condition is that if num is equal to 7 then print 7. Since in the first line, you assigned the value of 7 to num, the condition is satisfied and 7 is printed.
This would be the case but since everything is indented, when the second condition failed, the code never went to the third condition.
When we intend, we imply that the indented statements are to be followed only if the if statement is true.
Hence the final output is 3.
Hope it helps.
0
Shevangae Singh if you mean about why 2 lines of output? Then:
print function have some arguments, from which end property have default value as end="\n" so it appends a new line charecter at end. If you want to print in the same line or to put something else then override end value as end="" end=" ".
print("3",end="") now next 7 value printed in same line.. Check this...