While loop and If Statement - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: While loop and If Statement (/thread-15687.html) |
While loop and If Statement - farzankh - Jan-27-2019 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 resultBut I receive error! https://pasteboard.co/HYpOEuJ.png Can somebody help? Thank you RE: While loop and If Statement - j.crater - Jan-27-2019 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. RE: While loop and If Statement - farzankh - Jan-27-2019 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 RE: While loop and If Statement - stullis - Jan-27-2019 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. |