Write a program that simulates a television with a class Television. The class s
ID: 3537125 • Letter: W
Question
Write a program that simulates a television with a class Television. The class should create the following attributes for a new object:
The class should define the following methods:
The class should define one property:
Your program should instantiate an object from the class Television and allow a user to manipulate it through a menu system. The menu choices should be:
0 - Exit
1 - Toggle Power
2 - Change Channel
3 - Raise Volume
4 - Lower Volume
The Program should display the status of the television each time it presents the menu
Explanation / Answer
Here is the code I wrote after reading your problem definition. Dont forget to rate.
class Television(object):
def __init__(self, channel=1, volume=1, is_on=False):
self._channel= channel
self.volume = volume
self.is_on = is_on
def __str__(self):
volume = self.volume
if not volume:
volume = 'muted'
elif volume == 10:
volume = 'max'
if self.is_on:
return "The TV is on, channel {0}, volume {1}".format(self.channel, volume)
else:
return "The TV is off."
def toggle_power(self):
self.is_on = not self.is_on
return self.is_on
def get_channel(self):
return self._channel
def set_channel(self, choice):
self._check_on()
if 0 <= choice <= 499:
self._channel = choice
else:
raise ValueError('Invalid channel')
channel = property(get_channel, set_channel)
def _check_on(self):
if not self.is_on:
raise ValueError("The television isn't on")
def raise_volume(self, up=1):
self._check_on()
self.volume += up
if self.volume >= 10:
self.volume = 10
def lower_volume(self, down=1):
self._check_on()
self.volume -= down
if self.volume <= 0:
self.volume = 0
def main():
tv = Television()
while True:
print 'Status:', tv
"""
Television
0 - Exit
1 - Toggle Power
2 - Change Channel
3 - Raise Volume
4 - Lower Volume
"""
choice=raw_input("Choice: ")
try:
if choice=="0":
break
elif choice=="1":
tv.toggle_power()
elif choice=="2":
change=int(raw_input("What would you like to change the channel to? "))
tv.set_channel(change)
elif choice=="3":
tv.raise_volume()
elif choice=="4":
tv.lower_volume()
else:
raise ValueError("Sorry, but {0} isn't a valid choice.".format(choice))
except ValueError as e:
print ' *** ERROR: {0} '.format(e)
main()
raw_input("Press enter to exit.")
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.