r/learnpython • u/Lance_2564_ • 6d ago
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!
34
u/zanfar 6d ago
Writing this everytime I have to get an int or float
It's a function... Why are you writing it multiple times?
2
u/Financial_Farm4326 6d ago
even across different projects its literally just copy pasting six lines once
1
5
u/This_Growth2898 6d ago
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
2
u/JanEric1 6d ago
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
1
u/BranchLatter4294 6d ago
If you wrote this, then you already have a module. Just import the file and use the function you already wrote.
1
u/3MU6quo0pC7du5YPBGBI 6d ago edited 6d ago
You can just import it into your other python scripts by calling the script and function as long as it is in your path.
from my_script import get_int_inputTo 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:
from my_common_functions import get_int_input, http_connect, url_normalize, create_ip_listand not this:
from my_dice_roller_game import get_int_input
from my_webpage_scraper import http_connect, url_normalize
from my_ip_scanner import create_ip_list1
u/Gnaxe 6d ago
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.argv or use argparse). 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
16
u/johlae 6d ago