Another stupid newbie question

Benjamin Niemann pink at odahoda.de
Fri Feb 17 14:26:51 EST 2006


Byte wrote:

> How can I make the following code:
> 
> from random import random
> 
> 
> 
> def stuff(a, mx):
>     x = 2
>     while x == 2:
>         x = random()
>         if x == mx: print x
>         else: print 'No luck,', x
>         x = 2
> 
> Stop when x == mx?

What's the intention behind setting x = 2 at all?

def stuff(a, mx):
    while True:
        x = random()
        if x == mx: print x
        else: print 'No luck,', x

Should do the same as you're code above.

If stuff will never be called with mx=None, I would suggest using

def stuff(a, mx):
    x = None
    while x != mx:
        x = random()
        if x == mx: print x
        else: print 'No luck,', x

Also note that random() returns a float and it is *very* unlikely that the
condition x == mx will ever come true

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://www.odahoda.de/



More information about the Python-list mailing list