Leonardo Petry <leonardo.petry...@gmail.com> writes:

> So I am starting with python and I have been working on some simple
> exercises.

You are welcome here. Congratulations on starting with Python!

You may also be interested to know there is also a separate forum
<URL:https://mail.python.org/mailman/listinfo/tutor> dedicated to
tutoring beginners in Python.

> 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

You should avoid using U+0009 TAB characters for indentation, since they
render inconsistently and can easily result in invisible differences in
changed code. Instead, use four-column indentation with space (U+0020
SPACE) characters.

> 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. 

Is that a complaint, or shock at how easy it is? :-)

> Basically my question is: Why is python not treating the contents of
> wordplay.txt as one long string and looping each character?

Because the types of the objects are different; different types define
different behaviour. Indeed, that is almost the definition of what a
type is.

A text string object supports iteration by returning each character
<URL:https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str>.

A file object supports iteration by returning each line from the stream
<URL:https://docs.python.org/3/library/io.html>.

-- 
 \          “Our products just aren't engineered for security.” —Brian |
  `\             Valentine, senior vice-president of Microsoft Windows |
_o__)                                                development, 2002 |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to