Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #52072
| Newsgroups | comp.lang.python |
|---|---|
| Subject | Re: Beginner question |
| References | <6e80b2f8-0b14-43cd-b8af-211ef65d73ba@googlegroups.com> |
| From | "Rhodri James" <rhodri@wildebst.demon.co.uk> |
| Organization | The Wildebestiary |
| Message-ID | <op.w1e1eniha8ncjz@gnudebeest> (permalink) |
| Date | 2013-08-06 23:14 +0100 |
On Tue, 06 Aug 2013 22:35:44 +0100, <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':
This line doesn't do what you think it does :-) Typing that condition at
an interactive prompt reveals something interesting:
>>> goagain = "n"
>>> goagain=="y"
False
>>> goagain=="y" or "yes"
'yes'
Oho. What's actually happening is that you've mistaken the operator
precedence. "==" has a higher precedence than "or", so your condition is
equivalent to '(goagain=="y") or "yes"'. Since it's left-hand argument is
False, "or" returns its right-hand argument, which has the value 'yes',
which in a boolean context is "True".
What you seem to want to do is to have your condition be true if goagain
is either "y" or "yes". Probably the easiest way of doing this and
learning something new at the same time is to ask if goagain appears in a
list (or rather a tuple) of strings:
if goagain in ('y', 'yes'):
print('ok')
elif goagain not in ('y', 'yes'):
print('goodbye')
sys.exit()
or better,
if goagain in ('y', 'yes', 'ohdeargodyes', 'you get the idea'):
print('ok')
else:
print('goodbye')
sys.exit()
--
Rhodri James *-* Wildebeest Herder to the Masses
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll 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