【问题标题】:I want my the following code to perform a loop multiple times taking the new values?我希望我的以下代码多次执行循环以获取新值?
【发布时间】:2019-07-11 15:50:13
【问题描述】:

我在 python 中有一个代码。我希望它像循环一样运行多次。可以说20次。我会使用什么语法?

所以对于下面的代码,我希望它进入循环并多次倾斜函数并给我结果。

p1g = float(input("Player 1 Utility for green"))
p2r = float(input("Player 2 ulitity for red"))
p1r = float(input("Player 1 utility for red"))
p2g = float(input("Player 2 utility for green"))
d1 = float(input("Player 1 Disagreement point"))
d2 = float (input("Player 2 Disagreement point"))
"""Returns the slope and intercept of the payoff/utilities"""
i = 1
while i < 20:
 m = (p2g-p2r)/(p1r-p1g)
 c = p2r - ((p2g-p2r)/(p1r-p1g))* p1g
 nash_bargaining_x = -(p2r -d2 - m*p1g - m*d1)/2*m
 nash_bargaining_y = -(p2r -d2 - m*p1g - m*d1) + c # where c = p1g-p2r * ((p2g-p2r)/(p1r-p1g)
 solution = [nash_bargaining_x,nash_bargaining_y]
 print (solution)
 if abs(p1g-nash_bargaining_x) > abs(p1r-nash_bargaining_x):
     solution = "P1 has Red"
 else:
    solution = "P2 has red"
 print(solution)
 if solution in ["P1 has red"]:
  p1r = p1r + 25 and p1g = p1r - 20 and p2g = p2g - 15 and p2r = p2g + 35
 else:
  p1r = p1g + 25 and p1g = p1g -25 and p2g = p2r - 20 and p2r = p2r + 25

语法错误:无法分配给运算符

【问题讨论】:

  • a = b and c = d - 你认为这应该怎么做?

标签: python loops iteration


【解决方案1】:

p1r = p1r + 25 and p1g = p1r - 20 and p2g = p2g - 15 and p2r = p2g + 35

你可能是说

if solution == "P1 has red":
  p1r = p1r + 25
  p1g = p1r - 20
  p2g = p2g - 15
  p2r = p2g + 35

and是错误消息中的运算符;它用于计算布尔表达式,而不是连接一系列赋值运算符。)

【讨论】:

  • 谢谢。它确实运行了,但现在循环没有结束。这是我第一次使用循环,所以我不知道发生了什么。循环一直在进行,并且第 20 次没有停止
  • 要使循环停止,您需要在循环末尾添加语句i += 1。您当前正在循环,而 i&lt;20i 永远不会从 0 更改其值
  • 我确实这样做了,但它仍在无限运行。
  • 你永远不会 break 并且显然永远不会增加(或以其他方式使用)i 的值,所以 i &lt; 20 始终成立。如果你只想跑 20 次,你可以改用for _ in range(20): ...
  • 谢谢。是的,它确实工作了 20 次,但现在的问题是 IT 在运行程序时没有更新 p1r 或 p2g 的值。它只给了我 20 次相同的结果。
猜你喜欢
  • 2022-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多