0

How do I fix the code below to print only a valid input:

x = input("Y/N? ")
while x not in ["Y","N"]:
    x = input("Y/N? ")

If I enter invalid input, this one prints

 Y/N? what
 Y/N? is
 Y/N? Y

Instead of printing invalid input like what or is, I want to only print Y.

  • 3
    It's not printing the input. That's just the user's typing being echoed as they type it. – Barmar Nov 16 '21 at 23:32
  • You called `input()` with prompt message, entered text and want all this to disappear? – Olvin Roght Nov 16 '21 at 23:32
  • @Barmar Ok, that makes sense. Then maybe my question is wrong. I guess my question then is, Is there a way to get user input without having it shown on screen? –  Nov 16 '21 at 23:45
  • See https://stackoverflow.com/questions/4616813/can-i-get-console-input-without-echo-in-python. This is normally only used for passwords. – Barmar Nov 16 '21 at 23:46
  • @Barmar That would still print a new empty line every time the person failer to enter Y/N. If you're looking for single key inputs you could look into keyboard events – OmO Walker Nov 16 '21 at 23:48
  • @OmOWalker If you do that, then you also need to handle all the input editing yourself, too. – Barmar Nov 16 '21 at 23:49

2 Answers2

1

Your code is actually not printing anything. All you see in your terminal window is the input you asked the user to enter. When you call input("Message") in python, the message gets printed to the terminal and awaits user's input

input("Please enter Y/N: ")

> [input]: Please enter Y/N: ...

At this point, if you type "what", your for loop checks if it's in the list you provided. Since it's not there it prints the input message again. In Your case, it prints the message 3 times before you enter the correct value.

To see the program succeed you could print something at the end

x = input("Y/N? ")

while x not in ["Y","N"]:
    x = input("Please enter Y/N: ")
print("YaY, you finally entered:", x)

Will output:

> [input] Please enter Y/N: what
> [input] Please enter Y/N: is
> [input] Please enter Y/N: Y
> [output] YaY, you finally entered: Y
OmO Walker
  • 611
  • 6
  • 13
0

It's not printing the input, that's what the user is typing. If you want it in a seperate line, add \n right after the ? in the string. If you want it to print the values, only if they are correct, you can use a boolean and continuously check if it has been updated.

bool = False
while not bool:
   x = input("Y/N?\n")
   if x.lower() == "y" or x.lower() == "n":
      bool = True
#do whatever else you want
Craze XD
  • 110
  • 8