[Tutor] On off Toggle

Alan Gauld alan.gauld at btinternet.com
Sat Mar 12 11:08:51 CET 2011


"Adrian Atkinson" <admatkin at umail.iu.edu> wrote

> class Television(object):

While using a class is not in itself a bad idea it looks like
you have much more fundamental issues to deal with so
I'd suggest dropping the  class for now and just write
some functions using global variables to store the data.
You can then move that into a class later if you need to.
It will simplify the problem because you have a mixture
of OO issues and basic programming issues. Lets
fix the basics befoere worrying about the OO bits.

>    def __init__(self,__channel,volume,is_on):
>        self.volume = volume
>        self.is_on = "Power is off"
>        power = self.is_on

Its usually better not to use strings for this kind of task.
is_on is a boolean type value - its either on or its off so
is better rep[resented by a number or a simple True/False
boolean variable.

Power in this case does nothing because after you
assign it you throw it away when you leave the function.
This is one of the areas where using globals would help
simplify the problem.

>    def toggle_power(self):
>
>        if choice == "1" and power == self.is_on  :
>            power = "Power is Now on"
>        elif choice =="1" and power =="Power is Now on" :
>            power = self.is_on
>        print power

I have no idea what you think is happening here.
Can you describe in plain English how you think this
should work? When you call Toggle Power what would
you expect the program to do? What would be printed
and what would the data look like?

> choice = ""
> while choice != 0:
>    choice = raw_input("Can I have a selection number? : ")
>    tv = Television(0,50,"is_on")
>    tv.toggle_power()

Be careful about data types. choice starts as a string(empty)
then is compared to a number(0) then is set to a string
using raw_input().

Also you instantiate the tv object by passing 2 values
but the constructor expects 3...

> I'm trying to make a toggle to turn the power on and off in the 
> toggle_power
> method but I cannot figure  this out. Any help would be greatly 
> appreciated

First express exactly what you want the toggle to do in English.
Think about the data and the printed output - they are quite different 
things.

Then come back to us for more help.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list