In Python, we can use a variety of methods to limit the range of numerical values entered by the user.
1. Usewhile
Loop andtry-except
Methods of statements
The following is a usewhile
Loop andtry-except
An example of a statement that will require the user to enter an integer within the specified range.
Suppose we want to limit the number of user inputs between 1 and 100 (including 1 and 100):
def get_valid_input(min_value, max_value): """ Gets a valid integer input within the specified range parameter: min_value (int): Minimum allowed value max_value (int): Maximum allowed return: int: Integers entered by the user within the specified range Throw out: ValueError: If the user input is not an integer or is not within the specified range """ while True: try: # Try to convert user input to integer user_input = int(input(f"Please enter one{min_value}arrive{max_value}Integer between: ")) # Check whether the integer is within the specified range if min_value <= user_input <= max_value: return user_input # If the input is valid, return it else: print(f"Invalid input,Please enter one{min_value}arrive{max_value}Integer between。") except ValueError: # If the user inputs not an integer, capture the ValueError and prompt the user to re-enter. print("Input is invalid, please enter an integer.") # Use functions to get user inputvalid_input = get_valid_input(1, 100) print(f"The valid number we entered is: {valid_input}")
In this example,get_valid_input
The function will loop continuously until the user enters an integer within the specified range. If the user inputs not an integer, or the input integer is not within the specified range, the function will print out the corresponding error message and prompt the user to re-enter. Once the user has entered a valid integer, the function returns the integer and exits the loop.
2. Useinput()
Function and conditional judgment
def get_valid_input(min_value, max_value): while True: user_input = input(f"Please enter one{min_value}arrive{max_value}Integer between: ") if not user_input.isdigit(): print("Input is invalid, please enter an integer.") continue user_input = int(user_input) if min_value <= user_input <= max_value: return user_input else: print(f"Invalid input,Please enter one{min_value}arrive{max_value}Integer between。") # Use functions to get user inputvalid_input = get_valid_input(1, 100) print(f"The valid number we entered is: {valid_input}")
3. Useinput()
Functions andint(input(), base)
(For hexadecimal inputs)
If we need to process input from other bits (such as hexadecimal), we can useint()
Functionalbase
parameter. Note, however, that this is not usually used to limit the input range, but to interpret different numerical representations.
def get_hex_input(): while True: user_input = input("Please enter a hexadecimal number (0-9, A-F): ") try: hex_value = int(user_input, 16) print(f"The decimal number corresponding to the hexadecimal number you entered is: {hex_value}") return hex_value # If it's just an example, you may not need to return a value except ValueError: print("The input is invalid, please enter a valid hexadecimal number.") # Use functions to get user input# Note: There is no scope limit here, because the hexadecimal number can be very largehex_input = get_hex_input() # Because this example just shows how to handle hexadecimal input,So there is no follow-up operation
4. Use the graphical user interface (GUI) library
If we are developing a graphical user interface application, we can use GUI libraries such as Tkinter, PyQt, wxPython, etc. to create an input box with scope limitations. These libraries usually provide methods to verify input.
5. Use third-party libraries
Some third-party libraries (e.g.prompt_toolkit
) provides more advanced input processing functions, including input verification and automatic completion.
6. Command line parameter processing
If our script receives input through command line parameters, we can useargparse
The module parses the parameters and sets the scope limits of the parameters.
import argparse def main(args): if not ( >= 1 and <= 100): print("The number of inputs must be between 1 and 100.") return print(f"The number you entered is: {}") if __name__ == "__main__": parser = (description="Processing command line parameters") parser.add_argument("--number", type=int, help="Enter an integer") args = parser.parse_args() main(args)
Form verification in the application
If we are developing a web application, we can use HTML formsmin
andmax
properties, as well as input validation for JavaScript or backend languages such as Python's Flask or Django.
def validate_number_from_file(file_path, min_value, max_value): with open(file_path, 'r') as file: for line in file: number = int(()) # Assume that there is only one integer per line and no extra characters if min_value <= number <= max_value: print(f"Valid numbers: {number}") else: print(f"Invalid number: {number},Not here{min_value}arrive{max_value}between。") # Use functions to read and verify numbers from filesvalidate_number_from_file('', 1, 100)
8. Verification when reading files or databases
If we read data from a file or database and want this data to be within a specific range, we can verify it after reading.
Each method has its applicable scenarios and advantages and disadvantages. Which method to choose depends on our specific needs and context. In most cases, useinput()
Function and conditional judgment are the easiest and most direct methods.
This is the article about the number range of Python restricted input. For more information about Python restricted input, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!