在Python中寻找如何使while循环中断的建议

2024-06-25 05:24:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力制作一个带有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

Tags: youapiinputdatareplyrequestslowerlike
2条回答

reply in yesChoice代替reply == yesChoicereply是一个字符串,yesChoice是一个列表。您必须检查列表中是否有字符串

在while循环中不需要if语句。因为while循环每次运行时都会检查reply in yesChoice,如果reply in yesChoicefalse,它就会退出

代码的正确版本:

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.')

等于运算符无法检查列表中的项目。要使此代码正常工作,您需要将YesSchoice和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

相关问题 更多 >