Python Forum
Simplifying multiple "or" conditions in if statement.
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simplifying multiple "or" conditions in if statement.
#6
if ('Ed' or 'Bob') in s:
This code checks always if 'Ed' in s:

The or operator is a binary operation, which is checking for trueness.
A str object with the length 0 is False. All other str objects are True.
With your code you'll always get 'Ed' after evaluating the expression.

What you want to do:

s = 'BobTom'

for name in ('Bob', 'Ed'):
    if name in s:
        print('Name {} is in {}'.format(name, s))
If you want to check if any of the names is in the string, you can write it more compact:

any(name in s for name in ('Bob', 'Ed'))
If you want to check if all the names are in the string, you can use the built-in function all:

all(name in s for name in ('Bob', 'Ed'))
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: Simplifying multiple "or" conditions in if statement. - by DeaD_EyE - Jul-21-2017, 01:32 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How do you format Update statement with multiple conditions hammer 4 2,110 Dec-16-2021, 10:49 PM
Last Post: hammer
  multiple condition if statement problem FelixReiter 3 2,614 Jan-11-2021, 08:07 AM
Last Post: FelixReiter
  Multiple conditions when indexing an array with or without np.where noob2305 1 2,683 Oct-25-2020, 02:06 PM
Last Post: jefsummers
  Multiple conditions, one is null moralear27 1 2,204 Sep-13-2020, 06:11 AM
Last Post: scidam
  SyntaxError: multiple statements found while compiling a single statement Kayode_Odeyinka 1 2,997 Mar-12-2020, 05:50 PM
Last Post: micseydel
  multiple conditions Chandan 7 4,023 Jan-31-2020, 12:53 AM
Last Post: Chandan
  Help for simplifying code mmk1995 8 4,182 Sep-24-2019, 02:04 PM
Last Post: perfringo
  simplifying a stack of elifs Skaperen 8 4,115 Aug-17-2019, 04:13 AM
Last Post: Skaperen
  Simplifying my code ilondire05 5 3,793 Jul-21-2019, 03:21 AM
Last Post: scidam
  SyntaxError: multiple statements found while compiling a single statement DragonG 1 5,460 Nov-26-2018, 05:33 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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