0
What's going on in this Challenge question?
The question was: What is the output of this code? mylist = [False] string = "a" if mylist else "b" print(string) The answer is: a I expected: b Could somebody explain this? I haven't even seen this type of syntax before (conditional statement inside an assignment). Thanks! Felix
11 Réponses
+ 6
In my understanding,
False --> 0
[False] --> [0]
Since the array isn't empty
"String = 'a' if mylist" is true, so it prints a
Using False without the brackets
mylist=False
"string = 'a' if mylist" is False,prints b
+ 3
Kiran Deep Naidu Felix is right.
The challenge regards the list, not the items in the list.
+ 2
Felix Lipo, when you mention the list in if statement then it would consider the number of elements in the list. So, according to your program it evaluates as
string = "a" if 1 else "b" (since mylist length is 1)
So, as the condition is True it assign the "a" to variable "string"…
To make the answer you desired make the "mylist" as empty (mylist=[])
+ 2
But mylist is not False ,it is a list with 1 entry
You mean
mylist = [False]
string = "a" if mylist[0] else "b"
print(string)
+ 2
Thanks Oma Falk, I think I have gained some sort of knowledge out of this discussion
+ 1
Booleans can be very confusing at times. But in your code, mylist is true because a list does exist. The code does not check the values in the list. It is just like when you type "False"(False in inverted commas, that is in string). When you remove the brackets, the output will be 'b'.
The above syntax means:
String=(Value if true) if (condition) else (Value if false).
+ 1
Thanks for the quick answers, guys! I think I understood it now! Kiran Deep Naidu: I think the lenght of the list doesn't matter as long as it isn't empty.
0
And here is the code: https://code.sololearn.com/ciB0dRT5gkse/?ref=app
Happy Easter, guys!
0
mylist = False
string = "a" if mylist else "b"
print(string)
0
In my understanding it matters Felix Lipo, because any value except 0 results in True.
- 1
In my understanding,
False --> 0
[False] --> [0]
Since the array isn't empty
"String = 'a' if mylist" is true, so it prints a
Using False without the brackets
mylist=False
"string = 'a' if mylist" is False,prints b