I'm having trouble with a program I'm writing and any help would be greatly appreciated. I'm supposed to use an if statement to return an error message if the values entered aren't either the strings 'on' or 'off'. Right now I have

if (b1 and b2 and b3 and b4 != str('on') or b1 and b2 and b3 and b4 !=str('off')):
        print'You must enter either on or off for the button states.'

The problem is the program prints out the statement even if all the values entered are either the strings 'on' or 'off'. The program prints out the error statement whether theres an error or not. Im not sure what I am doing wrong and would really appreciate any help since I have to turn in this program tonight!
Thanks

Recommended Answers

All 6 Replies

return an error message if the values entered aren't either the strings 'on' or 'off'

Can you use a list instead of all of those variables? Otherwise, try the code below which tests each button individually instead of the confusing and, and, or, etc. in your code. Speaking of testing each button individually, it would be better to test each one as it is entered.

error_switch = False
for button in [b1, b2, b3, b4]:
    button = button.lower()
    if button != 'on' and button != 'off':
        error_switch = True
if error_switch:
    print 'You must enter either "on" or "off" for the button states.'

Edit: Do you know how and why
for button in [ b1, b2, b3, b4]:
works? Post any ideas. You can not really use anything like this unless you understand it.

Never mind, I figured it out. Thanks though

Please ass "Solved" to the thread title so no one else wastes their time on this.

Member Avatar for sravan953

I hope pun not intended:

Please ass "Solved"...

lol
:)

To test if all buttons are 'on' you can simplify to this ...

b1 = 'on'
b2 = 'on'
b3 = 'on'
b4 = 'on'

if b1 == b2 == b3 == b4 == 'on':
    print 'all buttons on'

Conversely you can do the same thing for 'off'.

Functions any() and all() were introduced with Python25, they make the problem a little easier to understand ...

# test if all buttons are on or off
on = True
off = False

b1 = on
b2 = on
b3 = on
b4 = off

if all([b1, b2, b3, b4]):
    print( "all buttons on" )
elif any([b1, b2, b3, b4]):
    print( "need to turn all buttons on or off!" )
else:
    print( "all buttons off" )

I hope pun not intended:
Please ass "Solved"...

I'll save the pun for one of your posts. And it's now too late to change it. Oh well, we'll just have to let this thread wind down the list into obscurity.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.