在 Python 中寻找关于如何让我的 while 循环中断的建议

我正在尝试使用 API 制作查克诺里斯笑话生成器。这需要一个无限循环,但我只是看不出我哪里出错了。最初,我从 WHILE 上的 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


凤凰求蛊
浏览 88回答 2
2回答

海绵宝宝撒

使用reply in yesChoice而不是reply == yesChoice。reply是一个字符串,yesChoice是一个列表。您必须检查字符串是否在列表中。您不需要在 while 循环中使用 if 语句。reply in yesChoice因为 while 循环会在每次运行时检查,如果reply in yesChoice是false它就会退出。您的代码的正确版本:import requestsyesChoice = ['yes', 'y']noChoice = ['no', 'n'] # variable not usedprint('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.')

慕森卡

等于运算符无法检查列表中的项目。要使此代码起作用,您需要将 yesChoice 和 noChoice 更改为字符串。如果您希望回复有选项,您需要更改您的 while 条件。import requestsyesChoice = ['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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python