Consider the following fragment: for i in ('a','b','c'):
.... for i in (1,2,3):
.... print i,
.... print i,
....
1 2 3 3 1 2 3 3 1 2 3 3
Now. I believe I know what is happening. The i in both loops refers to the
same variable. My question is whether it would make more sense (be more
intuitive) to have a for loop create its own local scope. (ie. an output
string of
1 2 3 a 1 2 3 b 1 2 3 c
)
Grzegorz
"Some cause happiness wherever they go; others, whenever they go."
- Oscar Wilde (1854-1900) 8 1332
Actually the result is exactly as expected.
Programming 101 teaches us not to reuse
loop variables in nested loops.
and
People have enough problems with "scope"
already (just monitor this newsgroup for
a while if you don't believe me). Also
consider a variation of your example:
d={}
for i in ('a','b','c'):
for j in (1,2,3):
d[i]=j
If 'j' loop had local scope how could
it reference 'i'?
Larry Bates
"Grzegorz Dostatni" <gr******@ee.ualberta.ca> wrote in message
news:Pi*************************************@e5-05.ee.ualberta.ca... Consider the following fragment:
for i in ('a','b','c'):
... for i in (1,2,3): ... print i, ... print i, ... 1 2 3 3 1 2 3 3 1 2 3 3
Now. I believe I know what is happening. The i in both loops refers to the same variable. My question is whether it would make more sense (be more intuitive) to have a for loop create its own local scope. (ie. an output string of 1 2 3 a 1 2 3 b 1 2 3 c
)
Grzegorz
"Some cause happiness wherever they go; others, whenever they go." - Oscar Wilde (1854-1900)
Grzegorz Dostatni <grzegorz <at> ee.ualberta.ca> writes: My question is whether it would make more sense (be more intuitive) to have a for loop create its own local scope
I highly doubt you're going to convince Python to change on this, but you can
always try... ;)
Anyway, there are times when you want to access the loop variable afterwards,
e.g.:
for i, line in enumerate(file(...)):
# do something with each line of the file
print 'lines in file:', i
So the tradeoff is between catching errors like yours (and as Larry Bates
says, you really shouldn't use the same variable in nested loops anyway) and
being able to be more expressive. My suspicion is that there really aren't
too many use cases where you really need to have the same loop variable name
in a nested for loop, but I bet there are a fair number of good use cases for
having access to the loop variable after the end of the loop.
Steve
"Larry Bates" <lb****@swamisoft.com> writes: Actually the result is exactly as expected. Programming 101 teaches us not to reuse loop variables in nested loops.
Programming 101 usually doesn't say whether a nested loop introduces a
new scope or not. If there's a new scope, it's not re-use of a variable.
Grzegorz Dostatni wrote: My question is whether it would make more sense (be more intuitive) to have a for loop create its own local scope. (ie. an output string of 1 2 3 a 1 2 3 b 1 2 3 c
If for loops created a new local scope then the following
would not work
for i in range(10):
if data[i] == "stop":
break
else:
return None
print "Found at position", i
.. continue to work with that position ..
In Python only functions, modules, and classes
create a new scope (at least syntax-wise)
If you really, really want a scope there you
can do this for i in range(5):
.... class Spam:
.... for i in "ABC":
.... print i,
.... print "At end -->", i
.... del i
.... print "After del -->", i
.... i = "qwerty" # show that 'i' gets removed
.... print "After end of class scope", i
....
A B C At end --> C
After del --> 0
After end of class scope 0
A B C At end --> C
After del --> 1
After end of class scope 1
A B C At end --> C
After del --> 2
After end of class scope 2
A B C At end --> C
After del --> 3
After end of class scope 3
A B C At end --> C
After del --> 4
After end of class scope 4
Strange, but it works. I don't think I've seen
anyone use this in real code, and I don't really
advise you do either.
Andrew da***@dalkescientific.com
Andrew Dalke <adalke <at> mindspring.com> writes: >>> for i in range(5):
... class Spam: ... for i in "ABC": ... print i,
Wow, that's an awesome abuse of classes. How cool! =)
Steve
On Thu, 23 Sep 2004 14:18:01 -0500, "Larry Bates" <lb****@swamisoft.com> wrote: Actually the result is exactly as expected. Programming 101 teaches us not to reuse loop variables in nested loops.
[14:07] C:\pywk\clp>type p101.cpp
#include <cstdio>
void main(){
char abc[]="abc";
for(int i=0;i<3;++i){
printf("%c ", abc[i]);
for(int i=0;i<3;++i) printf("%d ", i);
}
}
[14:07] C:\pywk\clp>cl p101.cpp
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8168 for 80x86
Copyright (C) Microsoft Corp 1984-1998. All rights reserved.
p101.cpp
Microsoft (R) Incremental Linker Version 6.00.8168
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.
/out:p101.exe
p101.obj
[14:07] C:\pywk\clp>p101
a 0 1 2 b 0 1 2 c 0 1 2
;-)
Regards,
Bengt Richter
On 23 Sep 2004 21:09:26 GMT, bo**@oz.net (Bengt Richter) wrote: On Thu, 23 Sep 2004 14:18:01 -0500, "Larry Bates" <lb****@swamisoft.com> wrote:
Actually the result is exactly as expected. Programming 101 teaches us not to reuse loop variables in nested loops.
[14:07] C:\pywk\clp>type p101.cpp #include <cstdio> void main(){ char abc[]="abc"; for(int i=0;i<3;++i){ printf("%c ", abc[i]); for(int i=0;i<3;++i) printf("%d ", i); } }
[14:07] C:\pywk\clp>cl p101.cpp Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8168 for 80x86 Copyright (C) Microsoft Corp 1984-1998. All rights reserved.
p101.cpp Microsoft (R) Incremental Linker Version 6.00.8168 Copyright (C) Microsoft Corp 1992-1998. All rights reserved.
/out:p101.exe p101.obj
[14:07] C:\pywk\clp>p101 a 0 1 2 b 0 1 2 c 0 1 2
;-)
Regards, Bengt Richter
Oops, I gave too much credit to M$ ;-/
Reordering the above as below, it gives
[14:24] C:\pywk\clp>cl/nologo p101.cpp
p101.cpp
[14:38] C:\pywk\clp>p101
0 1 2 0 1 2 0 1 2
vs g++ from mingw using msys shell:
[14:35] /c/pywk/clp>cat -n p101.cpp
1 #include <cstdio>
2 int main(){
3 char abc[]="abc";
4 for(int i=0;i<3;++i){
5 for(int i=0;i<3;++i) printf("%d ", i);
6 printf("%c ", abc[i]);
7 }
8 return 0;
9 }
10
[14:35] /c/pywk/clp>g++ p101.cpp -o p101a.exe
p101.cpp: In function `int main()':
p101.cpp:6: warning: name lookup of `i' changed
p101.cpp:4: warning: matches this `i' under ISO standard rules
p101.cpp:5: warning: matches this `i' under old rules
[14:35] /c/pywk/clp>p101a
0 1 2 a 0 1 2 b 0 1 2 c [14:36] /c/pywk/clp>
[14:36] /c/pywk/clp>
Regards,
Bengt Richter
Paul Rubin <http://ph****@NOSPAM.invalid> writes: "Larry Bates" <lb****@swamisoft.com> writes: Actually the result is exactly as expected. Programming 101 teaches us not to reuse loop variables in nested loops.
Programming 101 usually doesn't say whether a nested loop introduces a new scope or not. If there's a new scope, it's not re-use of a variable.
Whether the OP's usage is "re-use of a variable" is a matter of how
you choose to define the words in that phrase, I suppose. But even in
a hypothetical Python-like language that works the way Grzegorz
expected, whatever you choose to call the usage of the name i in G's
example, I call it "a bad idea".
I assume you didn't mean to imply that the OP's example wouldn't be
better if written with a differently-named loop variable, even in such
a language?: for i in ('a','b','c'):
.... for j in (1,2,3):
.... print j,
.... print i,
....
1 2 3 a 1 2 3 b 1 2 3 c
John This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: sky2070 |
last post by:
Parse error: parse error, unexpected T_OBJECT_OPERATOR, expecting ')'
in c:\inetpub\wwwroot\session.php on line 19
can anyone tell me what is wrong with this code???
<?
// Define the Session...
|
by: Salim |
last post by:
Hi people, keep getting this errorParse error: parse error, unexpected
T_STRING in order_fns.php line 91. the code is below for the file and
I've indicated line 91
<?php
function...
|
by: Ehartwig |
last post by:
I recently created a script for user verification, solved my emailing
issues, and then re-created the script in order to work well with the
new PHP 5 that I installed on my server. After...
|
by: ashu |
last post by:
hi
look at this code
include <stdio.h>
int main(void)
{
int i,j=2;
i=j++ * ++j * j++;
printf("%d %d",i,j);
return 0;
|
by: devereaux |
last post by:
I'm trying to run a script and it's throwing the following error:
Parse error: syntax error, unexpected T_OBJECT_OPERATOR in openfile.php on line 41
Here is the openfile.php file and I have...
|
by: bintom |
last post by:
I ran the following simple code in C++ and got unexpected results:
float f = 139.4;
cout << f;
Output:
139.399994;
|
by: =?Utf-8?B?QXJtaW4gR2FsbGlrZXI=?= |
last post by:
Hi
I've got an unexpected error in a unit test. I want to test a activity from
Windows Workflow Foundation (WF).
First, I executed the test outside of the activity just in the test-init...
|
by: JRough |
last post by:
I'm trying to use output buffering to cheat so i can print to excel
which is called later than this header().
header("Content-type: application/xmsdownload");
header("Content-Disposition:...
|
by: riverdale1567 |
last post by:
Hi I am a newbie trying to get some of my first code working, yada yada yada.
I have a drop down box which chooses a state then takes the post data to 'processform2.php' to use that to pull up...
|
by: Padfoot153 |
last post by:
Hey, I'm getting the error:
Parse error: syntax error, unexpected T_VARIABLE in /Users/Oscar/AwesomeSongz/userCake/profile.php on line 7
with this code
<?php...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
| |