I have this simple python program. I ran it and it prints yes, when in fact I expect it to not print anything because 14 is not greater than 14.
I saw this related question, but it isn’t very helpful.
#! /usr/bin/python
import sys
hours = "14"
if (hours > 14):
print "yes"
What am I doing wrong?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Convert the string to an integer with int:
hours = int("14")
if (hours > 14):
print "yes"
In CPython2, when comparing two non-numerical objects of different types, the comparison is performed by comparing the names of the types. Since 'int' < 'string', any int is less than any string.
In [79]: "14" > 14 Out[79]: True In [80]: 14 > 14 Out[80]: False
This is a classic Python pitfall. In Python3 this wart has been corrected — comparing non-numerical objects of different type raises a TypeError by default.
CPython implementation detail: Objects of different types except
numbers are ordered by their type names; objects of the same types
that don’t support proper comparison are ordered by their address.
Method 2
I think the best way is to convert hours to an integer, by using int(hours) .
hours = "14"
if int(hours) > 14:
print("yes")```
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0