Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Basic Object-Oriented Python Welcome to OOP Methods

Faris Rachmadyo
Faris Rachmadyo
1,660 Points

Method with Megan Amendola

hello, can someone explain me when i set gas consumption 35, why the method use_gas called second times, it produce You are run out of gas!???

Class Car():
    doors = 4
    wheel = 4
    engine = True

    def __init__(self, model, year, make = "Honda"):
        self.model = model
        self.year = year
        self.make = make
        self.gas = 100
        self.is_moving = False

    def stop(self):
        if self.is_moving:
            print("The Car has stopped")
            self.is_moving = False
        else:
            print("The car has already stop")

    def go(self, speed):
        if not self.is_moving:
            if not self.is_moving:
                print(f"The car is start")
                self.is_moving = True
            print(f"the car is going {speed} KMH")
        else:
            print("You are run out of gas!")
            self.stop()

    def use_gas(self):
        self.gas -= 35
        if self.gas <= 0:
            return False
        else:
            return True

car_one = Car("Civic", 2022)
car_one.stop()
car_one.go(200)
car_one.go(250)
car_one.go(300)
car_one.stop()
car_one.stop() 

please help, i am newbie in python and sorry for my english

Faris Rachmadyo
Faris Rachmadyo
1,660 Points

this is the result

The car has already stop
The car is start
the car is going 200 KMH
You are run out of gas!
The Car has stopped
The car is start
the car is going 300 KMH
The Car has stopped
The car has already stop

2 Answers

Faris Rachmadyo
Faris Rachmadyo
1,660 Points

sorry my false is i type incorrect if statement under method go, it must be like this :

def go(self, speed):
    if self.use_gas():
Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 90,797 Points

What stands out to me is that you have 3 calls to the go method of over 200 but you only start with enough gas for 100. That may be why you're seeing the car stopped when you're not expecting it to.

Faris Rachmadyo
Faris Rachmadyo
1,660 Points

200, 250, and 300 are for speed, i set each call will consume 35