【发布时间】:2022-01-18 20:08:56
【问题描述】:
我想调用函数foo(a, b, c),其中参数可以是int 或float
这些参数用户输入使用space 作为分隔符。
例如:1 8 9
同时,用户不仅可以输入数字,还可以输入一些错字,例如:
1 8k 9。
在这种情况下,我应该提出 TypeError 并输入错误元素的数量
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))
在我的代码中出现下一个错误:我无法将k8 写入int 变量。
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'
当用户输入k8 时如何引发 TypeError?
如果用户输入k8 9 5h,情况如何?在这种情况下,我需要使用消息 The type of 1, 3 element is incorrect 引发 TypeError
【问题讨论】:
-
那么你必须在这行之前检查输入是否可以转换为float或int:
a, b, c = map(int, input().split()) -
如果允许浮动,为什么要使用
map(int, ...)?
标签: python exception typeerror