Python Forum
Potential confusion combining != with or
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Potential confusion combining != with or
#11
(Oct-31-2019, 07:21 AM)perfringo Wrote: buran explanation backed-up with Python docs (already referenced earlier):

Quote:Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)

This behaviour enables writing 'clever' code like:

>>> lst = [1, 2, 3]
>>> for i in lst:
...     print(i % 2 and 'odd' or 'even')
... 
odd
even
odd

I didn't see these three posts until now. This is the sort of explanation I really wanted except I do not understand. Can you explain the odd, even, odd output in this example?
Reply
#12
maybe this will help as it brakes line 3 into sub-steps
lst = [1, 2, 3]
for i in lst:
    print(f'i={i}')
    print(f"i % 2 --> {i % 2}")
    print(f"{i % 2} and 'odd' --> {i % 2 and 'odd'}")
    print(f"{i % 2 and 'odd'} or 'even' --> {i % 2 and 'odd' or 'even'}")
    print('-'*10)
Output:
i=1 i % 2 --> 1 1 and 'odd' --> odd odd or 'even' --> odd ---------- i=2 i % 2 --> 0 0 and 'odd' --> 0 0 or 'even' --> even ---------- i=3 i % 2 --> 1 1 and 'odd' --> odd odd or 'even' --> odd ----------
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Is it possible to use the full potential of scalene in Pycharm? arnoldpredator 4 634 Nov-18-2023, 01:46 PM
Last Post: arnoldpredator
  Potential Permission error on Mac OSX Catalina OWOLLC 1 717 Nov-02-2023, 07:52 AM
Last Post: unjnsacih
  Potentiostat/Galvanostat potential issue pepe523869 10 2,464 Nov-05-2022, 07:08 PM
Last Post: pepe523869

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020