How Do Quotes Affect Python if Conditional Tests of Equality for a Variable?

Problem scenario
You are programming in Python, and you want to use conditional logic.  You want to know how variables are evaluated and tested.  You want to use the keyword "if" to evaluate a variable assignment.

Solution
This program below shows how the evaluation of a variable in Python behaves when quotes are involved. Errors are not thrown or displayed to the programmer.  Therefore in some instances the programmer must know how quotes affect logical evaluations with variables.

Notice how "testfunc" and "specialfunc" test the variable named "digit" with and without quote marks respectively:


def testfunc(digit):
  if (digit == 0):
    print( "The digit was zero when you called this function")
  else:
    print ("The digit was NOT 0.")

h = testfunc('0')
print ("h with quotes around the zero is above. i with no quotes around the zero is below")
i = testfunc(0)

print( " ")
print( " **************** ")
print( " ")

def specialfunc(digit):
  if (digit == '0'):
    print( "The digit was zero when you called this function")
  else:
    print( "The digit was NOT 0.")

j = specialfunc('0')
print( "j is above with quotes around the zero. k is below with no quotes around the zero.")
k = specialfunc(0)

###Python 3 version above

###Python 2 version below

def testfunc(digit):
  if (digit == 0):
    print "The digit was zero when you called this function"
  else:
    print "The digit was NOT 0."

h = testfunc('0')
print "h with quotes around the zero is above. i with no quotes around the zero is below"
i = testfunc(0)

print " "
print " **************** "
print " "

def specialfunc(digit):
  if (digit == '0'):
    print "The digit was zero when you called this function"
  else:
    print "The digit was NOT 0."

j = specialfunc('0')
print "j is above with quotes around the zero. k is below with no quotes around the zero."
k = specialfunc(0)

The above program prints this:

The digit was NOT 0.
h with quotes around the zero is above. i with no quotes around the zero is below
The digit was zero when you called this function

 ****************

The digit was zero when you called this function
j is above with quotes around the zero. k is below with no quotes around the zero.
The digit was NOT 0.

Given that the only difference between testfunc and specialfunc is the quotes around the 0 in the if clause, you may think that Python is weakly-typed.  There are no errors thrown.  However, Python is strongly typed and dynamically typed.  For more information see this article.

Leave a comment

Your email address will not be published. Required fields are marked *