简体   繁体   中英

i do not understand the usage of the first not true statement in the first line of code?

I didn't understand the purpose of first not true statement as i understand that
if proceeds with statement if it is deemed true but in the following scenario shouldn't code return out no results?
PS: I am just learning python for the first time and
would appreciate your valuable time and help

if not True:
   print("1")
elif not (1 + 1 == 3):
   print("2")
else:
   print("3")

The output of the following code turns out to be 2 I dont understand how?

The first line will always be bypassed and will never get executed, the fact is if statement will check if the expression is true or false and doesn't really care about it if it seems logical or not, if not True: is not logical cause it's never going to get executed! but in some cases you need while True to create an endless loop, but for if statements it doesn't sound logical however it works.

  1. The first condition makes no sense. The default value of an expressionless boolean check is True, thus making the condition False.

  2. It gets to the else-if condition which checks if (1+1 == 3) is False, which is True. thus printing 2.

  3. An else statement is executed only if all the preceding if and elif conditions are not met.

Hence, the output turns out to be 2.

if tries to search for True condition here

so first condition ---> if not True (means) if False: print(1) -------> this is false condition and will never be executed in any case

2nd condition -------> else if not (1+1 = 3) ---> this is True condition. as 1+1 is not equal to 3

3rd condition ----> if above 2 conditions is not true, than print 3 but condition 2 is true hence answer will be (2) which is true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM