Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #109202

Re: why for loop print only once after add if statement

From Peter Otten <__peter__@web.de>
Newsgroups comp.lang.python
Subject Re: why for loop print only once after add if statement
Date 2016-05-28 13:54 +0200
Organization None
Message-ID <mailman.7.1464436471.1839.python-list@python.org> (permalink)
References <4743c1df-de66-44e1-9d27-b62582d757ac@googlegroups.com> <nic0t5$666$1@ger.gmane.org>

Show all headers | View raw


jobmattcon@gmail.com wrote:

> for item, i in enumerate(aa)
>   print item
> 
> this writing, it can print all values
> 
> for item, i in enumerate(aa)
>   if item == findit:
>     print item
> 
> this only print the first value, means it only print once then not print
> again,

Assuming

aa = ["foo", "bar", "baz"]

and

findit = "bar"

the print statement will only be executed when findit == item.

First iteration of your for loop:

item = "foo"
if "foo" == "bar": # False
   print "foo"     # not executed, nothing printed

Second iteration:

item = "bar"
if "bar" == "bar": # True
    print "bar"    # prints bar

Third iteration:

item = "baz"
if "baz" == "bar": # False
    print "baz"    # not executed, nothing printed

> where is wrong?

This depends on what you want to achieve. Can you tell us?

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

why for loop print only once after add if statement jobmattcon@gmail.com - 2016-05-28 03:19 -0700
  Re: why for loop print only once after add if statement Sayth Renshaw <flebber.crue@gmail.com> - 2016-05-28 03:49 -0700
  Re: why for loop print only once after add if statement Peter Otten <__peter__@web.de> - 2016-05-28 13:54 +0200
  Re: why for loop print only once after add if statement Steven D'Aprano <steve@pearwood.info> - 2016-05-28 22:02 +1000
  Re: why for loop print only once after add if statement meInvent bbird <jobmattcon@gmail.com> - 2016-05-28 05:31 -0700
  Re: why for loop print only once after add if statement meInvent bbird <jobmattcon@gmail.com> - 2016-05-28 05:35 -0700
  Re: why for loop print only once after add if statement Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2016-05-28 12:59 -0400

csiph-web