繁体   English   中英

Python if-else语句顺序

[英]Python if-else statement order

我的问题与此类似: Python if-elif语句顺序但答案是:

    #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语句输入到list direction = []中? 它是有效的数据类型吗? 编辑:我想知道我将如何能够应用上面的代码。 假设在迷宫中有一个对象a,当它到达一个交叉点时,这就是我的代码:

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

但是这段代码意味着他总是会一直向前走,然后向左,向右等等。我希望它的方向是随机的,以便他可以先向右/向前/向左走。

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)]

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

# 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语句是顺序的。 尽管我们将其称为分支,但实际上它是按顺序分支的,只是跳过了一些带有条件的语句。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM