Deep Dive into inputNum()
with Examples and Outputs
This post explores inputNum()
from PyInputPlus with basic-to-moderate examples, demonstrating how to validate numeric input, enforce ranges, handle timeouts/limits, and more.
Why Use inputNum()
?
Instead of using input()
plus manual conversion and try/except for numeric validation, inputNum()
automatically ensures the user enters a valid number (int or float). It also supports parameters like min
, max
, greaterThan
, lessThan
, limit
, timeout
, and default
to streamline your input-handling logic.
import pyinputplus as pyip
# Basic numeric input: automatically retries until a valid number is entered.
num = pyip.inputNum("Enter any number: ")
print(f"Received number: {num} (type: {type(num)})")
Sample Interaction & Output:
Enter any number: abc
'abc' is not a number.
Enter any number: 42
Received number: 42 (type: <class 'int'>)
Allow Only Integers or Floats Explicitly
By default, inputNum()
accepts integers and floats. If you want strictly integers, use inputInt()
; for strictly floats, use inputFloat()
. But if you want to accept both, inputNum()
is convenient:
import pyinputplus as pyip
value = pyip.inputNum("Enter integer or float: ")
print(f"Value: {value} (type: {type(value)})")
# If you need only integers:
int_value = pyip.inputInt("Enter integer only: ")
# If you need only floats:
float_value = pyip.inputFloat("Enter float only: ")
Sample Interaction & Output:
Enter integer or float: 3.14
Value: 3.14 (type: <class 'float'>)
Enter integer only: 5
Enter float only: five
'five' is not a number.
Enter float only: 2.718
Enforce a Range with min
and max
Require the entered number to lie within a specified inclusive range. Useful for age checks, menu selections, etc.
import pyinputplus as pyip
# Example: age between 18 and 65 inclusive
age = pyip.inputNum("Enter your age (18–65): ", min=18, max=65)
print(f"Age accepted: {age}")
Sample Interaction & Output:
Enter your age (18–65): 17
Number must be at minimum 18.
Enter your age (18–65): seventy
'seventy' is not a number.
Enter your age (18–65): 30
Age accepted: 30
Use greaterThan
and lessThan
for Exclusive Bounds
If you need strict inequalities (exclusive), use greaterThan
and/or lessThan
:
import pyinputplus as pyip
# Strictly greater than 0 and strictly less than 1
frac = pyip.inputNum("Enter a fraction between 0 and 1 (exclusive): ", greaterThan=0, lessThan=1)
print(f"You entered: {frac}")
Sample Interaction & Output:
Enter a fraction between 0 and 1 (exclusive): 0
Number must be greater than 0.
Enter a fraction between 0 and 1 (exclusive): 1
Number must be less than 1.
Enter a fraction between 0 and 1 (exclusive): 0.5
You entered: 0.5
Custom Error Messages with errorMsg
You can override the default messages when validation fails:
import pyinputplus as pyip
# Custom message for out-of-range
num = pyip.inputNum(
"Pick a number from 1 to 10: ",
min=1, max=10,
errorMsg="Please enter a valid number between 1 and 10!"
)
print(f"Chosen: {num}")
Sample Interaction & Output:
Pick a number from 1 to 10: 11
Please enter a valid number between 1 and 10!
Pick a number from 1 to 10: abc
'abc' is not a number.
Pick a number from 1 to 10: 7
Chosen: 7
Limit Attempts with limit
and default
Allow only a certain number of invalid attempts; after exceeding, return a default value:
import pyinputplus as pyip
# Only 2 invalid attempts, then default of -1
num = pyip.inputNum(
"Enter priority (1-5): ",
min=1, max=5,
limit=2, default=-1
)
print(f"Priority: {num}")
Sample Interaction & Output:
Enter priority (1-5): 0
Number must be at minimum 1.
Enter priority (1-5): 10
Number must be at maximum 5.
Priority: -1
Or if valid within attempts:
Enter priority (1-5): 3
Priority: 3
Timeout with timeout
and default
Wait for input up to a specified number of seconds; if the user does not respond in time, return the default
(or raise TimeoutException
if no default provided):
import pyinputplus as pyip
# Wait up to 4 seconds; use -1 if timed out
try:
num = pyip.inputNum(
"Enter a number within 4 seconds: ",
timeout=4, default=-1
)
except pyip.TimeoutException:
num = -1
print("Timed out; default used.")
print(f"Result: {num}")
Sample Interaction & Output (timeout):
Enter a number within 4 seconds:
(no input for 4 seconds)
Result: -1
Sample Interaction & Output (valid input):
Enter a number within 4 seconds: 12
Result: 12
Combine min/max
, greaterThan/lessThan
, limit
, timeout
, and default
Examples combining multiple parameters for robust input handling:
import pyinputplus as pyip
# Example: optional discount percentage: allow blank entry, otherwise between 0 and 100
discount = pyip.inputNum(
"Enter discount % (0–100) or wait 3s for default: ",
min=0, max=100,
timeout=3, default=0
)
print(f"Discount: {discount}%")
Sample Interaction & Output (timeout):
Enter discount % (0–100) or wait 3s for default:
Discount: 0%
Sample Interaction & Output (valid entry):
Enter discount % (0–100) or wait 3s for default: 25
Discount: 25%
Happy coding!
π Related Topics from PyInputPlus:
- ➤ Introduction to PyInputPlus
- ➤ inputStr() from PyInputPlus
- ➤ inputNum() from PyInputPlus
- ➤ inputChoice() from PyInputPlus
- ➤ inputMenu() from PyInputPlus
- ➤ Other Important PyInputPlus Functions
πTrending Topics
π Connect With Us:
“In the world of code, Python is the language of simplicity, where logic meets creativity, and every line brings us closer to our goals.”— Only Python
π Follow Us And Stay Updated For Daily Updates
Comments
Post a Comment