+ 2

Python3

code: x=1 y=1 if x and not y: print("a") else: print("b") I can't understand why the solution is "b".

12th Sep 2018, 5:48 AM
蘇詳崴
蘇詳崴 - avatar
10 odpowiedzi
+ 3
in a Boolean context 1 converts to True, and not y converts to False True AND False is False, so we execute the else branch, not the 'if'
12th Sep 2018, 6:17 AM
Dan Walker
Dan Walker - avatar
+ 2
0 = false 1 = true. since x and y are both 1(or true) saying “not y” returns the opposite of true(false) if statements only run if the value is true. else runs if no if / elif statements run. therefore, b is printed
6th May 2020, 8:39 AM
Ivan Shabashev
Ivan Shabashev - avatar
0
The if statement is passed if the evaluated condition gives you True. As it was explained, 1 and not 0 will lead to False. For better understanding, you should test and see how python evaluates different types of values. For instance, any 'int' or 'float' value which is different than 0 will evaluate to True, while the 0 value will lead to False. An empty string, "", will evaluate to False, and a string with one or more characters will evaluate to True. An empty list will evaluate to False, and a list with one or more items will evaluate to True. Etc. In the if condition above, x is evaluated to True and y to True. Thus, you get the expression: if True and not True: ... Finally, it will lead to False, because it's the AND result between True and False (not True). I hope that was helpful! :) Happy coding!
29th Nov 2019, 11:04 PM
Gonçalo Magalhaes
Gonçalo Magalhaes - avatar
0
If not(x and y):
27th Jan 2020, 6:00 PM
Amir_thb
Amir_thb - avatar
0
Python3 code: x=1 y=1 if x and not y: print("a") else: print("b") I can't understand why the solution is "b".
9th May 2020, 7:05 AM
Kuldeep Yadav
Kuldeep Yadav - avatar
0
ok, its got to do with booleans. True=1 False=0 b is true. not(b) means opposite of true, so not b is false. if a and not b is a false statement. if not b was true then it’d be a true statement. hope you understood.
2nd Jul 2020, 4:34 AM
Pr0C0d3r
Pr0C0d3r - avatar
0
In a Boolean 1 means true and 0 means false, and X and y are 1 here so both true. The if statement asks if X is true and y is false, that isn't the case so it executes the else and prints b
23rd Jul 2020, 11:24 AM
milo
milo - avatar
0
If u want to make the solution 'a' use 'or' at the place of 'and'.
24th Sep 2020, 1:31 PM
Ved Tiwari
27th Jun 2021, 8:02 AM
Sushant Raj
Sushant Raj - avatar
- 1
True "Pr0C0d3r 6₹--₹ sotzzkgagakzhlgri💜💕
29th Jan 2021, 9:54 AM
Onkar Pawar
Onkar Pawar - avatar