Reputation: 3
I am working on trying to make a Chuck Norris joke generator with an API. This needs to be an endless loop but I just don't see where I am going wrong. Initially, I started out with an IF statement over WHILE and now have realized WHILE is what I need for this program.
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
Upvotes: 0
Views: 214
Reputation: 51
Use reply in yesChoice
instead of reply == yesChoice
. reply
is a string, yesChoice
is a list. You have to check if a string is in a list.
You do not need to have if statement in a while loop. Because while loop will check for the reply in yesChoice
every time it runs, if reply in yesChoice
is false
it will exit.
Correct version of your code:
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.')
Upvotes: 3
Reputation: 16
Equal-to operators are unable to check for an item inside a list. For this code to work, you would need to change your yesChoice and noChoice to strings. If you want the reply to have options you would need to change your while condition.
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
Upvotes: 0