r/learnpython • u/Lance_2564_ • Oct 30 '26
Any python module which deals with this?
def get_int_input(prompt: str) -> int:
while True:
try:
return int(input(prompt))
except ValueError:
print("Please enter a valid number!")Is there any module which I can just import and use it. Writing this everytime I have to get an int or float input is really annoying.
Thanks!
0
Upvotes
16
u/johlae Oct 30 '26
34
u/zanfar Oct 30 '26
It's a function... Why are you writing it multiple times?
16
u/odaiwai Oct 30 '26
Now that you have the function definition as shown above, you can just import it into any python script that requires it.
So you don't need to define it in every script you need it in.
5
u/This_Growth2898 Oct 30 '26
It's only common in very basic learning tasks, and the actual detail can be very different (do you need to print the message? Or maybe return an error? Or put the message into some window in GUI? Do you need to repeat it forever, or three times and exit? etc.), so you'd better make your own library for your needs if you think it's worth it.
3
u/mattynmax Oct 30 '26
What? It’s a function? Use it like a function?
2
u/JanEric1 Oct 30 '26
I think lisp is the only language I have seen that has this built in.
But as others have said,n just reuse that function
2
u/Sure-Passion2224 Oct 30 '26
Why not just save a cluster of these common actions as your own library?
1
u/BranchLatter4294 Oct 30 '26
If you wrote this, then you already have a module. Just import the file and use the function you already wrote.
1
u/3MU6quo0pC7du5YPBGBI Oct 30 '26 edited Oct 30 '26
You can just import it into your other python scripts by calling the script and function as long as it is in your path.
To keep things from getting too crazy you might want to create a python file that has all your commonly used functions and call it something like my_common_functions.py, so you aren't doing something confusing like importing from 10 different scripts to get all your functions.
e.g. do this:
and not this:
1
u/Gnaxe Oct 30 '26
That's a pretty tedious way of entering numbers, and it isn't done that way very much (except maybe in beginner classes). For entering a lot of numbers, you'd probably read them from a file, which you could create with a proper editor. For simple parameters, you'd enter them at the command line when starting the program (read from
sys.argvor useargparse). If that fails, you abort the whole script. For wizard-like interactivity, you might use tkinter and events, you might abort the script, or you might do something like you're doing, but reuse the function. Or you might have something like a shell or REPL, which would ask for the next command even if one fails.1
u/TheRNGuy Oct 31 '26
Use UI framework for that.Â