Why do I need to assign the local variable?

Respected Prof,
Why does my code throw the following error and what’s the solution? I tried a lot and went throw some queries in the form to get some clue. I realized others had called the function in the same manner as I did, and they didn’t complain about error. I tried google too but couldn’t get my head around this.

Below is my code:
#! /usr/bin/env python

import rospy
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan

def callback(msg):

rospy.init_node('topics_quiz_node', anonymous = True)
pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
sub = rospy.Subscriber('/kobuki/laser/scan', LaserScan, callback)

rate = rospy.Rate(2)
move = Twist()

def decide_direction(ranges):

straight = ranges[360]
left = ranges[719]
right = ranges[0]

if straight > 1:
if (straight < 1) or (right < 1):
if left < 1:

def turn_left():
    move.linear.x = 0
    move.angular.z = 0.2

def turn_right():
    move.linear.x = 0
    move.angular.z = -0.2
def straight_motion():
    move.linear.x = 0.6
    move.angular.z = 0


Hi @abdulbasitisdost,

Try moving all your functions to the top of the file, ordering them in the order you expect them to be called. You may try this order:


Then put the rest of the code under the functions.

1 Like

Thank you so much Professor bayode
It worked. But would you please tell me why:

  1. Why did my order throw that error above ?
  2. Why did you give this order above(which worked) where you put turn_left on top then turn_right, then straight_motion, then decide_direction, then call_back ? Why this specific order…

The simple rule is that you need to define a function before you try to use it (by calling it), because the code is run from top to bottom. There can be other arrangements besides the one I have given, but any order must respect this rule.

Thanks a lot. I had forgotten such a basic rule of functions. Really appreciate your kind response