Turtlebot only rotates right? Syntax error?

Hi!
Very new with python here. What am I doing wrong?
The robot_control_class is copied from lesson 6. Rotate does seem to work, but my Turtlebot only decides to turn right… even when left > right?
I tried changing that syntax around but never figured it out…

from robot_control_class import RobotControl

rc = RobotControl()

def check_surroundings():

    front = rc.get_laser(360)

    left = rc.get_laser(719)

    right = rc.get_laser(0)

    print ("Front: ", front," / Left: ", left, " / Right: ", right)

def try_fwd():

    front = rc.get_laser(360)

    while front > 1:

        print ("Path is clear... going straight")

        rc.move_straight()

        front = rc.get_laser(360)

    else:

        print ("Something is in the way, I'll try turning")

        rc.stop_robot()

        try_turn()

        

def try_turn():

    print ("try_turn")

    check_surroundings()

    if left > right: #why does this always turn right?

        print ("Left is clear, I'll turn that way...")

        rc.rotate(-90)

        try_fwd()

    else:

        print ("Left is blocked so I'll turn right...")

        rc.rotate(90)

        try_fwd()

front = 0

left = 0

right = 0

check_surroundings()

try_fwd()

Hi @Higgs, welcome to our community.

The reason why the “if left > right” is always returning false is that both has 0 (zero) values.

The value assigned to “left” on “try_fwd” is not saved in the global variable.

If you have to use a variable defined outside a variable, you have to make the variable global.

Something like the example below, taken from W3 Schools:

x = "awesome"

def myfunc():
  global x
  x = "fantastic"

myfunc()

print("Python is " + x)

Thank you! This really helped me!
However I remembered something from lesson 5:

" IMPORTANT 3: From now on, you cannot use the global keyword in your programs. That is a very bad practice!!! Instead, you should organize your Python program to use classes that do not need global variables (instead, they use the variables of the class)."

So instead of adding global, I decided to add my variables and functions to the robot_control_class and I got it to work!

Thanks again!

1 Like