Main Content

Conditional operators in Python

Archive - Originally posted on "The Horse's Mouth" - 2016-11-05 09:16:04 - Graham Ellis

Python does NOT support the ? and : condiitonal operator. Instead, the and and or keywords are lazy.

Look at this example which seeks out the longest line in a file and tells you how long it is:

  fh = open("ac_20160516.xyz")
  loli = 0
  while True:
    l = len(fh.readline())
    if l == 0: break
    loli = loli < l and l or loli
  print loli


loli is the longest line to date as the file is parsed, with l being the length of each line. In the conditional line, loli is checked against l and the larger of the two is assignd back to loli.