Python while循环,如果那时条件不能正常工作

问题描述 投票:-5回答:1

我是Python新手并尝试我的第一个while循环。

下面的代码用于迭代用户在number_of_moves变量中定义的已定义公式。

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

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

实际上,else语句x2应该等于前一次迭代的输出x1x3应该等于x2输出的值...依此类推......使用这个公式(22695477 * x2 + 1) % 2 ** 31

print("Choose the type of game(1:Easy;2 Difficult)")
levelinput = int(input())

print("")


print("Enter the number of moves")

number_of_moves = int(input())
i =1
x = 79
randomvalue = (22695477*x+1)%2**31
x2 = randomvalue
machine = int()


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

    move_selection = int(input())

    if i  == 1:
        randomvalue = (22695477*x+1)%2**31

    else:
        randomvalue = (22695477*x2+1)%2**31

    i = i +1


    if randomvalue <= 2**31:
        machine == int(0)
    else:
        machine == int(1)

    def resultgame (move_selection,machine):
        if move_selection == machine:
            return("Computer Wins")
        else:
            return("Player Wins")

    result = resultgame

    print("player = ", move_selection, "machine = ", machine,"-", result(move_selection,machine))
python loops while-loop
1个回答
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)

我编写的代码存在很大问题,但我并不完全明白你要实现的是什么。也许有关游戏的更多信息会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.