473,320 Members | 1,976 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Basic question

I've been studying python for 2 weeks now and got stucked in the
following problem:

for j in range(10):
print j
if(True):
j=j+2
print 'interno',j

What happens is that "j=j+2" inside IF does not change the loop
counter ("j") as it would in C or Java, for example.

Am I missing something?

[]'s
Cesar

May 12 '07 #1
22 1501
Cesar G. Miguel wrote:
for j in range(10):
print j
if(True):
j=j+2
print 'interno',j

What happens is that "j=j+2" inside IF does not change the loop
counter ("j") as it would in C or Java, for example.
Am I missing something?
If you want that kind of behaviour then use a `while` construct:

j = 0
while j < 5:
print j
if True:
j = j + 3
print '-- ', j

If you use a for loop, for each pass through the foor loop Python
assigns next item in sequence to the `j` variable.

HTH,
Karlo.
May 12 '07 #2
On May 12, 5:18 pm, "Cesar G. Miguel" <cesar.go...@gmail.comwrote:
I've been studying python for 2 weeks now and got stucked in the
following problem:

for j in range(10):
print j
if(True):
j=j+2
print 'interno',j

What happens is that "j=j+2" inside IF does not change the loop
counter ("j") as it would in C or Java, for example.

Am I missing something?
Yes you are :)

"for j in range(10):..." means:
1. Build a list [0,1,2,3,4,5,6,7,8,9]
2. For element in this list (0, then 1, then 2,...), set j to that
value then execute the code inside the loop body

To simulate "for(<initialisation>; <condition>; <increment>) <body>"
you have to use while in Python:

<initialisation>
while <condition>:
<body>
<increment>

Of course in most case it would not be the "pythonic" way of doing
it :)

--
Arnaud

May 12 '07 #3
Cesar G. Miguel wrote:
I've been studying python for 2 weeks now and got stucked in the
following problem:

for j in range(10):
print j
if(True):
j=j+2
print 'interno',j

What happens is that "j=j+2" inside IF does not change the loop
counter ("j") as it would in C or Java, for example.

Am I missing something?

[]'s
Cesar

Nope. The loop counter will be assigned successively through the list of
integers produced by range(10). Inside the loop, if you change j, then
from that point on for that pass through the body, j will have that
value. But such an action will not change the fact that next pass
through the loop, j will be assigned the next value in the list.
May 12 '07 #4
"j=j+2" inside IF does not change the loop
counter ("j")
You might be not truly catching the idea of Python `for` statements
sequence nature. It seems that <http://docs.python.org/ref/for.html>
will make things quite clear.
The suite may assign to the variable(s) in the target list; this
does not affect the next item assigned to it.
In C you do not specify all the values the "looping" variable will be
assigned to, unlike (in the simplest case) you do in Python.

--
Happy Hacking.

Dmitry "Sphinx" Dzhus
http://sphinx.net.ru
May 12 '07 #5
On May 12, 12:18 pm, "Cesar G. Miguel" <cesar.go...@gmail.comwrote:
I've been studying python for 2 weeks now and got stucked in the
following problem:

for j in range(10):
print j
if(True):
j=j+2
print 'interno',j

What happens is that "j=j+2" inside IF does not change the loop
counter ("j") as it would in C or Java, for example.

Am I missing something?

[]'s
Cesar
What is your real intent here? This is how I understand it after
reading your post: you want to create a loop that steps by an
increment of 2. If that's the case, then:
>>for j in range(0,10,2):
.... print j
....
0
2
4
6
8

would be a simple result.

Cheers,
-Basilisk96

May 12 '07 #6
On May 12, 2:45 pm, Basilisk96 <basilis...@gmail.comwrote:
On May 12, 12:18 pm, "Cesar G. Miguel" <cesar.go...@gmail.comwrote:
I've been studying python for 2 weeks now and got stucked in the
following problem:
for j in range(10):
print j
if(True):
j=j+2
print 'interno',j
What happens is that "j=j+2" inside IF does not change the loop
counter ("j") as it would in C or Java, for example.
Am I missing something?
[]'s
Cesar

What is your real intent here? This is how I understand it after
reading your post: you want to create a loop that steps by an
increment of 2. If that's the case, then:
>for j in range(0,10,2):

... print j
...
0
2
4
6
8

would be a simple result.

Cheers,
-Basilisk96
Actually I'm trying to convert a string to a list of float numbers:
str = '53,20,4,2' to L = [53.0, 20.0, 4.0, 2.0]

As some of you suggested, using while it works:

-------------------------------------
L = []
file = ['5,1378,1,9', '2,1,4,5']
str=''
for item in file:
j=0
while(j<len(item)):
while(item[j] != ','):
str+=item[j]
j=j+1
if(j>= len(item)): break

if(str != ''):
L.append(float(str))
str = ''

j=j+1

print L
-------------------------------------

But I'm not sure this is an elegant pythonic way of coding :-)

Thanks for all suggestions!

May 12 '07 #7
Cesar G. Miguel wrote:
-------------------------------------
L = []
file = ['5,1378,1,9', '2,1,4,5']
str=''
for item in file:
j=0
while(j<len(item)):
while(item[j] != ','):
str+=item[j]
j=j+1
if(j>= len(item)): break

if(str != ''):
L.append(float(str))
str = ''

j=j+1

print L
But I'm not sure this is an elegant pythonic way of coding :-)
Example:

In [21]: '5,1378,1,9'.split(',')
Out[21]: ['5', '1378', '1', '9']

So, instead of doing that while-based traversal and parsing of `item`,
just split it like above, and use a for loop on it. It's much more
elegant and pythonic.

HTH,
Karlo.
May 12 '07 #8
On May 12, 3:09 pm, Karlo Lozovina <_karlo_@_mosor.netwrote:
Cesar G. Miguel wrote:
-------------------------------------
L = []
file = ['5,1378,1,9', '2,1,4,5']
str=''
for item in file:
j=0
while(j<len(item)):
while(item[j] != ','):
str+=item[j]
j=j+1
if(j>= len(item)): break
if(str != ''):
L.append(float(str))
str = ''
j=j+1
print L
But I'm not sure this is an elegant pythonic way of coding :-)

Example:

In [21]: '5,1378,1,9'.split(',')
Out[21]: ['5', '1378', '1', '9']

So, instead of doing that while-based traversal and parsing of `item`,
just split it like above, and use a for loop on it. It's much more
elegant and pythonic.

HTH,
Karlo.
Great! Now it looks better :-)

May 12 '07 #9
Actually I'm trying to convert a string to a list of float numbers:
str = '53,20,4,2' to L = [53.0, 20.0, 4.0, 2.0]
str="53,20,4,2"
map(lambda s: float(s), str.split(','))

Last expression returns: [53.0, 20.0, 4.0, 2.0]
--
Happy Hacking.

Dmitry "Sphinx" Dzhus
http://sphinx.net.ru
May 12 '07 #10
On 2007-05-12, Cesar G. Miguel <ce*********@gmail.comwrote:
Actually I'm trying to convert a string to a list of float numbers:
str = '53,20,4,2' to L = [53.0, 20.0, 4.0, 2.0]
>>str = '53,20,4,2'
>>[float(w) for w in str.split(',')]
[53.0, 20.0, 4.0, 2.0]
>>map(float,str.split(','))
[53.0, 20.0, 4.0, 2.0]

--
Grant Edwards grante Yow! I want you to
at MEMORIZE the collected
visi.com poems of EDNA ST VINCENT
MILLAY... BACKWARDS!!
May 12 '07 #11
On 2007-05-12, Dmitry Dzhus <ma**@sphinx.net.ruwrote:
str="53,20,4,2"
map(lambda s: float(s), str.split(','))
There's no need for the lambda.

map(float,str.split(','))

Does exactly the same thing.

--
Grant Edwards grante Yow! I feel like I am
at sharing a "CORN-DOG" with
visi.com NIKITA KHRUSCHEV...
May 12 '07 #12
On May 12, 3:40 pm, Dmitry Dzhus <m...@sphinx.net.ruwrote:
Actually I'm trying to convert a string to a list of float numbers:
str = '53,20,4,2' to L = [53.0, 20.0, 4.0, 2.0]

str="53,20,4,2"
map(lambda s: float(s), str.split(','))

Last expression returns: [53.0, 20.0, 4.0, 2.0]
--
Happy Hacking.

Dmitry "Sphinx" Dzhushttp://sphinx.net.ru
Nice!

The following also works using split and list comprehension (as
suggested in a brazilian python forum):

-------------------
L = []
file = ['5,1378,1,9', '2,1,4,5']
str=''
for item in file:
L.append([float(n) for n in item.split(',')])
-------------------

Thank you for all suggestions!

May 12 '07 #13
"Cesar G. Miguel" <ce*********@gmail.comwrites:
I've been studying python for 2 weeks now and got stucked in the
following problem:

for j in range(10):
print j
if(True):
j=j+2
print 'interno',j

What happens is that "j=j+2" inside IF does not change the loop
counter ("j") as it would in C or Java, for example.
Granted this question has already been answered in parts, but I just
wanted to elaborate.

Although the python for/in loop is superficially similar to C and Java
for loops, they work in very different ways. Range creates a list
object that can create an iterator, and the for/in construct under the
hood sets j to the results of iterator.next(). The equivalent
completely untested java would be something like:

public ArrayList<Objectrange(int n){
a = new ArrayList<Object>; //Java 1.5 addition I think.
for(int x=0,x<n,x++){
a.add(new Integer(x));
}
return a;
}
Iterator i = range(10).iterator();

Integer j;
while i.hasNext(){
j = i.next();
system.out.println(j.toString());
j = j + 2;
system.out.println("interno" + j.toString());
}

This probably has a bunch of bugs. I'm learning just enough java
these days to go with my jython.

1: Python range() returns a list object that can be expanded or
modified to contain arbitrary objects. In java 1.5 this would be one
of the List Collection objects with a checked type of
java.lang.Object. So the following is legal for a python list, but
would not be legal for a simple C++ or Java array.

newlist = range(10)
newlist[5] = "foo"
newlist[8] = open("filename",'r')

2: The for/in loop takes advantage of the object-oriented nature of
list objects to create an iterator for the list, and then calls
iterator.next() until the iterator runs out of objects. You can do
this in python as well:

i = iter(range(10))
while True:
try:
j = i.next()
print j
j = j + 2
print j
except StopIteration:
break

Python lists are not primitive arrays, so there is no need to
explicitly step through the array index by index. You can also use an
iterator on potentially infinite lists, streams, and generators.

Another advantage to for/in construction is that loop counters are
kept nicely separate from the temporary variable, making it more
difficult to accidentally short-circuit the loop. If you want a loop
with the potential for a short-circuit, you should probably use a
while loop:

j = 0
while j < 10:
if j == 5:
j = j + 2
else:
j = j + 1
print j

>
Am I missing something?

[]'s
Cesar
--
Kirk Job Sluder
May 12 '07 #14
Cesar G. Miguel <ce*********@gmail.comwrote:
On May 12, 3:40 pm, Dmitry Dzhus <m...@sphinx.net.ruwrote:
Actually I'm trying to convert a string to a list of float numbers:
str = '53,20,4,2' to L = [53.0, 20.0, 4.0, 2.0]
str="53,20,4,2"
map(lambda s: float(s), str.split(','))

Last expression returns: [53.0, 20.0, 4.0, 2.0]
--
Happy Hacking.

Dmitry "Sphinx" Dzhushttp://sphinx.net.ru

Nice!
As somebody else alredy pointed out, the lambda is supererogatory (to
say the least).

The following also works using split and list comprehension (as
suggested in a brazilian python forum):

-------------------
L = []
file = ['5,1378,1,9', '2,1,4,5']
str=''
for item in file:
L.append([float(n) for n in item.split(',')])
The assignment to str is useless (in fact potentially damaging because
you're hiding a built-in name).

L = [float(n) for item in file for n in item.split(',')]

is what I'd call Pythonic, personally (yes, the two for clauses need to
be in this order, that of their nesting).
Alex
May 12 '07 #15
On May 12, 6:18 pm, "Cesar G. Miguel" <cesar.go...@gmail.comwrote:
Am I missing something?
Python for loops iterates over the elements in a container. It is
similar to Java's "for each" loop.

for j in range(10):
print j
if(True):
j=j+2
print 'interno',j

Is equivalent to:

int[] range = {0,1,2,3,4,5,6,7,8,9};
for (int j : range) {
system.out.writeln(j);
if (true) {
j += 2;
system.out.writeln("iterno" + j);
}
}

If I remember Java correctly...


May 12 '07 #16
On May 13, 12:13 am, a...@mac.com (Alex Martelli) wrote:
As somebody else alredy pointed out, the lambda is supererogatory (to
say the least).
What a wonderful new word!
I did not know what supererogatory meant, and hoped it had nothing to
do with Eros :-)
Answers.com gave me a meaning synonymous with superfluous, which
I think is what was meant here, but Chambers gave a wonderful
definition where they say it is from the RC Church practice of doing
more
devotions than are necessary so they can be 'banked' for distribution
to others (I suspect, that in the past it may have been for a fee or
a
favour).

Supererogatory, my word of the day.

- Paddy

P.S; http://www.chambersharrap.co.uk/cham...ry+&title=21st
May 13 '07 #17
Paddy <pa*******@googlemail.comwrote:
On May 13, 12:13 am, a...@mac.com (Alex Martelli) wrote:
As somebody else alredy pointed out, the lambda is supererogatory (to
say the least).

What a wonderful new word!
I did not know what supererogatory meant, and hoped it had nothing to
do with Eros :-)
Answers.com gave me a meaning synonymous with superfluous, which
I think is what was meant here,
Kind of, yes, cfr <http://www.bartleby.com/61/60/S0896000.html.
but Chambers gave a wonderful
definition where they say it is from the RC Church practice of doing
more
devotions than are necessary so they can be 'banked' for distribution
to others (I suspect, that in the past it may have been for a fee or
a favour).
"Doing more than necessary" may be wonderful in a devotional context,
but not necessarily in an engineering one (cfr also, for a slightly
different slant on "do just what's needed",
<http://en.wikipedia.org/wiki/You_Ain't_Gonna_Need_It>).
Supererogatory, my word of the day.
Glad you liked it!-)
Alex
May 13 '07 #18
On May 12, 8:13 pm, a...@mac.com (Alex Martelli) wrote:
Cesar G. Miguel <cesar.go...@gmail.comwrote:
On May 12, 3:40 pm, Dmitry Dzhus <m...@sphinx.net.ruwrote:
Actually I'm trying to convert a string to a list of float numbers:
str = '53,20,4,2' to L = [53.0, 20.0, 4.0, 2.0]
str="53,20,4,2"
map(lambda s: float(s), str.split(','))
Last expression returns: [53.0, 20.0, 4.0, 2.0]
--
Happy Hacking.
Dmitry "Sphinx" Dzhushttp://sphinx.net.ru
Nice!

As somebody else alredy pointed out, the lambda is supererogatory (to
say the least).
The following also works using split and list comprehension (as
suggested in a brazilian python forum):
-------------------
L = []
file = ['5,1378,1,9', '2,1,4,5']
str=''
for item in file:
L.append([float(n) for n in item.split(',')])

The assignment to str is useless (in fact potentially damaging because
you're hiding a built-in name).

L = [float(n) for item in file for n in item.split(',')]

is what I'd call Pythonic, personally (yes, the two for clauses need to
be in this order, that of their nesting).

Alex
Yes, 'str' is unnecessary. I just forgot to remove it from the code.

May 13 '07 #19
En Sat, 12 May 2007 20:13:48 -0300, Alex Martelli <al***@mac.comescribió:
Cesar G. Miguel <ce*********@gmail.comwrote:
>-------------------
L = []
file = ['5,1378,1,9', '2,1,4,5']
str=''
for item in file:
L.append([float(n) for n in item.split(',')])

The assignment to str is useless (in fact potentially damaging because
you're hiding a built-in name).

L = [float(n) for item in file for n in item.split(',')]

is what I'd call Pythonic, personally (yes, the two for clauses need to
be in this order, that of their nesting).
But that's not the same as requested - you get a plain list, and the
original was a list of lists:

L = [[float(n) for n in item.split(',')] for item in file]

And thanks for my "new English word of the day": supererogatory :)

--
Gabriel Genellina

May 14 '07 #20
Gabriel Genellina <ga*******@yahoo.com.arwrote:
En Sat, 12 May 2007 20:13:48 -0300, Alex Martelli <al***@mac.comescribió:
Cesar G. Miguel <ce*********@gmail.comwrote:
-------------------
L = []
file = ['5,1378,1,9', '2,1,4,5']
str=''
for item in file:
L.append([float(n) for n in item.split(',')])
The assignment to str is useless (in fact potentially damaging because
you're hiding a built-in name).

L = [float(n) for item in file for n in item.split(',')]

is what I'd call Pythonic, personally (yes, the two for clauses need to
be in this order, that of their nesting).

But that's not the same as requested - you get a plain list, and the
original was a list of lists:

L = [[float(n) for n in item.split(',')] for item in file]
Are we talking about the same code?! What I saw at the root of this
subthread was, and I quote:
L = []
file = ['5,1378,1,9', '2,1,4,5']
str=''
for item in file:
j=0
while(j<len(item)):
while(item[j] != ','):
str+=item[j]
j=j+1
if(j>= len(item)): break

if(str != ''):
L.append(float(str))
str = ''

j=j+1

print L
This makes L a list of floats, DEFINITELY NOT a list of lists.
And thanks for my "new English word of the day": supererogatory :)
You're welcome! Perhaps it's because I'm not a native speaker of
English, but I definitely do like to widen my vocabulary (and others').
Alex
May 14 '07 #21
En Mon, 14 May 2007 02:05:47 -0300, Alex Martelli <al***@mac.comescribió:
Gabriel Genellina <ga*******@yahoo.com.arwrote:
>But that's not the same as requested - you get a plain list, and the
original was a list of lists:
Are we talking about the same code?! What I saw at the root of this
subthread was, and I quote:
[...code painfully building a plain list...]

Oh, sorry, I got confused with another reply then.
>And thanks for my "new English word of the day": supererogatory :)
You're welcome! Perhaps it's because I'm not a native speaker of
English, but I definitely do like to widen my vocabulary (and others').
Me too!

--
Gabriel Genellina

May 14 '07 #22
Dmitry Dzhus skrev:
>Actually I'm trying to convert a string to a list of float numbers:
str = '53,20,4,2' to L = [53.0, 20.0, 4.0, 2.0]

str="53,20,4,2"
map(lambda s: float(s), str.split(','))

Last expression returns: [53.0, 20.0, 4.0, 2.0]
The lambda is not needed there, as float is a callable.

map(float, str.split(','))

--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
May 14 '07 #23

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Malcolm | last post by:
After some days' hard work I am now the proud possessor of an ANSI C BASIC interpreter. The question is, how is it most useful? At the moment I have a function int basic(const char *script,...
13
by: Pete | last post by:
I'm cross posting from mscom.webservices.general as I have received no answer there: There has been a number of recent posts requesting how to satisfactorily enable BASIC authorization at the...
5
by: Aussie Rules | last post by:
Hi, Having a mental block on this one. Have done it before but can't rack my brain on how... I have an object, with a bunch on property, and I add that object to a combo box. I want the...
4
by: Chris Asaipillai | last post by:
Hi there My compay has a number of Visual Basic 6 applications which are front endeed onto either SQL Server or Microsoft Access databases. Now we are in process of planning to re-write these...
3
by: Scott Stark | last post by:
Hello, I'm trying to get a better handle on OOP programming principles in VB.NET. Forgive me if this question is sort of basic, but here's what I want to do. I have a collection of Employee...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.