Python if-else语句顺序

时间:2017-09-12 00:08:33

标签: python if-statement random

我的问题与此类似:Python if-elif statements order但答案是:

    #this was the answer given from the question I linked 
    directions = []
        if <the obstacle has a free tile on its RIGHT>:
              directions.append(move_right)
        if <the obstacle has a free tile on its LEFT>:
              directions.append(move_left)

    if not directions:
          stop()
    else:
         random.choice(directions)()

现在,我的问题是如何将if语句输入列表方向= []? 它是有效的数据类型吗? 编辑:我想知道我将如何应用上面的代码。假设在迷宫中存在物体a,当它到达交叉点时,这就是我的代码:

   if (a is in intersection):
        a.forward()
   elif (forward().doesntexist):
        a.left()
   elif (left().doesntexist):
        a.right()
  ......

但是这段代码意味着他总是先行前进,然后是左,右等等。我希望它的方向是随机的,他可能先行/前进/左转。

2 个答案:

答案 0 :(得分:0)

import sys
import random

# example for a "free tile"
free_tile = (0,5)

def move_right():
    my_pos = free_tile
    return my_pos

def move_left():
    my_pos = free_tile
    return my_pos

def stop():
    print 'bye!'
    sys.exit(0)

directions = []

if free_tile == (0,5):
    print 'moving right'
    directions.append(move_right())

if free_tile == (0,6):
    print 'moving left'
    directions.append(move_left())

elif not directions:
    print 'no directions...exiting...'
    stop()
else:
    print random.choice(directions)

print 'current location', directions

演示:

moving right
(0, 5)
current location [(0, 5)]

答案 1 :(得分:0)

我认为你需要的只是一些评论:

# init list
directions = []

# insert all possible directions into the list
# !!! NO else/elif here !!!
if ((forward possible)):
    directions.append(forward)
if ((left possible)):
    directions.append(left)
if ((right possible)):
    directions.append(right)

# now we have all possible directions
# stop if empty
if not directions:
      stop()
# otherwise randomly choose one
else:
     random.choice(directions)()

if - else语句是连续的。虽然我们会调用那个分支,但它实际上是用顺序分支,只是跳过一些带条件的语句。