Sublime Forum

Python 3.9 No Output to Console

#1

The code below does not produce a result in the console. This is an exercise from the book Python Crash Course (I am total beginner). The code runs but nothing prints. I think it is related to the creation of a class. This is the first lesson that has a new class and an instance of that class. If I add print(“hello world”) at the bottom of this code it prints.

I am using Mac Mojave & Python 3.9. I made sure that Python 3 is selected in build, tried Shift + Command + B. Any guidance on what I’m doing wrong appreciated. Thanks!

class Dog :
    """A simple attempt to model a dog"""

    def __init__(self, name, age):
        
        """Intialize name and age attributes."""
        self.name = name
        self.age = age
        
    def sit(self):
        """ Simulate a dog sitting is response to a command."""
        print(f"{self.name} is now sitting.")
    
    def roll_over(self):
        """Simulate rolling over in response to a command."""
        print(f"{self.name} rolled over!")
        
        my_dog = Dog('Willie', 6)

        print(f"My dog's name is {my_dog.name}")
        print(f"My dog is {my_dog.age} years old.")
            
        my_dog.sit()
        my_dog.roll_over()
0 Likes

#2

Your code isn’t doing anything, that’s why nothing gets printed. You’ve defined a Dog class with some methods, but you’re making an instance of said class or calling any of those methods.

0 Likes

#3

Thank you. So, the my_dog = Dog(‘Willie’, 6) and the print calls below it won’t work? Can you tell me why, please?

0 Likes

#4

You are instantiating your Dog class within one of it’s methods itself. I believe you got the indentation wrong.
So something like

class Dog(object):
    def __init__(self, name, age):
        
        """Intialize name and age attributes."""
        self.name = name
        self.age = age
        
    def sit(self):
        """ Simulate a dog sitting is response to a command."""
        print(f"{self.name} is now sitting.")

    def roll_over(self):
        """Simulate rolling over in response to a command."""
        print(f"{self.name} rolled over!")
    
my_dog = Dog('Willie', 6)

print(f"My dog's name is {my_dog.name}")
print(f"My dog is {my_dog.age} years old.")
    
my_dog.sit()
my_dog.roll_over()

1 Like

#5

Thank you! I thought I tried changing the indent - but I obviously did not. It works now. Thanks for the help!!

0 Likes