Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Raising TypeError when type is not correct

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading