Home > Mobile >  What happens when I put a string behind 'and' operator
What happens when I put a string behind 'and' operator

Time:02-27

Beginner question, what happens if a string is used as one of the conditions for an 'and' operator in Python code?

def bar(a,b):
  if b%a >= b-a:
    print(a, "first")
  elif b*3 > a**2 and "False":
    print(a, "second")
  else:
    print(a, "third")
  a,b = b%a,a
  if a>1:
    bar(a,b)
bar(7,19)

I'm referring to the second elif condition here. Appreciate the help!

CodePudding user response:

Null string will evalulate to False , non-empty string will evaluate to True.

CodePudding user response:

In python, an object is considered True by default unless its class defines a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. Learn more in this article on python operators and in the official python documentation.

What this means for your example above is that having a string in the conditional statement after an and has no effect on the logic of the program since it is always considered True. What ultimately affects whether you enter an if, elif, or else block in your example is the expression that comes before the and which can evaluate to either a boolean True or False depending on the inputs to the function. Furthermore, if you were to add an integer or float right after the and instead of a string you would discover this exact same behaviour.

The only example where adding something after an and would affect the logic of the program would be if you added any of the following (which would be considered as False):

  • zero of any type: 0, 0.0, etc.
  • constants such as None and False
  • empty sequences or collections: '', (), [], {}, set(), range(0)

CodePudding user response:

putting string or int or whatever in if condition will always return True. If blank or null than it will return False. try executing it and you will be able to understand it better.

if (2 and "hello"):
    print("2 and hello")

if (2 or "hello"):
    print("2 or hello")

if ("hello"):
    print("only hello")

if (2):
    print("only 2")

b = 5
if (b):
    print("variable b")

c = ''
if (c):
    print("variable c. this if will not be executing")

you will find every if is executing except the last that is assigned blank.

  • Related