Python mange with liste

Rustom Mody rustompmody at gmail.com
Sun Dec 29 11:47:00 CET 2013


On Sun, Dec 29, 2013 at 3:49 PM, Bala Ji <baladjy at gmail.com> wrote:
>
>
> 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

Ok lets start with

1.

l = len(names)
for i in range(0,l): ... names[1] ...

Better to do in python as

for n in names: ... n ...
ie use n where you were using names[i]
no need for range, len, indexing etc etc

2.
You are setting (ie assigning) message each time round the loop
Try writing a function that does NO set (assign) NO print

Ok this time let me write it for you
So I write a function called foo, taking an argument called nn
>>> def foo(nn):
...   for n in names:
...     if n == nn: return True
...   return False
...

Note: No input, No output, No file IO and above all No assignment

>>> foo(("nam1","F","Y"))
True
>>> foo(("nam4","F","Y"))
False

Notice my foo takes an argument that is a triplet
You need to change foo to taking name and sex and ignoring the third element

Your homework -- Oui??



More information about the Python-list mailing list