MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / valid_input

Function valid_input

machine_learning/linear_discriminant_analysis.py:251–279  ·  view source on GitHub ↗

Ask for user value and validate that it fulfill a condition. :input_type: user input expected type of value :input_msg: message to show user in the screen :err_msg: message to show in the screen in case of error :condition: function that represents the condition that user input

(
    input_type: Callable[[object], num],  # Usually float or int
    input_msg: str,
    err_msg: str,
    condition: Callable[[num], bool] = lambda _: True,
    default: str | None = None,
)

Source from the content-addressed store, hash-verified

249
250
251def valid_input[num](
252 input_type: Callable[[object], num], # Usually float or int
253 input_msg: str,
254 err_msg: str,
255 condition: Callable[[num], bool] = lambda _: True,
256 default: str | None = None,
257) -> num:
258 """
259 Ask for user value and validate that it fulfill a condition.
260
261 :input_type: user input expected type of value
262 :input_msg: message to show user in the screen
263 :err_msg: message to show in the screen in case of error
264 :condition: function that represents the condition that user input is valid.
265 :default: Default value in case the user does not type anything
266 :return: user's input
267 """
268 while True:
269 try:
270 user_input = input_type(input(input_msg).strip() or default)
271 if condition(user_input):
272 return user_input
273 else:
274 print(f"{user_input}: {err_msg}")
275 continue
276 except ValueError:
277 print(
278 f"{user_input}: Incorrect input type, expected {input_type.__name__!r}"
279 )
280
281
282# Main Function

Callers 1

mainFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected