我正在尝试创建一个运行基本模拟的程序。创建一排十个盒子,让随机数发生器选择他移动的方向,并跟踪他。最近一段时间的问题是初始位置不友好。我想从中间开始——五个——但无论我把那条线放在哪里,我都会出错。
这是代码:
import random
def right_movement():
p = p + 1
m = m + 1
times[p] = p
print times
def left_movement():
p = p - 1
m = m + 1
times[p] =+ 1
def main():
p = 5
times = [0] * 11
times[p] = 1
m = 0
print times
while p >= 0 and p <= 10:
x = random.randint(0, 1)
if x > 0:
right_movement()
else:
left_movement()
if p == 11:
print "Movement to the right into location 11."
print "Number of moves is " + m + "."
else:
print "Movement to the left into location 0."
print "Number of moves is " + m + "."
main()
无论我把它放在哪里p = 5
,我都会得到一个错误的参考。我正在运行 Python 2.7。