2 回答

TA貢獻1809條經驗 獲得超8個贊
使用reply in yesChoice而不是reply == yesChoice。reply是一個字符串,yesChoice是一個列表。您必須檢查字符串是否在列表中。
您不需要在 while 循環中使用 if 語句。reply in yesChoice因為 while 循環會在每次運行時檢查,如果reply in yesChoice是false它就會退出。
您的代碼的正確版本:
import requests
yesChoice = ['yes', 'y']
noChoice = ['no', 'n'] # variable not used
print('This is the Random Chuck Norris Joke Generator.\n')
reply=input("Would you like a joke?").lower()
while reply in yesChoice:
joke=requests.get('https://api.chucknorris.io/jokes/random')
data=joke.json()
print(data["value"])
reply=input("\nWould you like another joke?").lower()
print('Chuck Norris hopes you enjoyed his jokes.')

TA貢獻1806條經驗 獲得超8個贊
等于運算符無法檢查列表中的項目。要使此代碼起作用,您需要將 yesChoice 和 noChoice 更改為字符串。如果您希望回復有選項,您需要更改您的 while 條件。
import requests
yesChoice = ['yes', 'y']
noChoice = ['no', 'n']
print('This is the Random Chuck Norris Joke Generator.\n')
reply=input("Would you like a joke?").lower()
while reply in yesChoice:
joke=requests.get('https://api.chucknorris.io/jokes/random')
data=joke.json()
print(data["value"])
reply=input("\nWould you like another joke?").lower()
if reply in noChoice:
print('Chuck Norris hopes you enjoyed his jokes.')
break
添加回答
舉報