[英]What am I doing wrong in my code python that it won't print the totall cost?
[英]Python won't print what I tell it to
score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
"f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
"l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
"r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
"x": 8, "z": 10}
def scrabble_score(word):
total = []
for x in word:
total.append(score[x.lower()])
total_1 = sum(total)
return total_1
print total_1
scrabble_score('Hey')
好的。 因此,我試圖將其打印出來。 基本上,這需要一個單詞,並加上該單詞的拼字游戲分數。 由於某種原因,它不會打印出來。
return
將把程序的控制權返回給調用者。 過去的任何東西(基本上)都是無法訪問的代碼。
反轉語句的順序,您的print
語句將起作用:
print total_1
return total_1
這是無效的代碼-盡管可以編譯,但是這是特殊的,因為其他編程語言會當場將其標記為錯誤:
return total_1
print total_1 # unreachable code, function ends with return on previous line
它應該是:
print total_1
return total_1
換句話說: return
語句必須是函數內部任何執行路徑中的最后一個語句。
您可以通過使用列表理解或保持運行總數而不是建立第二個列表來簡化此過程。
def scrabble_score(word):
return sum((score.get(x.lower(), 0) for x in word))
print scrabble_score('Hey')
>>> 9
要么
def scrabble_score2(word):
total = 0
for w in word:
total += score.get(w.lower(), 0)
return total
print scrabble_score2('Hey')
>>> 9
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.