Why it print all 3?

I only need to print google from here, why does my code prints all 3? My code needs to return false if the string in array stars with ‘%’ or is an empty string.

header = ['google', '', '%micrasoft']

for x in header:
  if not x.startswith('%') or not x == '':

you’re using or condition… Which means statement will be executed if any of the given condition is true.

Let’s loop through the header

  1. For first one(google), both the conditions are true(‘google’ doesn’t start with % and it’s not an empty string)

  2. We’ve an empty string here, First condition is true(empty string doesn’t starts with %) and second is false. Hence the whole condition is True. and empty string is printed

  3. Third string is %microsoft, which starts with % and hence first condition is false(condition before the or keyword), but second condition is true as %microsoft is not an empty string.

You can use and operator, so that whole statement will be true only if both conditions are satisfied

Learn more about or and and operator at GeeksForGeeks

1 Like