Python (IF statements) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Python (IF statements)

What is the output of this code? num = 7 if num > 3: print("3") if num < 5: print("5") if num ==7: print("7") the ans is 3 .. my question is why it is not 37?

20th May 2020, 7:17 AM
Kirti
Kirti - avatar
6 Answers
+ 6
Because variable num is not less than 5, So num < 5 the condition fails and the indented code will won't execute ---------------------------------------- num = 7 if num > 3: print("3") if num < 5: print("5") if num ==7: print("7") The above will make output 37 ---------------------------------------------- NOTe: space matters in python
20th May 2020, 7:27 AM
Subash
Subash - avatar
+ 2
It is because when it reached if num > 3: print ("3") the if loop closed and 3 is printed as if num < 5:. is FALSE So the conditions after it would not be carried out!
21st May 2020, 6:11 PM
ROHIT PRADHAN
ROHIT PRADHAN - avatar
+ 1
num = 7 #1 if num > 3: #2 print("3") #3 if num < 5: #4 print("5") #5 if num ==7: #6 print("7") #7 Now as num is 7, #2 condition is true, so 3 will be printed. Next, #4 condition is false so the control will jump out of that suite (block of code) #6 condition comes under #4 indent. So #6 will execute only if #4 is True. So answer is 3 And not 37
22nd May 2020, 4:26 AM
Vaishnavi Rajkumar Pawar
0
Because of when your loop reach at if num>3: your computer has to stop computing before and give the answer that is 3.
20th May 2020, 5:35 PM
Dhiren Machhar
Dhiren Machhar - avatar
0
The 'if' statements should be indented using equal spaces. 'elif' and 'else' statements should also fall in the same line as the if statements for example x=input("Enter x: ") num1=int(x) print(num1) if num1<=60: print("Pass") elif num1>=60: print("Good") elif num1>=70: print("Excellent!")
20th May 2020, 8:14 PM
Steve Biko
Steve Biko - avatar
0
each time you indent, the code must meet the if requirements before it to run. youre telling the computer if 7 < 5, follow these commands. so it doesnt print “7” because it just skips the code in that section
21st May 2020, 2:28 PM
madeline
madeline - avatar