Python 而循环未读取变量 将numpy导入为np def RVs(): #s=0 s=1 f=0 而s=0: z=np.random.random() 如果z

Python 而循环未读取变量 将numpy导入为np def RVs(): #s=0 s=1 f=0 而s=0: z=np.random.random() 如果z,python,python-3.x,while-loop,Python,Python 3.x,While Loop,请尝试以下操作: 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() 将num

请尝试以下操作:

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()
将numpy导入为np
def RVs():
#s=0
s=1
f=0
而s=0或f==0:#将始终在第一次运行它
z=np.random.random()

如果z据我所知,您正在尝试模拟do while循环,其中循环将至少运行一次(并且您希望s的起始值为0)

如果是这种情况,您可以无限地运行循环,如果您的条件为真,则可以从循环中断。例如:

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()

无论发生什么情况,这将至少运行一次循环,并在结束时再次运行循环,直到您的条件通过。

另一种解决方案非常好。这里有一种不同的方法:

while True:
    #code here
    if (s != 0):
        break
将numpy导入为np
def RVs():
#s=0
s=1
f=0
虽然为True:#将始终第一次运行。。。
z=np.random.random()

如果zPython没有do。。。。while()与其他语言一样。所以只需使用“首次”操作符

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()
将numpy导入为np
def RVs():
s=0
t=1#循环中的第一次
f=0
而s=0或t==1:
t=0#不再是第一次了
z=np.random.random()
如果zthanks为解决方案(关于缩进错误,实际上我的复制粘贴出错,我现在编辑了它)
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()