[Tutor] Random Number Game: Returns always the same number - why?
Prasad, Ramit
ramit.prasad at jpmorgan.com
Thu May 30 20:26:02 CEST 2013
[Reordered response to after quote]
Thomas Murphy wrote:
>
>
> > There are a few issues here:
> > * variable names should be lower case
> > * for this case it's best to use for loop with range()
> > * you calculate random number only once, outside of loop
> >
> > Try something like:
> >
> > for count in range(100):
> > print random.randint(1, 100)
> >
> >
> > -m
>
> Mitya,
> Why is it best in this situation to use range() rather than a while
> loop? Curious about best practices for the various iterating
> functions. Thanks!
This is not really a case of "range" vs. "while" loops, it is really
"while" vs "for" loops. In general, you should use "for" loops when
you know the number of times to loop up front. "While" loops should
be used when you are unsure how many times you need to loop.
"For" loops are good for use with iterables (lists, strings, sequences).
"While" loops are good for processing until some state is achieved.
In C, it was very easy to interchange "for" and "while" loops, and
while it can probably be done in Python it may require a bit more work.
~Ramit
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