0

Here is a simplified version of a class I want to use to run through some kind of algorithm. The problem is my comparison method between two class variables isn't returning what I expect.

import sys

class Gosh:
    def __init__(self, magicnumber):
        self.magicnumber = magicnumber
        self.number = 1400

    def isbad(self):
        print self.number
        print self.magicnumber
        return self.number < self.magicnumber

def __main__():
    magicnumber = sys.argv[1]
    gosh = Gosh(magicnumber)
    print gosh.isbad()

__main__()

Here is the output:

% python gosh.py 718
1400
718
True

It's late, and maybe I'm having a brain fart, but I can't figure out why it's doing this.

Matthias
  • 12,873
  • 6
  • 42
  • 48
Kaiser Octavius
  • 157
  • 1
  • 2
  • 8
  • 4
    You are comparing a string and a number. – Klaus D. Mar 03 '21 at 09:29
  • Doh! Brain fart it is :) – Kaiser Octavius Mar 03 '21 at 09:30
  • 4
    Python 2 is dead since the beginning of 2020 (and that was announced over 10 years ago). Use Python 3 and you'll get an error when you try to make this comparison. – Matthias Mar 03 '21 at 09:32
  • 1
    Does this answer your question? [How does Python 2 compare string and int? Why do lists compare as greater than numbers, and tuples greater than lists?](https://stackoverflow.com/questions/3270680/how-does-python-2-compare-string-and-int-why-do-lists-compare-as-greater-than-n) – Tomerikoo Mar 03 '21 at 09:54
  • Thanks, everyone. Now that I realize it's comparing a string with an int, it makes sense. The part I was missing was the constructor arg is a string and not an int when I reference it from argv. – Kaiser Octavius Mar 03 '21 at 10:03

2 Answers2

2

It may be because you are comparing a string with an integer. the value coming from sys.argv would be a string until you cast it as an integer.

Try:

magicnumber = int(sys.argv[1])
Pablo
  • 983
  • 10
  • 24
0

try to convert magic number to int

magicnumber = int(sys.argv[1])
George Imerlishvili
  • 1,816
  • 2
  • 12
  • 20
  • 1
    Welcome to Stackoverflow Giorgi! Please remembter to add explanations to your solution code - why did the original code not work, what's different in your code and why did it fix the problem. Otherwise it is hard for people to see how you solved what. – Cribber Mar 03 '21 at 09:45