1

Ok the title is a bit weird. But, basically what i want to ask is:

read = input("Enter some numbers: ")
# The user should only enter numbers and nothing else

But the thing is the user can enter something else other than a numerical value. How do i stop someone from entering an alphabet in realtime from the terminal?

Lets say the user inputs 123 then enters an "e". How do i make this e not even appear on the terminal even if the user presses the e key?

user69420
  • 11
  • 2
  • 1
    You can't do it when using the `input` function, Python only gets to see the value after the user has pressed Enter. – mkrieger1 Oct 11 '22 at 16:19
  • Does this answer your question? [How can I limit the user input to only integers in Python](https://stackoverflow.com/questions/23326099/how-can-i-limit-the-user-input-to-only-integers-in-python) – sneeu Oct 11 '22 at 16:20
  • 1
    Does this answer your question? [How to read a single character from the user?](https://stackoverflow.com/questions/510357/how-to-read-a-single-character-from-the-user), and then https://stackoverflow.com/questions/40097590/detect-whether-a-python-string-is-a-number-or-a-letter – mkrieger1 Oct 11 '22 at 16:21
  • OK. But is there any way? Like using the keybord module in python? Or some other module. But thanks anyway. – user69420 Oct 11 '22 at 16:27
  • 'How do i make this e not even appear on the terminal even if the user presses the e key?' - that task seems to be something really hard and deep. there is hardly some python module that can manipulate your OS on that level. – Dmitriy Neledva Oct 11 '22 at 16:34

1 Answers1

1

you can repeat asking int values if user enters a string.

while True:
    try:
        # ️ use int() instead of float
        # if you only accept integers
        num = float(input('Your favorite number: '))
        print(num)
        break
    except ValueError:
        print('Please enter a number.')