if coin == 25 | 10 | 5:
If I replace the ‘|’ with ‘or’ the code runs just fine. I’m not sure why I can’t use ‘|’ in the same statement.
Doing the following doesn’t work either:
if if coin == 25 | coin == 10 | coin == 5:
I know bitwise operators can only be used with integers, but other then that is there another difference from logical operators?
a use case – feature flags
Mix and match to plan your day
will i be going home today?
>>> OUTRAGED_BY_NEWS = 0b00000001 >>> GET_A_COFFEE = 0b00000010 >>> GO_FOR_A_HIKE = 0b00000100 >>> GO_FOR_A_RUN = 0b00001000 >>> GO_HOME = 0b00010000 >>> various_flags_ored_together = GET_A_COFFEE | GO_FOR_A_RUN | GO_HOME >>> various_flags_ored_together & GO_HOME == GO_HOME True >>> various_flags_ored_together & GO_FOR_A_HIKE == GO_FOR_A_HIKE False >>> various_flags_ored_together = GET_A_COFFEE | GO_FOR_A_RUN | GO_HOME >>> bin(various_flags_ored_together) '0b11010' >>> various_flags_ored_together & OUTRAGED_BY_NEWS == OUTRAGED_BY_NEWS >>> False >>> bin(OUTRAGED_BY_NEWS) >>> '0b1' >>> various_flags_ored_together >> OUTRAGED_BY_NEWS >>> bin(various_flags_ored_together) '0b1101'
Guess haven’t gone for a hike today…maybe tomorrow
right shift removes bit at flag position. Which, in this case, happens to correspond to the right most bit.
use case – file access permissions
For those looking to check file access permissions there is the stat module
>>> import stat >>> from pathlib import Path >>> path_f = Path.home().joinpath(".bashrc") >>> stat.S_IRUSR 256 >>> path_f.stat().st_mode 33188 >>> is_owner_read = path_f.stat().st_mode & stat.S_IRUSR == stat.S_IRUSR >>> is_owner_read True >>> path_f = Path("/etc/fstab") >>> is_other_write = path_f.stat().st_mode & stat.S_IWOTH == stat.S_IWOTH >>> is_other_write False
Assumes
~/.bashrc
exists, if not choose a different file you are owner and have read access to.path_f.stat().st_mode & stat.S_IRUSR == stat.S_IRUSR
Looking thru the mundane file (not Linux access control list) permissions. All those flags are crammed into st_mode. In st_mode, on/off bit at 2^8 is that on?
Sources
read user access stat.S_IRUSR
write others access stat.S_IWOTH
os.stat_result
pathlib.Path.stat