In: Computer Science
PYTHON
Exercise: Accelerate Method
-------------------------
### Description
In this exercise, you will add to your `Car` class
a method to accelerate the speed of an instance.
### Class Name
`Car`
### Method
`accelerate()`
### Parameters
* `self` : the `Car` object to use
* `delta_speed` : a number, the desired value to add to the speed
data member.
### Action
Adds `delta_speed` to the speed of the object. If the
new speed is too fast, then set the speed to the
maximum allowed speed.
Only do this action of `delta_speed` is positive, and
the `Car` isn't already at maximum speed.
### Return Value
`True` if a change occurred, `False` otherwise.
class Car:
def __init__(self):
self.speed = 0.0
def getSpeed(self):
return self.speed
def setSpeed(self, speed):
if speed >= 0 and speed <= 80:
self.speed=speed
return True
else:
return False
def accelerate(self, delta_speed):
class Car:
def __init__(self):
self.speed = 0.0
def getSpeed(self):
return self.speed
def setSpeed(self, speed):
if speed >= 0 and speed <= 80:
self.speed=speed
return True
else:
return False
def accelerate(self, delta_speed):
if delta_speed > 0:
if self.speed >= 80:
self.speed = 80
return False
elif self.speed < 80:
self.speed = self.speed + delta_speed
if self.speed > 80:
self.speed = 80
return True
else:
return False
I have put if-else condition to check if
delta_speed is positive or not and if its already
in max speed then no change. If after adding
delta_speed, the speed is greater than max speed,
i.e., 80, then speed is set to the
max allowed speed. Since, change in speed occurs, so it will return
True otherwise False.
Jupyter Notebook sample run: -