python return - “name not defined”

后端 未结 3 1111
青春惊慌失措
青春惊慌失措 2021-01-27 07:12

I\'m trying to get this script to write information into a basic text file. I\'m still learning python.

The problem lies here:

file_text = \"\"\"%s SHOOT         


        
相关标签:
3条回答
  • 2021-01-27 07:36

    This looks like a scope issue. Variables declared inside functions are only defined within that function. To fix it, put the declaration of the variable on the same scope as where it is used. See below for the sample code

    number_of_details = 0
    
    def detailformation():
        number_of_details = number_of_firers / number_of_lanes
        return number_of_details
    
    file_text = """%s SHOOT DETAILS\n
    Number of shoots:\t %s
    Maximum range:\t %s
    Number of firers:\t %s
    Number of lanes active:\t %s
    Number of details:\t %s
    Troops per detail:\t %s
    \n 
    RANGE STAFF
    Ammo NCO:\t %s
    Medical Supervisor:\t %s
    IC Butts:\t %s""" % (shoot_name, number_of_shoots, max_range, number_of_firers, number_of_lanes, number_of_details, size_of_details, ammo_nco, medical_supervisor, ic_butts)
    

    Note that this is just a quick solution (putting the variable on the global scope).

    0 讨论(0)
  • 2021-01-27 07:37

    Call your functions in order to get the value they return

    size_of_details = detailsizer() 
    
    0 讨论(0)
  • 2021-01-27 07:39

    The variables only exist in the scope you declare them

    def fun():
        x = 5
        return x
    
    >>> x
    Traceback (most recent call last):
      File "<pyshell#4>", line 1, in <module>
        x
    NameError: name 'x' is not defined
    

    If you want to use the return value from a function, then call the function and assign it to such a variable

    >>> x = fun()
    >>> x
    5
    
    0 讨论(0)
提交回复
热议问题