Reputation: 11
The while loop asks for the input twice, even when the input is within the specified lists. I need help to figure out a better method or fix to this
I am new to python, so please be nice ;), I haven't really tried an awful lot because I don't know how else i'd do it.
Y_list = ("Y")
N_list = ("N")
user_choice = input("Y / N")
while user_choice not in Y_list or N_list:
user_choice = input("Y / N")
if user_choice in Y_list:
print("U said Y")
elif user_choice in N_list:
print("U said N")
I want there to only ask the question once unless the user inputs something not in the Y list or N list
Upvotes: 1
Views: 1060
Reputation: 1324
Y_list = ("Y")
N_list = ("N")
user_choice = ""
while user_choice not in Y_list or N_list:
user_choice = input("Y / N")
if user_choice in Y_list:
print("U said Y")
elif user_choice in N_list:
print("U said N")
just initiate user choice by "". simple method.
Upvotes: 0
Reputation: 6331
I think you may want something like this:
Y_list = ("y", "yes", "yeah")
N_list = ("n", "no", "none")
while True:
user_choice = input("Y / N").lower()
if user_choice in Y_list:
print("U said Y")
break
elif user_choice in N_list:
print("U said N")
break
Upvotes: 1
Reputation: 1440
Your problem resides in your logical operation in the while condition. You're telling python to evaluate: user_choice not in Y_list
OR N_list
. The second part here is taken as a stand alone logical operation and since N_list
is not None, it will always be true. You need to explicitly specify your condition and then put an AND operator to make sure your input is not in both the lists.
Y_list = ["Y"]
N_list = ["N"]
user_choice = input("Y / N")
while user_choice not in Y_list and user_choice not in N_list:
user_choice = input("Y / N")
if user_choice in Y_list:
print("U said Y")
elif user_choice in N_list:
print("U said N")
Having said this, there are better ways to write this code but important to know why your initial approach didn't work.
Upvotes: 0
Reputation: 262
You would be better off writing something like
while True:
user_choice = input("Y / N")
user_choice = user_choice.lower()
if user_choice != "y" or user_choice != "n":
print("You entered something other than 'y' or 'n'.")
continue
else:
break
This essentially checks if the user has entered a 'y' or 'n' regardless of whether it's upper-case or lower-case. If it's something other than a 'y' or 'n' it goes to the top of the loop, otherwise, it just continues.
Upvotes: 0