I'd like to call function foo(a, b, c)
, where arguments can be int
or float
Those arguments user inputs using space
as a separator.
For example: 1 8 9
In the same time user can input not only digits, bit make some typo like:
1 8k 9
.
In this case I should raise TypeError and type the number of incorrect element
a, b, c = map(int, input().split())
for i, key in enumerate([a, b, c]):
if not isinstance(key, (int, float)):
raise TypeError(
f'The type of {i 1} element is incorrect')
foo(float(a), float(b), float(c))
In my code I have the next error: i can't write k8
into int
variable.
1 k8 5
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\digits\main.py", line 40, in <module>
a, b, c = map(int, input().split())
ValueError: invalid literal for int() with base 10: 'k8'
How can I raise the TypeError when user input k8
?
And how to be in situation if user inputs k8 9 5h
? I that case I need to Raise the TypeError with message The type of 1, 3 element is incorrect
CodePudding user response:
This ought to do it:
args = input().split()
f_args = []
errors = []
for i, arg in enumerate(args, 1):
try:
f_args.append(float(arg))
except ValueError:
errors.append(str(i))
if errors:
raise TypeError(f"The type of {', '.join(errors)} element is incorrect")
foo(*f_args)