while loop is not reading the variable

Stat_prob_001
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.)

Aviv Shai

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Awk breaks when reading variable in while-loop

From Dev

Awk breaks when reading variable in while-loop

From Dev

Reading a finite input from user through while loop into an integer variable

From Dev

unexpected behavior of while loop variable with scanf reading string

From Dev

For loop reading empty variable

From Dev

For loop reading empty variable

From Dev

Inifnite loop while reading numbers

From Dev

While Loop with hasNextInt() actually reading?

From Dev

Infinite Loop while reading a file

From Dev

Shell script loop while not reading

From Dev

Variable While Loop

From Dev

While loop flag variable

From Dev

Undefined variable in the while loop

From Dev

Reading a variable in a for loop in a bat file

From Dev

Infinite loop while reading integers from file

From Dev

How to break a loop in scala while reading a file?

From Dev

while loop and reading from console in java

From Dev

Infinity loop while reading data from file

From Dev

Infinite loop while reading integers from file

From Dev

While loop - reading two lines at a time

From Dev

Reading space seperated string into array in while loop

From Dev

Why the variable is cut while reading a file?

From Dev

Is it valid to rebind a variable in a while loop?

From Dev

Call variable outside while loop

From Dev

SQL concatenate variable in a while loop

From Dev

Is it possible to assign a variable in a while loop?

From Dev

While loop and checking static variable

From Dev

A variable in the while loop doesnt change

From Dev

Setting A Variable in A While Loop in Bash