猿问

while 循环未读取变量

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

如果我把代码运行顺利,s=1但由于 while 循环是 for s!=0,如果我从s=0循环开始甚至没有运行。那么,在这种情况下,当我必须运行s=0. (或者更准确地说,我需要 while 循环读取s=0是第二次。)


万千封印
浏览 140回答 3
3回答

泛舟湖上清波郎朗

另一个解决方案很棒。这是一种不同的方法:import numpy as npdef RVs():&nbsp; &nbsp; # s = 0&nbsp; &nbsp; s = 1&nbsp; &nbsp; f = 0&nbsp; &nbsp; while True: # will always run the first time...&nbsp; &nbsp; &nbsp; &nbsp; z = np.random.random()&nbsp; &nbsp; &nbsp; &nbsp; if z <= 0.5:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x = -1&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x = 1&nbsp; &nbsp; &nbsp; &nbsp; s = s + x&nbsp; &nbsp; &nbsp; &nbsp; f = f + 1&nbsp; &nbsp; &nbsp; &nbsp; if s == 0: break # ... but stops when s becomes 0&nbsp; &nbsp; return(f)RVs()注意:return(f)需要在原始代码中缩进才能在RVs函数内。

扬帆大鱼

据我所知,您正在尝试模拟 do while 循环,该循环将至少运行一次(并且您希望 s 的起始值为 0)如果是这种情况,您可以无限地运行循环并在条件为真时中断循环。例如:while True:&nbsp; &nbsp; #code here&nbsp; &nbsp; if (s != 0):&nbsp; &nbsp; &nbsp; &nbsp; break这将至少运行一次您的循环,并在最后再次运行循环,直到您的条件通过

梦里花落0921

Python 没有 do.... while() 和其他语言一样。所以只需使用“第一次”操作符。import numpy as npdef RVs():&nbsp; &nbsp; s = 0&nbsp; &nbsp; t = 1 # first time in loop&nbsp; &nbsp; f = 0&nbsp; &nbsp; while s!=0 or t==1:&nbsp; &nbsp; &nbsp; &nbsp; t = 0 # not first time anymore&nbsp; &nbsp; &nbsp; &nbsp; z = np.random.random()&nbsp; &nbsp; &nbsp; &nbsp; if z<=0.5:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x = -1&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x = 1&nbsp; &nbsp; &nbsp; &nbsp; s = s + x&nbsp; &nbsp; &nbsp; &nbsp; f = f + 1return(f)RVs()
随时随地看视频慕课网APP

相关分类

Python
我要回答