Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis+ 6
Boolean Logic third question related to not operator
What is the result of this code? if not True: print("1") elif not (1 + 1 == 3): print("2") else: print("3") explain me this plz
7 Respostas
+ 12
It will print 2.
Think of it like this, an if statement tests whether a condition is true, if it is true then the statements under it will run.
"#" indicates a comment, comments are ignored by the interpreter if you didn't know this.
if(True) # will run following statements
if(False) # won't run
not True = False
so
if (not True) # won't run
The parentheses are just so you can understand it better, they aren't necessary.
if not True: # False, won't run
print("1")
elif not (1 + 1 == 3): # True, because 1 + 1 does not equal 3
print("2")
else: # Won't run because the elif ran before it
print("3")
You can also use the != comparison operator.
Example:
if 1 + 1 != 3: # Returns True and runs the code in the block, 1 + 1 does not equal 3
...
+ 3
it's 2
I don't usually do python.
but because of the "Not" it makes everything that is true, false and everything that is false, true
If you look at the second "if" you can see that 1+1 does not equal 3 which makes it false.
but because of the Not it makes that false statement true.
+ 2
Š£ ŃŠµŠ±Ń ŃŃŠ»Š¾Š²ŠøŠµ, ŃŃŠ¾ not True, Š·Š½Š°ŃŠøŃ ŠæŃŠ¾ŠæŃŃŠŗŠ°ŠµŠ¼ ŃŃŠ¾ ŃŃŠ»Š¾Š²ŠøŠµ, Š“Š°Š»ŠµŠµ ŃŃŠ»Š¾Š²ŠøŠµ elif not(1+1==3): Š£ŃŠ»Š¾Š²ŠøŠµ Š·Š²ŃŃŠøŃ ŃŠ°Šŗ: ŠµŃŠ»Šø 1+1 Š½Šµ ŃŠ°Š²Š½ŃŠµŃŃŃ 3 ŃŠ¾ Š²ŃŠ²Š¾Š“ŠøŠ¼ 2, ŠæŠ¾ŃŃŠ¾Š¼Ń ŠæŃŠ¾Š³ŃŠ°Š¼Š¼Š° Š²ŃŠ²ŠµŠ“ŠµŃ 2.
+ 1
if not True can be understood as if False. elif not can also be understood as another if False. (1 + 1 == 3) -> (2 == 3), which is false. So the output is 2. Therefore do not continue to the next line since the second statement worked (printed an output).
0
Here
if not True :
'''this statement will print 1 when the if returns true but as you know not operator inverts the condition so true became false and statement of the first if block won't run '''
elif not(1+1==3):
'''here (1+1==3) is false ,cause 1+1=2 . So , as the not operator inverts false as true , the statement of second block will run and print 2 and else statement will not run'''
0
Answer is 2
In second case you see that 1+1 actually equals to 2 but here it is written that 1+1=3
Surely it should give false but we had used not here so output will be reversed to true and the elif condition will be executed.
I hope I had cleared your doubtāŗļø
0
if not true means if false as mentioned in some comments above. But the false statements will not be printed, thats why 1 is not printed.
elif not (1 + 1 == 3) means if 1 + 1 is not equal to 3, which is True.
Because itās true, therefore 2 is printed.
else: means if both statements above are falls then print 3. But one of the statements above was true, thatās why 3 is not printed.
As a result only 2 is printed, because this statement is true.