[Tutor] New to this list ....
Prasad, Ramit
ramit.prasad at jpmorgan.com
Fri Mar 30 18:22:56 CEST 2012
> > Hi there .... I've just joined this list and thought I'd introduce
myself.
Welcome!
> > correct = 0
> > match = 0
> > wrong = 0
> > results = [correct, match, wrong]
> >
> > results = getflag(flag_1, results)
> > results = getflag(flag_2, results)
> > results = getflag(flag_3, results)
> > results = getflag(flag_4, results)
>> def getflag(thisflag, results):
>> if (thisflag == 2):
>> results[0] += 1
>> elif (thisflag == 1):
>> results[1] += 1
>> elif (thisflag == 0):
>> results[2] += 1
>> return(results)
>>
>> In c, I would have used switch and case, but I gather there is no direct
>> equivalent in Python ... But it works as is.
C switch is just a different way of doing an if/elif tree, I do not
really see any real difference. Although, if there is you can feel free
to enlighten me. :)
Unlike C, the parenthesis in if statements and returns are not necessary.
> if (thisflag == 2):
becomes
if thisflag == 2:
> return(results)
becomes
return results
Furthermore, the way Python binds names means that modifying the list
in getflags modifies it in the callee. No need to return and reassign
results.
>>> def foo(x):
... x[0] += 1
...
>>> bar = [ 1, 3, 4 ]
>>> foo( bar )
>>> print bar
[2, 3, 4]
>>> foo( bar )
>>> print bar
[3, 3, 4]
Be careful of "results = [0] * 3". This style works fine for immutable
types (int, float, str) but does not work as people new to Python think
it does.
>>> def foo(x):
... x[0][0] += 1
...
>>> bar = [ [0] ]*3
>>> print bar
[[0], [0], [0]]
>>> foo( bar )
>>> print bar
[[1], [1], [1]]
>>> foo( bar )
>>> print bar
[[2], [2], [2]]
This occurs because bar is a list containing 3 elements which are
all the exact same object. Modifying one sub-list will modify the
"others" as well.
Ramit
Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423
--
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.
More information about the Tutor
mailing list