無論輸入,功能始終打印「輸入號碼」的「其他人」。爲什麼我的函數返回一個聲明,而不是「而」
def AddNum(n1, n2, n3, n4):
while n1 and n2 and n3 and n4 == int:
x = n1 + n2 + n3 + n4
return x
else:
print("Enter a number.")
無論輸入,功能始終打印「輸入號碼」的「其他人」。爲什麼我的函數返回一個聲明,而不是「而」
def AddNum(n1, n2, n3, n4):
while n1 and n2 and n3 and n4 == int:
x = n1 + n2 + n3 + n4
return x
else:
print("Enter a number.")
這是相當不清楚爲什麼你想要一個循環裏面,因爲一個簡單的if語句可以做到這一點。除此之外,這不是你如何做類型檢查 - 考慮使用isinstance()
。此外,您可能希望你的函數的參數任意數量的工作:
def add_num(*args):
if all(isinstance(arg, int) for arg in args):
return sum(args)
else:
return 'Arguments must be integers.'
...這可能還縮短爲:
def add_num(*args):
return sum(args) if all(isinstance(arg, int) for arg in args) else 'Arguments must be integers.'
>>> add_num('spam', 1)
Arguments must be integers.
>>> add_num(1, 2)
3
>>> add_num(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
55
您可能也想當涉及到函數時,請閱讀有關命名約定的what PEP8 says。
https://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values可能會幫助你理解爲什麼像'a和b和c == x'唐建做你認爲他們做的事。 –