Simple Yes or No Loop Python3

Simple Yes or No Loop Python3

You are first calling yes_or_no, which outputs a value but you throw it away and are calling the function again instead of testing on the output of the first call.

Try storing the output in a variable.

# Store the output in a variable
answer = yes_or_no()

# Conditional on the stored value
if answer == 1:
print("You said yeah!")

else:
print("You said nah!")

Sidenotes

It is considered bad pratice to use capitalized names for variables, those should be reserved for classes.

Also, a user-prompt loop is better implemented with a while-loop to avoid adding a frame to your call-stack everytime the user enters a wrong input.

Here is what an improved version of your function could look like.

def yes_or_no():
while True:
answer = input("Yes or No?").lower()

if answer == "yes":
return 1

elif answer == "no":
return 0

Yes or No output Python

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.

APT command line interface-like yes/no input?

As you mentioned, the easiest way is to use raw_input() (or simply input() for Python 3). There is no built-in way to do this. From Recipe 577058:

import sys


def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.

"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).

The "answer" return value is True for "yes" or False for "no".
"""
valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)

while True:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == "":
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n")

(For Python 2, use raw_input instead of input.)
Usage example:

>>> query_yes_no("Is cabbage yummier than cauliflower?")
Is cabbage yummier than cauliflower? [Y/n] oops
Please respond with 'yes' or 'no' (or 'y' or 'n').
Is cabbage yummier than cauliflower? [Y/n] [ENTER]
>>> True

>>> query_yes_no("Is cabbage yummier than cauliflower?", None)
Is cabbage yummier than cauliflower? [y/n] [ENTER]
Please respond with 'yes' or 'no' (or 'y' or 'n').
Is cabbage yummier than cauliflower? [y/n] y
>>> True

While Loop With Yes/No Input (Python)

Try:

def yes_or_no(question):
reply = str(input(question+' (y/n): ')).lower().strip()
if reply[0] == 'y':
return 1
elif reply[0] == 'n':
return 0
else:
return yes_or_no("Please Enter (y/n) ")

print("started")
while True:
# DRAW PLOT HERE;
print("See plot....")
if(yes_or_no('Do you like the plot')):
break
print("done")

Best to keep function definition separate from loop for clarity. Also, otherwise it will be read in every loop wasting resources.

Output:

$ python ynquestion.py 
started
See plot....
Do you like the plot (y/n): n
See plot....
Do you like the plot (y/n): N
See plot....
Do you like the plot (y/n): NO
See plot....
Do you like the plot (y/n): No
See plot....
Do you like the plot (y/n): no
See plot....
Do you like the plot (y/n): yes
done
$

If condition is "None" the loop starts somewhere else than I want

I would approach this with a pair of recursive functions. One that ran until the user gave a valid response, the other until a name was properly set.

Note that in many cases, recursive functions can be rewritten as loops and since python lacks tail call optimization, some people will prefer not using recursion. I think it is usually fine to do so though.

def get_input_restricted(prompt, allowed_responses):
choice = input(prompt)
if choice in allowed_responses:
return choice

print(f"\"{choice}\" must be one of {allowed_responses}")
return get_input_restricted(prompt, allowed_responses)

def set_character_name():
prospective_name = input("Enter a name for your character: ")
print(f"Your name will be: {prospective_name}.")

confirmation = get_input_restricted("Are you happy with your choice (y|n)? ", ["y", "n"])
if "y" == confirmation:
return prospective_name

return set_character_name()

character_name = set_character_name()
print(f"I am your character. Call me {character_name}.")

While loop (really simple)

change this:

while temp!="1" or temp!="2":

to this:

while temp!="1" and temp!="2":


Related Topics



Leave a reply



Submit