this post was submitted on 09 Mar 2025
1 points (100.0% liked)

Python

7947 readers
1 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

πŸ“… Events

PastNovember 2023

October 2023

July 2023

August 2023

September 2023

🐍 Python project:
πŸ’“ Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
Feeds

founded 3 years ago
MODERATORS
 

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 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?

you are viewing a single comment's thread
view the rest of the comments
[–] ExtremeDullard@lemmy.sdf.org 0 points 1 year ago* (last edited 1 year ago)

Much to unpack here...

coin == 25 | 10 | 5

...will evaluate as True if coin is equal to the bitwise OR of 25, 10 and 5 - i.e. 31. In other word, it's equivalent to coin == 31. That's because the bitwise OR has precedence over the == operator. See operator precedence in Python.

If I replace the β€˜|’ with β€˜or’ the code runs just fine.

It probably doesn't. If you replace | with or, you have the statement coin == 25 or 10 or 5 which is always True in the if statement because it's evaluated as (coin == 25) or (not 0) or (not 0) in an if statement.

coin == 25 | coin == 10 | coin == 5

...will evaluate as coin == (25 | coin) == (10 | coin) == 5. Again, operator precedence.

What you want to do is this:

if coin in [25, 10, 5]:

or

if coin in (25, 10, 5):

or simply

if coin == 25 or coin == 10 or coin == 5:

Don't create problems and confusion for the next guy who reads your code for nothing. Simple and readable are your friends πŸ™‚