Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

python3 if not equal condition in OR statement

Status
Not open for further replies.

twantrd

Technical User
Feb 13, 2005
26
US
Hey guys,

Trying to figure out why my "not equals" operator doesn't work in this OR statement:

Code:
#!/usr/bin/env python3

import sys

readyprompt = input("Are you ready? [y/n]\n>")
ans = readyprompt.lower()
if ans != "y" or ans != "yes":
        print("Quitting. Please run " + sys.argv[0] + "when ready")
else:
        print("Executing scripts!")

Whatever I input, it always returns True. If I type in 'y' or 'yes', it should execute my else statement *scratches head*. I've tried putting my conditions into ()'s and such and no dice. Someone please show me the light :). Thanks!

 
Hi

twantrd said:
[tt]ans != "y" or ans != "yes"[/tt]
So either not "y" or not "yes" ? Let us reverse this : could you tell me a word that is both equal with "y" and with "yes" ? :)

I think you get it already - you need [tt]and[/tt] there : [tt]ans [teal]!=[/teal] [green]"y"[/green] and ans [teal]!=[/teal] [green]"yes"[/green][/tt].

In case you are ( excuse my assumption ) beginner, you may find easier to use equality checks instead then negate the entire expression : [tt]not [teal]([/teal]ans [teal]==[/teal] [green]"y"[/green] or ans [teal]==[/teal] [green]"yes"[/green][teal])[/teal][/tt]. ( I used them this way in my early years. YMMV. )

Feherke.
feherke.ga
 
Ah, I completely missed that. Thank you for clearing that up!
 
personally I would not check for a "Not" condition unless absolutely necessary as it makes code harder to read & maintain

Code:
if a=='y' of a=='yes':
[indent]do stuff[/indent]
else:
[indent]exit[/indent]

A Maintenance contract is essential, not a Luxury.
Do things on the cheap & it will cost you dear
 
Hi

Some coding standards says that if any of the branches does effectively nothing just exits, then that should be in the "then" branch and there should be no "else" branch. Personally I tend to agree with this rule as I find it makes my code easier to follow.
Python:
[b]if[/b] ans [teal]!=[/teal] [i][green]"y"[/green][/i] [b]or[/b] ans [teal]!=[/teal] [i][green]"yes"[/green][/i][teal]:[/teal]
        [COLOR=orange]exit[/color][teal]([/teal][i][green]"Quitting. Please run "[/green][/i] [teal]+[/teal] sys[teal].[/teal]argv[teal][[/teal][purple]0[/purple][teal]] +[/teal] [i][green]"when ready"[/green][/i][teal])[/teal]

[b]print[/b][teal]([/teal][i][green]"Executing scripts!"[/green][/i][teal])[/teal]

Feherke.
feherke.ga
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top