Python while循环,如果条件不正确

时间:2018-09-16 11:09:44

标签: python loops while-loop

我是Python的新手,正在尝试我的第一个while循环。

以下代码旨在迭代用户在number_of_moves变量中定义的定义公式。

i = 1时,它应该执行一个公式,但是当i > 1时,它应该执行另一个公式。因此,我在公式内定义了一个 if else语句

问题是,当i > 1时,它没有选择第二个公式,而是继续使用第一个定义的公式,即(22695477 * x + 1) % 2 ** 31

有效地, else语句 x2应该等于上一次迭代x1的输出,而x3应该等于{{ 1}}……等等……使用此公式x2

(22695477 * x2 + 1) % 2 ** 31

1 个答案:

答案 0 :(得分:1)

好吧,您以最好的方式编写的代码不好。

def LinearCong (x,x2):
  if i == 1:
    randomvalue = (22695477*x+1)%2**31
  else:
    randomvalue = (22695477*x2+1)%2**31

  return randomvalue

 x2 = randomvalue
 i+=1

不应将此函数放入while循环或与此有关的任何循环中。现在,我建议您忘记使用函数,即def function(): 虽然您所编写的语法在某种程度上是正确的,但丝毫没有正确实现。

以下是我对您尝试做的事情的解释。

i =1
number_of_moves = 10
x = 10000

#problem understanding
#included a randomvalue variable here becaause you want it to be assigned to var x2
#unless randomvalue is declared here the else statement would never work
randomvalue = (22695477*x+1)%2**31
x2 = randomvalue

while i <= number_of_moves:
    print("")
    print("Choose your move number", i ,"(0 or 1)")
    move_selection = int(input())

    if move_selection == 1:
        randomvalue = (22695477*x+1)%2**31
        break
    else:
        #here you are asking for var x2 which would have no value unless declared above
        #randomvalue as a variable is created here so x2 would have nothing to refer to
        randomvalue = (22695477*x2+1)%2**31
        #in this case, we are reassigning our already declared variable
        break

print(randomvalue)

我编写的这段代码有很多问题,但是我不完全了解您要实现的目标。也许有关游戏的更多信息会有所帮助。