Python mange with liste

Frank Millman frank at chagford.com
Sun Dec 29 12:02:18 CET 2013


"Bala Ji" <baladjy at gmail.com> wrote in message 
news:11c1b4ef-07a3-4424-b356-9a9cf635f787 at googlegroups.com...
>
>
> hello,
>
> thank you for your help
>
> i wrote this:
>
> x="nam1"
> y="F"
>
> names = [("nam1", "F", "Y"), ("nam2", "M", "N")]
> l = len(names)
> for i in range(0,l):
>     print names[i][0]
>     print names[i][1]
>     if x == names[i][0] and y == names[i][1]:
>         message = "right"
>     else:
>         message = "wrong"
>
> print message
>
>
> normally it must tell me "right" but it tells me "wrong"
>
> best

Your problem is that, after you find a valid name, you continue looping, and 
then find an invalid name, so the message is over-written.

The usual way to terminate a loop without continuing to the next item is 
with the 'break' statement.

Here are three variations of your code, each with an improvement over the 
previous one -

1. This adds the break statement - it should do what you want -
l = len(names)
for i in range(0,l):
    print names[i][0]
    print names[i][1]
    if x == names[i][0] and y == names[i][1]:
        message = "right"
        break
    else:
        message = "wrong"

2. This uses a feature of python which specifies an action to be taken only 
if the loop continues to the end without interruption -
l = len(names)
for i in range(0,l):
    print names[i][0]
    print names[i][1]
    if x == names[i][0] and y == names[i][1]:
        message = "right"
        break
else:
    message = "wrong"

Note that the last two lines are indented to line up with the 'for ' 
statement. In the previous version, message is set to 'wrong' for every 
iteration of the loop until a valid name is found. In this version, it is 
only set to 'wrong' if no valid name is found.

3. This uses a feature of python which allows you to iterate over the 
contents of a list directly -
for name in names:
    print name[0]
    print name[1]
    if x == name[0] and y == name[1]:
        message = "right"
        break
else:
    message = "wrong"

Hope this gives you some ideas.

Frank Millman






More information about the Python-list mailing list