Python while循环不能正常工作

时间:2016-07-13 15:53:04

标签: python while-loop

这是我的代码:

def pressC():
    """ Wait for "c" to be entered from the keyboard in the Python shell """
    entry = " "
    while(entry != "c"):
        entry = raw_input("Press c to continue. ")
    print("Thank you. ")
    print

def unstuck():
    """ This gets the robot unstuck if it becomes stalled by hitting a wall   """
    stalls = 0
    while timeRemaining(120):
        stallStatus = getStall()
        if(stallStatus == 1):
            backward(1,1)
            turnRight(1,1.7145)
            stalls = stalls + 1
            return stalls
        else:
            forward(1,1)
    stop()

def printResults(stalls):
    """ This function prints the amount of times the robot stalled """
    print
    print ("The amount of stalls that occured: " + str(stalls) + ". ")

def main():
    pressC()
    numStalls = unstuck()
    printResults(numStalls)

main()    

所以,我在myro模拟器上运行代码,用户定义的unstuck()函数只运行一次,然后打印机器人只停止一次。第一个while循环正常运行,但第二个while循环没有运行。无论如何,我想让它运行我输入的120秒。我需要帮助!

1 个答案:

答案 0 :(得分:1)

您的return声明位置错误。试试这个:

# This gets the robot unstuck if it is stalled
def unstuck():
    """ This gets the robot unstuck if it becomes stalled by hitting a wall """
    stalls = 0
    while timeRemaining(120):
        stallStatus = getStall()
        if(stallStatus == 1):
            backward(1,1)
            turnRight(1,1.7145)
            stalls = stalls + 1
        else:
            forward(1,1)
    stop()
    return stalls