0
import numpy as np
def RVs():
   #s = 0
    s = 1
    f = 0
    while s!=0:
        z = np.random.random()
        if z<=0.5:
            x = -1
        else:
            x = 1
        s = s + x
        f = f + 1
    return(f)
RVs()

The code is running smoothly if I put s=1 but since the while loop is for s!=0, if I start with s=0 the loop is not even running. So, what should I do in this case when I have to run the code for s=0. (Or more precisely, I need to while loop to read s=0 is the second time.)

0

4 Answers 4

3

The other solution is great. Here's a different approach:

import numpy as np

def RVs():
    # s = 0
    s = 1
    f = 0

    while True: # will always run the first time...
        z = np.random.random()

        if z <= 0.5:
            x = -1
        else:
            x = 1

        s = s + x
        f = f + 1

        if s == 0: break # ... but stops when s becomes 0

    return(f)

RVs()

Note: return(f) needs to be indented in your original code to be inside the RVs function.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the solution (abt the indented error, actually my copy paste went wrong, I edited it now)
2

From what I can understand you are trying to emulate a do while loop, where the loop will run at least one time(and you want the starting value of s to be 0)

If this is the case you can run the loop infinitely and break from the loop if your condition is true. For example:

while True:
    #code here
    if (s != 0):
        break

this will run your loop no matter what at least once, and will run the loop again at the end until your condition passes

Comments

1

Python does not have a do.... while() as in other languages. So just use a "first-time" operator.

import numpy as np
def RVs():
    s = 0
    t = 1 # first time in loop
    f = 0
    while s!=0 or t==1:
        t = 0 # not first time anymore
        z = np.random.random()
        if z<=0.5:
            x = -1
        else:
            x = 1
        s = s + x
        f = f + 1
return(f)
RVs()

Comments

1

Try this:

import numpy as np
def RVs():
   #s = 0
    s = 1
    f = 0
    while s!=0 or f==0: #will always run it the first time
        z = np.random.random()
        if z<=0.5:
            x = -1
        else:
            x = 1
        s = s + x
        f = f + 1
    return(f)
RVs()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.