Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do i keep validating string word length until it satisfies the condition?

So I have written this code to generate a random anime quote from the given website
could someone help me how can I make it so that the code checks if the quote has certain number of words and validates it accordingly

eg. If the quote has just 3 words I want it to try again
also if the quote has more than 20 words I want it to try again

I tried writing a while loop for it but it wasn’t working any answers would be appreciated

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

url = "https://animechan.vercel.app/api/random"
data = requests.get(url).json()

anime = data["anime"]
quote =data["quote"]
character =data["character"]

print("Anime : "+anime)
print(quote)
print(" '"+character+"'")

the while loop solution i came up with

quote = ""
word_list = quote.split()
number = len(word_list)
while number<=3 and number>=15:
    url = "https://animechan.vercel.app/api/random"
    data = requests.get(url).json()

    anime = data["anime"]
    quote =data["quote"]
    character =data["character"]

    print("Anime : "+anime)
    print(quote)
    print(" '"+character+"'")

>Solution :

I think this might be what you’re looking for (I’m assuming you wanted to stop on the first quote you found that was between 3 and 15 words long):

quote = ""
word_list = quote.split()
number = len(word_list)
while number<=3 or number>=15:
    url = "https://animechan.vercel.app/api/random"
    data = requests.get(url).json()

    anime = data["anime"]
    quote =data["quote"]
    character =data["character"]

    word_list = quote.split()
    number = len(word_list)

print("Anime : "+anime)
print(quote)
print(" '"+character+"'")

I only made a couple of changes to your original:

  1. Your while loop needed a change from and to or (the length can never be both less than or equal to 3 and greater than or equal to 15, so the loop never got the chance to run)
  2. You need to recalculate the value of number each time you get a new value from the API
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading