[Tutor] new to python

Andre Engels andreengels at gmail.com
Tue Jul 25 03:41:05 EDT 2017


The problem here is that you have doubled the "for line in f:" line.
Given that you say you know some programming, I'll just cut to the
technical name of the problem you are having: You are changing the
value of a loop variable (by starting an inner loop with the same loop
variable) inside a loop. Doing that in Python leads to behaviour that
is hard to understand and almost never what you intended.


On Tue, Jul 25, 2017 at 5:58 AM, N6Ghost <n6ghost at gmail.com> wrote:
>
>
> On 7/23/2017 1:03 AM, Alan Gauld via Tutor wrote:
>>
>> On 23/07/17 07:26, N6Ghost wrote:
>>
>>> f = open("C:\coderoot\python3\level1\inputfile.txt", 'r')
>>> for line in file:
>>
>> Note that you have no variable called 'file'.
>> So this line doesn't make sense.
>>
>>>       for line in f:
>>>           print(line.rstripe())
>>
>> This bit will work if you omit the line above and
>> fix the indentation. (and remove the 'e' from strip()
>>
>>>           f.close()
>>
>> This should be outside the loop, you don't want
>> to close the file after every line.
>>
>> Finally, there is another way to do this which
>> is considered 'better'/more Pythonic:
>>
>> with open("C:\coderoot\python3\level1\inputfile.txt", 'r') as f:
>>       for line in f:
>>           print(line.strip())
>>
>> Notice with this construct the closing of the file is
>> handled for you.
>>
>>> any idea why that does not work?
>>
>> When posting questions always include the full error text.
>> Although apparently cryptic it actually contains a lot of
>> useful detail which saves us from making guesses.
>>
>
>
> this code works
> f = open("C:/coderoot/python3/level1/inputfile.txt", 'r')
> for line in f:
>     for line in f:
>         #print(line.rstrip())
>         print(line)
>
> f.close()f = open("C:/coderoot/python3/level1/inputfile.txt", 'r')
> for line in f:
>     for line in f:
>         #print(line.rstrip())
>         print(line)
>
> f.close()
>
> the out put skips the first line of the inputfile and puts a blank line
> inbetween
>
> inputfile is:
> tom
> jerry
> make
> windows
> linux
>
> -N6Ghost
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



-- 
André Engels, andreengels at gmail.com


More information about the Tutor mailing list