Oct-26-2022, 08:30 PM
I tend to use a custom function when checking any (and all) user input.
As a simple example:
That function can be coded to return anything you choose (such as an error message) and do whatever checks you want, such as checking that a number is within a certain range.
Clearly, as is, the number being printed is a string object, but again, the function could return a int, or a float, or the object type can be changed after it has been returned; it's a matter of choice.
As a simple example:
def check_input(n): """check the user input for a valid number. if valid, return the number, otherwise return 'None'""" for number in n: if number.isnumeric(): pass else: return None return n user_input = check_input(input("Pick a number: ")) if user_input: print(f"You picked {user_input}") else: print("Not valid.\nNumbers need to be whole (no decimal point)")
That function can be coded to return anything you choose (such as an error message) and do whatever checks you want, such as checking that a number is within a certain range.
Clearly, as is, the number being printed is a string object, but again, the function could return a int, or a float, or the object type can be changed after it has been returned; it's a matter of choice.
Sig:
>>> import this
The UNIX philosophy: "Do one thing, and do it well."
"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse
"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
>>> import this
The UNIX philosophy: "Do one thing, and do it well."
"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse
"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein