Printing data from python program to terminal on mac

I'm trying to get my code to output the results of really any code to my terminal, but I can't seem to find out why it won't print. I'm just learning to code so I've been finding a lot of explanation on this site kind of confusing, so apologies if this has been asked before. This is my python file python.py:

class point(object):

    def __init__(self, x, y):

        self.x = float(x);
        self.y = float(y);

    def __str__(self):

        return("(" + self.x + "," + self.y + ")")


def main():

    first = point(2,3)


if __name__ == '__main__':
    main()

and in the terminal I'm just typing "python python.py"

Upvotes: 1

Views: 2475

Answers (2)

apolshchikov
apolshchikov

Reputation: 16

As others have mentioned, you need to add a print() call in your main function in order to get output to the terminal. Additionally, a few other things to note: Python doesn't require semi-colons, so there's no need for them in your __init__() method and you can't implicitly convert floats to strings, so you have to be explicit in your __str__() method.

class point(object):
    def __init__(self, x, y):
        self.x = float(x)
        self.y = float(y)

    def __str__(self):
        # explicitly cast floats to strings
        return "(" + str(self.x) + "," + str(self.y) + ")"

def main():
    first = point(2,3)
    print(first)

if __name__ == '__main__':
    main()

Also, as MrTrustworthy pointed out, you don't need to call Class.__str__() directly as print first calls the __str__() method associated with the class. If there's no such method and implicit conversion fails, then you will get the representation of the calling function and the address in memory.

If you remove __str__() from your example, you should get output like this: <__main__.point object at 0x7f184cec4b70> if you try to print the object.

Upvotes: 0

ShreyasG
ShreyasG

Reputation: 806

Add a print statement in the main() function to print to terminal:

class point(object):

def __init__(self, x, y):

    self.x = float(x);
    self.y = float(y);

def __str__(self):

    return("(" + self.x + "," + self.y + ")")


def main():

    first = point(2,3)
    print(first)


if __name__ == '__main__':
    main()

Upvotes: 1

Related Questions