2 回答

TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超4個(gè)贊
您的函數(shù)在子句中main
沒有語句,這會(huì)導(dǎo)致be 。迭代何時(shí)是導(dǎo)致錯(cuò)誤的原因。您可以采取一些措施來改進(jìn)代碼:return
else
tracks
None
tracks
None
關(guān)注點(diǎn)分離:該
main
函數(shù)正在做兩件不同的事情,檢查輸入和獲取曲目。一開始就做
.lower()
一次,這樣就不必重復(fù)。遵循文檔約定。
使用前檢查響應(yīng)
一些代碼清理
請(qǐ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貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超9個(gè)贊
當(dāng)if執(zhí)行 - 語句時(shí),您將返回一個(gè)項(xiàng)目列表并將它們輸入到display_tracks()函數(shù)中。else但是執(zhí)行 - 語句時(shí)會(huì)發(fā)生什么?您將請(qǐng)求添加到文本文件中,但不返回任何內(nèi)容(或項(xiàng)目NoneType)并將其輸入到display_tracks(). display_tracks然后迭代此NoneType-item,拋出異常。
您只想在確實(shí)有任何要顯示的曲目時(shí)顯示曲目。實(shí)現(xiàn)此目的的一種方法是將 的調(diào)用display_tracks()移至您的main函數(shù)中,但是如果沒有找到您的搜索項(xiàng)的曲目,則會(huì)引發(fā)相同的錯(cuò)誤。另一個(gè)解決方案是首先檢查您的內(nèi)容是否tracks不為空,或者使用類似的方法捕獲TypeError- 異常
tracks = main(city, int(number_of_songs))
try:
display_tracks(tracks)
except TypeError:
pass
添加回答
舉報(bào)