Yes or No output Python

Question:

Join = input('Would you like to join me?')
if Join == 'yes' or 'Yes':
  print("Great," + myName + '!')
else:
  print ("Sorry for asking...")

So this is my code. It’s longer; just including the problem. I’m asking a yes or no question and when in the console it runs smoothly until you get to it. Whatever you type you get the ‘yes’ output. Could someone please help? I’ve used elif statements as well but no luck.

Asked By: Ross Hudson

||

Answers:

That’s not how the or operator works. Replace:

if Join == 'yes' or 'Yes':

with:

if Join in ['yes', 'Yes']:

and it’ll do what you want.

EDIT: Or try this, for more general purpose:

if 'yes'.startswith(Join.lower()):

which ought to match ‘y’, ‘Y’, ‘ye’, ‘Ye’, ‘YE’, and so on.

Answered By: Crowman
if Join == 'yes' or 'Yes':

This is always true. Python reads it as:

if (Join == 'yes') or 'Yes':

The second half of the or, being a non-empty string, is always true, so the whole expression is always true because anything or true is true.

You can fix this by explicitly comparing Join to both values:

if Join == 'yes' or Join == 'Yes':

But in this particular case I would suggest the best way to write it is this:

if Join.lower() == 'yes':

This way the case of what the user enters does not matter, it is converted to lowercase and tested against a lowercase value. If you intend to use the variable Join elsewhere it may be convenient to lowercase it when it is input instead:

Join = input('Would you like to join me?').lower()
if Join == 'yes':   # etc.

You could also write it so that the user can enter anything that begins with y or indeed, just y:

Join = input('Would you like to join me?').lower()
if Join.startswith('y'):   # etc.
Answered By: kindall

The if statement should actually be:

if Join=='yes' or Join =='Yes'

The way the if statement is written in your code will cause code to be evaluated this way:

(if Join == 'yes') or ('Yes'):

Note that (‘Yes’) is a truthy and will always evaluate to true

Answered By: Prahalad Deshpande

I answered this question yesterday

You can use .lower()

Join = input('Would you like to join me?')
if Join.lower() == 'yes':
  print("Great," + myName + '!')
else:
  print ("Sorry for asking...")
Answered By: Stephan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.