Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #71559
| From | Ned Batchelder <ned@nedbatchelder.com> |
|---|---|
| Subject | Re: New to Python. For in loops curiosity |
| Date | 2014-05-14 09:41 -0400 |
| References | <2f08e970-1334-4e7f-ba84-14869708a73b@googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.10006.1400074922.18130.python-list@python.org> (permalink) |
On 5/13/14 11:38 PM, Leonardo Petry wrote:
> Hi All,
>
> So I am starting with python and I have been working on some simple exercises.
>
> Here is something I found curious about python loops
>
> This loop run each character in a string
>
> def avoids(word,letters):
> flag = True
> for letter in letters:
> if(letter in word):
> flag = False
> return flag
>
> The loop below (at the bottom) runs each line of the file
>
> fin = open('wordplay.txt');
> user_input = raw_input('Enter some characters: ')
> count = 0
> for line in fin:
> word = line.strip()
> if(avoids(word, user_input)):
> count += 1;
>
> This is just too convenient.
> Basically my question is: Why is python not treating the contents of wordplay.txt as one long string and looping each character?
>
> Any comment is greatly appreciate. Thanks
>
>
Every class can decide for itself how it will behave when iterated over
(including deciding whether it can be iterated at all). File objects
produce lines, strings produce characters, lists produce elements,
dictionaries produce keys. Other objects do more exotic things.
You might find this helpful: http://bit.ly/pyiter It's a PyCon talk
all about iteration in Python, aimed at new learners.
--
Ned Batchelder, http://nedbatchelder.com
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
New to Python. For in loops curiosity Leonardo Petry <leonardo.petry.br@gmail.com> - 2014-05-13 20:38 -0700 Re: New to Python. For in loops curiosity John Gordon <gordon@panix.com> - 2014-05-14 03:46 +0000 Re: New to Python. For in loops curiosity Rustom Mody <rustompmody@gmail.com> - 2014-05-13 20:48 -0700 Re: New to Python. For in loops curiosity Ian Kelly <ian.g.kelly@gmail.com> - 2014-05-13 21:49 -0600 Re: New to Python. For in loops curiosity Ben Finney <ben@benfinney.id.au> - 2014-05-14 14:03 +1000 Re: New to Python. For in loops curiosity Roy Smith <roy@panix.com> - 2014-05-14 07:38 -0400 Re: New to Python. For in loops curiosity Ned Batchelder <ned@nedbatchelder.com> - 2014-05-14 09:41 -0400
csiph-web