Python Forum
restrict user input to numerical values - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: restrict user input to numerical values (/thread-39751.html)



restrict user input to numerical values - MCL169 - Apr-08-2023

while True:
    year = input('please enter a 4-digit year: ')

    digit = len(year)

    if digit != 4 and year != int:
        print("sorry, that was bad input")
    else:
        print(f"thanks ! your value is {year}")
        break
I want to only except 4 character inputs or display error with the prompt again, which is working but i also need input to be only numeric values. Len wont work on int so im stuck.


RE: restrict user input to numerical values - Yoriz - Apr-08-2023

Maybe you could use the strings isdigit method
if digit != 4  or not year.isdigit():



RE: restrict user input to numerical values - MCL169 - Apr-08-2023

(Apr-08-2023, 05:00 PM)Yoriz Wrote: Maybe you could use the strings isdigit method
if digit != 4  or not year.isdigit():
That did the trick Thanks!