0

I have two variables a and b both are type string. It still works with greater than and less than operation with the assert. Shouldn’t it suppose to throw a Syntax error?

In [34]: a = '1'                                                                                    

In [35]: b='2'                                                                                      

In [36]: type(a)                                                                                    
Out[36]: str

In [37]: assert a<b   #This works like integer or float                                             

In [38]: assert a>b                                                                                 
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-38-e1202bf94274> in <module>
----> 1 assert a>b

AssertionError: 

Here is second example, which is completely non-numeric string, still it works. How?

In [49]: a='bob'                                                                                    

In [50]: b='cat'                                                                                    

In [51]: assert a>b                                                                                 
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-51-e1606bf94274> in <module>
----> 1 assert a>b

AssertionError: 

In [52]: assert a<b     # How does this becomes true?
MikeCode
  • 91
  • 11
  • 4
    ASCII value comparisons. The characters of 'bob' have a lower value than 'cat'. Same for '1' and '2'. – Rashid 'Lee' Ibrahim Mar 23 '20 at 20:21
  • 2
    Your assumption is wrong. `a = '1'; b = '2'` are still strings no numbers. Python does something like `ord('1') > ord('2')`. So `'2' > '10'` is True because `ord('2') > ord('1')`. – nauer Mar 23 '20 at 20:24

1 Answers1

1

when you evaluate 'bob' > 'cat' will actually evaluate the elements from left to right, first will compare character 'b' with 'c' which is obvious that 'b' is not > than 'c' (you could use the built-in function ord to check the value) since they are not equal the evaluation will stop and the truth value of the expression is False so your line assert a>b will raise AssertionError

kederrac
  • 16,819
  • 6
  • 32
  • 55