Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #52069

Re: Beginner question

References <6e80b2f8-0b14-43cd-b8af-211ef65d73ba@googlegroups.com>
Date 2013-08-06 23:10 +0100
Subject Re: Beginner question
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.274.1375827040.1251.python-list@python.org> (permalink)

Show all headers | View raw


On Tue, Aug 6, 2013 at 10:35 PM,  <eschneider92@comcast.net> wrote:
> Why won't the 'goodbye' part of this code work right? it prints 'ok' no matter what is typed. Much thanks.
>
> def thing():
>     print('go again?')
>     goagain=input()
>     if goagain=='y' or 'yes':
>         print('ok')
>     elif goagain!='y' or 'yes':
>         print('goodbye')
>         sys.exit()
> thing()

When you use 'or' in this way, it's not doing what you think it does.
It actually first computes

>>> goagain=='y'

which is either True or False, and then evaluates the next part:

>>> True or 'yes'
>>> False or 'yes'

Try out those two in interactive Python and see what they do. You
probably want to compare in both halves of the test, or possibly use
the 'in' operator:

if goagain in ('y', 'yes'):

Also, you don't need an 'elif' there; just use a plain else. Repeating
the condition just introduces the chance of bugs - for instance, would
you notice the error in this?

    if goagain=='y' or goagain=='yes':
        print('ok')
    elif goagain!='y' or goagain!='yes':
        print('goodbye')

Using a plain 'else' guarantees that exactly one of the branches will
be executed, rather than having the possibility that neither will,
which isn't the intention here.

Hope that helps!

ChrisA

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Beginner question eschneider92@comcast.net - 2013-08-06 14:35 -0700
  Re: Beginner question Dave Angel <davea@davea.name> - 2013-08-06 22:03 +0000
  Re: Beginner question Chris Angelico <rosuav@gmail.com> - 2013-08-06 23:10 +0100
  Re: Beginner question "Rhodri James" <rhodri@wildebst.demon.co.uk> - 2013-08-06 23:14 +0100
  Re: Beginner question Chris Down <chris@chrisdown.name> - 2013-08-06 23:46 +0200
  Re: Beginner question eschneider92@comcast.net - 2013-08-06 20:06 -0700

csiph-web