Godisalie
Godisalie

Reputation: 5

Python infinite while loop

I've got this code:

Text = input("Copy Text here ")
WordList = Text.split(" ")
i = 0
for i in range (0, len(WordList)-1):
     i += 1
while (i <= len(WordList))  :
    if (WordList[i] == "Name" or "Name1" or "Name2") :
        print(WordList[i])
     else:
        print("No DATA")

If I run this code I get two problems: first it only prints the last entry which might be because I forgot to tell it to stop counting when "Name", "Name2" or "Name1" is found. The bigger problem is that this ends in an infinite loop and I've got no idea why.

Upvotes: 0

Views: 231

Answers (3)

Aphire
Aphire

Reputation: 1652

Mix your loops together. the first loops only function is to keep adding to i until it is the length of your wordlist - 1.

The second loop will then continuously loop until i > the length of wordlist, which it will not do, unless you change the value of i in that loop.

This is also why it will print the last word, because i is always wordList - 1.

Try this instead

for x in range (0, len(WordList)):
    if ((WordList[x] == "Name") or (WordList[x] ==  "Name1") or (WordList[x] ==  "Name2")):
        print (WordList[x])
    else:
        print ("No Data")

Upvotes: -2

schesis
schesis

Reputation: 59118

You have two loops: a for loop which does nothing but increment i each time through (which is a mistake, because for already does that for you), and a while loop which attempts to do the actual work, but doesn't run until after the for loop terminates.

In any case, using an index variable to iterate over a list is the wrong way to approach the problem in Python. Instead, you should iterate over it directly:

text = "a b c Name d e Name2 f Name1 g"

for word in text.split(" "):
    if word in ("Name", "Name1", "Name2"):
        print(word)
    else:
        print("No DATA")

Another problem in your original code is the line

if (WordList[i] == "Name" or "Name1" or "Name2") :

... which isn't doing what you think. What actually happens here is that "Name" or "Name1" or "Name2" is evaluated to "Name" (because of short circuit logic), and then that is tested for equality with WordList[i]. The right way to test if something is one of a number of values is with the in operator, as in the code above.

Upvotes: 3

ZdaR
ZdaR

Reputation: 22954

text = input("Copy Text here ")
wordlist = text.split(" ")
for i in wordlist:
    if (i in ["Name", "Name1", "Name2"]):
        print (i)
    else:
        print ("No DATA")

You are over complicating the things the python handles the iterations very nicely, you dont need to increment the counter after ever iteration , Actually you don't need any sort of counter.

Upvotes: 2

Related Questions