mag paige
mag paige

Reputation: 29

While loop returns nothing

The function should print one list - the top list when 'paige' is inclusive in the list. However, it returns nothing. Where does it go wrong?

Also, is str(list) the best way here to store output in the result?

def addingpaige(s):
   list = ["paige", "peter", "eric"]
   result = ""
   while "paige" and "peter" in list:
        result = result + str(list)
   return result
print addingpaige(["paige", "peter", "eric"])

Upvotes: 0

Views: 381

Answers (2)

chriscberks
chriscberks

Reputation: 425

"paige" and "peter" actually evaluates to "peter". This code is effectively saying: while the string "peter" is present in list keep looping.

Upvotes: 0

BrechtDeMan
BrechtDeMan

Reputation: 6912

  1. It seems like you are giving the list ["paige", "peter", "eric"] as an argument to addingpaige(), but then not doing anything with it, instead defining list in that function.

  2. while "paige" and "peter" in list:: and doesn't work this way. Instead, test "paige" in list and then "peter" in list. In other words, this becomes while "paige" in list and "peter" in list:

  3. The while condition is always True in this case, so this gives you an infinite loop. Only have a while condition that can change between iterations, and/or have something in your while loop that can break out of it.

  4. list is a keyword so maybe choose a different name for your list.

It's not clear to me what you want to do, though. As it stands, the code is nonsensical as it contains an infinite loop. What should addingpaige() print, based on what condition?

Upvotes: 2

Related Questions