我正在努力制作一个带有API的Chuck Norris笑话生成器。这需要一个无止境的循环,但我只是不知道我会错在哪里。起初,我用IF语句开始了一段时间,现在我意识到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 == 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 == noChoice:
print('Chuck Norris hopes you enjoyed his jokes.')
break
用
reply in yesChoice
代替reply == yesChoice
reply
是一个字符串,yesChoice
是一个列表。您必须检查列表中是否有字符串在while循环中不需要if语句。因为while循环每次运行时都会检查
reply in yesChoice
,如果reply in yesChoice
是false
,它就会退出代码的正确版本:
等于运算符无法检查列表中的项目。要使此代码正常工作,您需要将YesSchoice和noChoice更改为字符串。如果希望回复具有选项,则需要更改while条件
相关问题 更多 >
编程相关推荐