我必須在 Python 中創建一個函式,將鍵盤字母與其對應的數字(不包括 1 和 0)相匹配。當我運行我的代碼并輸入一個字母時,我得到了正確的匹配,但我也得到了(letter,"matches",None)
它下面的一行。我做錯了什么,我需要修復什么以確保不會出現 None 行?代碼:
def keypad(ch):
if ch == "A" or ch == "a" or ch == "B" or ch == "b" or ch == "C" or ch == "c":
print(ch,"matches",2)
elif ch == "D" or ch == "d" or ch == "E" or ch == "e" or ch == "F" or ch == "f":
print(ch,"matches",3)
s = str(input("Enter a letter:"))
print(s,"matches",keypad(s))
示例輸出:
Enter a letter:D
D matches 3
D matches None
uj5u.com熱心網友回復:
您的keypad
函式呼叫print
,這是您看到的第一條輸出行。由于它沒有顯式回傳任何內容,因此它隱式回傳None
,然后您將print
在最后一行代碼中回傳。
簡而言之,print
從您上次通話中洗掉:
s = str(input("Enter a letter:"))
keypad(s)
uj5u.com熱心網友回復:
您的函式沒有回傳任何內容,因此它隱式回傳 None。
您正在函式中列印,因此“D 匹配 3”的列印。
您正在函式之外列印,因此“D 匹配無”的列印。
uj5u.com熱心網友回復:
您正在列印呼叫的回傳值keypad(s)
,它本身會列印第一行。不要列印回傳值,而只需使用 呼叫函式keypad(s)
,或者讓函式回傳需要列印的內容并且不讓它自己列印任何內容。
所以,要么:
def keypad(ch):
if ch == "A" or ch == "a" or ch == "B" or ch == "b" or ch == "C" or ch == "c":
print(ch,"matches",2)
elif ch == "D" or ch == "d" or ch == "E" or ch == "e" or ch == "F" or ch == "f":
print(ch,"matches",3)
s = str(input("Enter a letter:"))
keypad(s)
或者:
def keypad(ch):
if ch == "A" or ch == "a" or ch == "B" or ch == "b" or ch == "C" or ch == "c":
return 2
elif ch == "D" or ch == "d" or ch == "E" or ch == "e" or ch == "F" or ch == "f":
return 3
s = str(input("Enter a letter:"))
print(s, "matches", keypad(s))
更好的是:
def keypad(ch):
return 2 if ch.lower() in 'abc' else 3 if ch.lower() in 'def' else None
s = str(input("Enter a letter:"))
print(s, "matches", keypad(s))
請注意,當您輸入除'a'
through以外的任何內容時,第一個和第二個解決方案是不同的'f'
。如果您不想在這種情況下列印任何東西,第一個解決方案是最好的,這是它的簡短版本:
def keypad(ch):
result = 2 if ch.lower() in 'abc' else 3 if ch.lower() in 'def' else None
if result is not None:
print(s, "matches", result)
s = str(input("Enter a letter:"))
keypad(s)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/506852.html