Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 While loop and If Statement
#1
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
Quote
#2
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.
Quote
#3
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
Quote
#4
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.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Help converting int to str value in loop statement Jrvelandia 2 856 Feb-12-2018, 08:57 AM
Last Post: Jrvelandia
  if statement in for loop Danielk121 3 1,120 Nov-13-2017, 01:52 PM
Last Post: gruntfutuk

Forum Jump:


Users browsing this thread: 1 Guest(s)