Python Forum

Full Version: While loop and If Statement
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello friends,
This is our assignment:
Write a function called stop_at_z that iterates through a list of strings. Using a while loop, append each string to a new list until the string that appears is ā€œzā€. The function should return the new list.

I have came up with this:

def stop_at_z(testlist):
    index = 0
    result = []
    while index < len(testlist):
        if "z" in testlist[index]:
            index += 1
            continue
        result.append(testlist[index])
        index += 1
    return result
But I receive error!
https://pasteboard.co/HYpOEuJ.png

Can somebody help?

Thank you
Hello,
if "z" in testlist[index]
This line checks if character "z" is in the string "testlist[index]", not if the string is "z". So "pizza" will be True.
What you need instead is
if "z" == testlist[index]
You also don't need and index to iterate a list. You can simply do it like this:
my_list = ['a', 'b', 'c']
for item in my_list:
    print(item)
And instead of "continue", you will need a "break" when the condition is met.
Hello,

For this assignment, i'm supposed to use the While loop. And the question asks we should make a sublist from all the items with a "z", so it doesn't have to be just the "z" character.
This is my another attempt, but still I receive error: https://pasteboard.co/HYrlfxR.png

Thank you
Based on the expected values from the screenshots, the loop is expected to stop once "z" has been found. The first test expects "['c',...'r']" and 'r' is the last value prior to "z". Likewise, the second test expects "['zoo...azz']" and the only string in the list ending in "azz" is "pizzazz" which is immediately before "z".

Skipping "z" and appending the remaining the values would cause those first two tests to fail. Plus, the conditional is true if a "z" is in the string, but that is not true based on test 1. You want to test equality to "z" instead.

Also, there's a problem with your index too. If "z" is found, your function increments index by 2 - once under the conditional and once again after the conditional.