我想呼叫 function 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'
用戶輸入時如何引發 TypeError k8?如果用戶輸入,情況如何k8 9 5h?在這種情況下,我需要使用訊息引發 TypeErrorThe type of 1, 3 element is incorrect
uj5u.com熱心網友回復:
這應該這樣做:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/382749.html
上一篇:您如何在pythontkinter中將.get()與多幀購物車一起使用?
下一篇:捕捉到我不想捕捉的錯誤
