-2

I have to create a Car class that has the following characteristics:

It has a gas_level attribute.

It has a constructor (init method) that takes a float representing the initial gas level and sets the gas level of the car to this value.

It has an add_gas method that takes a single float value and adds this amount to the current value of the gas_level attribute.

It has a fill_up method that sets the car’s gas level up to 13.0 by adding the amount of gas necessary to reach this level. It will return a float of the amount of gas that had to be added to the car to get the gas level up to 13.0. However, if the car’s gas level was greater than or equal to 13.0 to begin with, then it doesn’t need to add anything and it simply returns a 0.

Result should be:

example_car = Car(9)
print(example_car.fill_up())  # should print 4

another_car = Car(18)
print(another_car.fill_up()) # should print 0

This is what I have so far. Just got stuck in the add_gas and fill_up methods.

class Car:
   def __init__(self, gas_level_x):
      self.x = gas_level_x
   def add_gas(self):
      return ((self.x + 

   def fill_up(self):
      return  

def main():
   ex_car = Car(9)
   print(ex_car.fill_up())             

if __name__ == "__main__":
   main()        
EnzoRad
  • 1
  • 1
  • 1

2 Answers2

0

If I understand it right all you want is this? if the tank is lower then 13 you tank it full till it's 13 and return the added value. else return 0

class Car:
    def __init__(self, gas_level_x):
        self.x = gas_level_x

    def add_gas(self, gas):
        self.x += gas

    def fill_up(self):
        added = 13-self.x
        self.x += added # Or call self.add_gas(added) if for some reason you want to use the method
        if added > 0:
            return added
        return 0

Edit: And to test your requirements I've ran:

car = Car(9)
print(car.fill_up()) # Prints 4

car = Car(18)
print(car.fill_up()) # Prints 0
davy gillebert
  • 307
  • 1
  • 11
  • However this is basically the same answer that EnzoRad gave... So if that is not what you're looking for you'll have to specify your problem a bit more. **EDIT:** Aah right you need to add the amount to self.x indeed that is what we forgot but that easy to do I'll edit my answer – davy gillebert Aug 28 '17 at 09:31
-1
class Car:

  def __init__(self, init_g):
    self.g = init_g
  def add_gas(gas):
    self.g = self.g + gas

  def fill_up(self):
    if self.g < 13:
        return 13 - self.g
    else:
        return 0 
EnzoRad
  • 1
  • 1
  • 1