2 回答

TA貢獻1785條經(jīng)驗 獲得超4個贊
您的函數(shù)在子句中main
沒有語句,這會導(dǎo)致be 。迭代何時是導(dǎo)致錯誤的原因。您可以采取一些措施來改進代碼:return
else
tracks
None
tracks
None
關(guān)注點分離:該
main
函數(shù)正在做兩件不同的事情,檢查輸入和獲取曲目。一開始就做
.lower()
一次,這樣就不必重復(fù)。遵循文檔約定。
使用前檢查響應(yīng)
一些代碼清理
請參閱下面我上面建議的更改:
def fetch_tracks(city: str, num_songs: int) -> List[Dict[str, Any]]:
"""Searches Spotify for songs that are about `city`.
:param city: TODO: TBD
:param num_songs: TODO: TBD
:return: at most `num_songs` tracks.
"""
results = []
for search_term in [city, *CITY_KEY_WORDS[city]]:
response = sp.search(search_term, limit=50)
if response and 'tracks' in response and 'items' in response['tracks']:
results += response['tracks']['items']
# Shuffle the results so that they are not ordered by key word and return
# at most `num_songs`
shuffle(results)
return results[: num_songs]
def display_tracks(tracks: List[Dict[str, Any]]) -> None:
"""Prints the name, artist and URL of each track in `tracks`"""
for num, track in enumerate(tracks):
# Print the relevant details
print(
f"{num + 1}. {track['name']} - {track['artists'][0]['name']} "
f"{track['external_urls']['spotify']}")
def main():
city = input("Virtual holiday city? ")
city = city.lower()
# Check the input city and handle unsupported cities.
if city not in CITY_KEY_WORDS:
print("Unfortunately, this city is not yet in our system. "
"We will add it to our requests file.")
with open('requests.txt', 'a') as f:
f.write(f"{city}\n")
exit()
number_of_songs = input("How many songs would you like? ")
tracks = fetch_tracks(city, int(number_of_songs))
display_tracks(tracks)
if __name__ == '__main__':
main()

TA貢獻1830條經(jīng)驗 獲得超9個贊
當(dāng)if執(zhí)行 - 語句時,您將返回一個項目列表并將它們輸入到display_tracks()函數(shù)中。else但是執(zhí)行 - 語句時會發(fā)生什么?您將請求添加到文本文件中,但不返回任何內(nèi)容(或項目NoneType)并將其輸入到display_tracks(). display_tracks然后迭代此NoneType-item,拋出異常。
您只想在確實有任何要顯示的曲目時顯示曲目。實現(xiàn)此目的的一種方法是將 的調(diào)用display_tracks()移至您的main函數(shù)中,但是如果沒有找到您的搜索項的曲目,則會引發(fā)相同的錯誤。另一個解決方案是首先檢查您的內(nèi)容是否tracks不為空,或者使用類似的方法捕獲TypeError- 異常
tracks = main(city, int(number_of_songs))
try:
display_tracks(tracks)
except TypeError:
pass
添加回答
舉報