0

Here's my code, super new to python. Struggling to understand why if I use < it always thinks is less than even though it will print a higher number. If I use greater than it works just fine. What am I missing? Here's my code, super new to python. Struggling to understand why if I use < it always thinks is less than even though it will print a higher number. If I use greater than it works just fine. What am I missing?

import time
t=time.localtime()
msttime=time.strftime("%H",t)
if(msttime < '2'):
    print(msttime)
else:
    print("This calculation believes msttime is greater than 2")
martineau
  • 119,623
  • 25
  • 170
  • 301
will.ditch
  • 49
  • 9
  • 1
    With strings, lt and gt are calculated in alphabetical order not numeric. `'2' > '1000'` because `2` comes after `1000` in the dictionary. – Mark May 15 '20 at 01:04
  • See Wikipedia article [Lexicographical order](https://en.wikipedia.org/wiki/Lexicographical_order) which is how Python compares strings. – martineau May 15 '20 at 01:08

1 Answers1

1

This code will give you the expected result:

import time

t = time.localtime()
msttime = time.strftime("%H", t)

if (int(msttime) < 2):
    print(msttime)
else:
    print("This calculation believes msttime is greater than 2")

The reason is that "18" < "2" lexographically, but 18 > 2 numerically. This is because the lexographical comparison has no regard for the second digit. Since 1 is before 2, the comparison ends there. In the numerical comparison, all digits are accounted for.

Mario Ishac
  • 5,060
  • 3
  • 21
  • 52