-2

Having a bit of trouble with while loops. I understand this basic for loop runs through whatever is passed into the function but how would I change the for loop to a while loop? Thought it would be as easy as changing the for to while but apparently not so.

def print_data(items):
 for item in items:
    print(item)
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • 1
    Are you aware of the differences between `for` and `while`? Have you read [the relevant documentation](https://docs.python.org/3.4/reference/compound_stmts.html#while)? – Frédéric Hamidi Jun 10 '15 at 08:13
  • i have, as i have read the passage about it in my textbook but im still really sturggling :/ Any pointers? – Liam Sharland Jun 10 '15 at 08:14
  • 1
    I think the simple answer, really, is you can't (or rather shouldn't). They serve different purposes. A `for` loop will run once for every item in an iterable (thing that you can step through items of), a `while` loop will run for as long as the statement that follows it evaluates to `True`. – SiHa Jun 10 '15 at 08:20
  • Dupe of http://stackoverflow.com/questions/920645/when-to-use-while-or-the-for-in-python – SiHa Jun 10 '15 at 08:32

6 Answers6

1

You can do something like this to have the same printing functionality with a while loop:

def print_data(items):
    i = 0
    while i < len(items):
        print items[i]
        i += 1
Mathias711
  • 6,568
  • 4
  • 41
  • 58
1

Here is a while loop version that works by constructing an iterator and manually walking it. It works regardless of whether the input is a generator or a list.

def print_data(items):
 it = iter(items)
 while True:
   try:
     print next(it)
   except StopIteration:
     break

print_data([1,2,3])
merlin2011
  • 71,677
  • 44
  • 195
  • 329
0

One option, that works on both lists and generators, is to construct an iterator and then use Python's built-in next function. When the iterator reaches the end, the next function will raise a StopIteration exception, which you can use to break the loop:

def print_data(items):
    it = iter(items)
    while True:
        try:
            print next(it)
        except StopIteration:
            break

print_data(['a', 'b', 'c'])
print_data(('a', 'b', 'c'))

There's more about the next built-in function and iterators in the docs.

Herman Schaaf
  • 46,821
  • 21
  • 100
  • 139
0

If you are learning Python:

If you need to iterate over an iterable (a list, a generator, a string etc.. in short and not precise words something that contains things and can "give" those things one by one..) you better use for.

In Python for was made for iterables, so you don't need a while.

If you are learning programming in general:

while needs a condition to be satisfied to keep looping, you create your own condition making a counter that will increment every loop, and making the while loop go while this counter is less or equal to the lenght of your items, as showed in Mathias711's answer.

Hrabal
  • 2,403
  • 2
  • 20
  • 30
0

The for-loop you are using is iterating through a so called iterator.

This means to walk through iterable objects (lists, generators, dicts,...) and return the next item from the iterator which is returned by the built-in function [next()][2]. If there is no item left, calling this function will raise an so called StopIteration error which causes to stop iteration.

So the pythonic way to iterate througth iteratable objects is in fact using the for-loop you provided in your question. However, if you really want to use a while loop (which at least in general is not recommended at all) you have to iterate using a try-except-block and handle the StopIteration error raised if no item is left.

def iterate_manually(items):
    # convert items list into iterator
    iterator = iter(items)
    while True:
        try:
            print(next(iterator))
        # handle StopIteration error and exit while-loop
        except StopIteration:
            break

iterate_manually(['foo', 'bar', 'baz'])
albert
  • 8,027
  • 10
  • 48
  • 84
-1

You can try this

 def print_data(items):
   i =0
   while items:
     if i < len(items):
       print items[i]
       i = i+1
     else:
       break 
Shruti Srivastava
  • 378
  • 1
  • 6
  • 26