遇到代码和程序流程问题

时间:2016-02-21 22:36:24

标签: python python-2.7

我要做的是在函数move中输入一个数字,如果参数大于前一个参数,则进行向上运动;如果参数低于前一个参数,则向下移动。但是如评论代码中所示,如果从.5移动到.125之后开始,它应该向下移动.375的差异。我得到的是运动总是在上升而且并没有修改变量'oldSteps'。 我可以得到一些新鲜的眼睛,帮助我弄清楚我做错了什么吗?

def move(n):
    numberEntered = float(n)
    stepPerRev = 400
    TPI = 4
    steps = int(( float( stepPerRev) * float( TPI ) ) * numberEntered)
    oldSteps = 0 # place holder for oldSteps
    if steps > oldSteps:    #turn ccw
        for i in range(steps - oldSteps):
            print i # turning code
        oldSteps -= steps
        print 'did %s steps up' % int(steps - oldSteps)
    if steps < oldSteps:    # turn cw        
        for i in range( oldSteps - steps ):
            print i # turning code
        oldSteps -= steps
        print 'did %s steps down' % int(oldSteps - steps)
    return 0
move(.5)    # move up 1/2 of inch
move(.125)    # move down from 1/2 to 1/8 of inch ( move 3/8 of inch)

2 个答案:

答案 0 :(得分:3)

你的问题不是很清楚。但是看看你的代码,当你在if steps < oldSteps之后调用move(.125)时,似乎你期望move(.5)成为现实。如果是这种情况,则不会发生这种情况,因为oldSteps始终会在重新调用0时重置为move()。函数内定义的变量不会在函数调用中保持其值。如果你想要这种行为,你必须将该状态存储在某个地方,理想情况是在函数之外。

我修改了你的代码,给你一个你可以做的事情的例子,但理想情况下,只需要避免全局语句并将你的状态存储在某些对象中,然后将其传递给move,或者使{{{ 1}}该对象的方法。

move()

如果您要重构它以使其更清洁并避免完全使用全局语句,那么您将如何执行此操作:

# Define your globals/Constants up top
stepPerRev = 400
TPI = 4
oldSteps = 0

def move(n):
    # Statment to specify you're modifying the /global/ oldSteps in this scope
    global oldSteps

    steps = stepPerRev * TPI * n

    if steps > oldSteps:    #turn ccw
        # Code for counterclockwise
        oldSteps -= steps
        print 'did %s steps up' % int(steps - oldSteps)

    if steps < oldSteps:    # turn cw        
        # Code for clockwise
        oldSteps -= steps
        print 'did %s steps down' % int(oldSteps - steps)

    return 0

# Test calls
move(.5)    # move up 1/2 of inch
move(.125)    # move down from 1/2 to 1/8 of inch ( move 3/8 of inch)

答案 1 :(得分:0)

<script src = "/javascripts/app.js"></script>
相关问题