简体   繁体   中英

calling functions python from outside

I have small a python script looking something like this:

def number1():
    x = 1
    open_numbers = []
    open_numbers.append(x)
    return open_numbers

def myfunction(open_numbers):
    y = 1
    open_numbers.append(y)

I would like to call the myfunction in the the end of the script. Using

myfunction()

But it keeps telling me missing 1 required positional argument: 'open_numbers'

Tried passing the argument and got name 'open_numbers' is not defined

I plan to add more functions later and run them the same way

function(arg)
function2(arg)
function3(arg)

Solution

First of all, your code was not properly indented. I have corrected that.
The function myfunction takes in a list ( open_numbers ) as input and should return it as well.

I have passed in the output of number1() as the input to myfunction() . This should create a list: [1, 1] . And that's what it did.

def number1():
    x = 1
    open_numbers = []
    open_numbers.append(x)
    return open_numbers


def myfunction(open_numbers):
    y = 1
    open_numbers.append(y)
    return open_numbers

myfunction(number1())

Output :

[1, 1]

you need to pass in an object to your function. you can call your function with an empty list if you want:

a = []
myfunction(a)

You might want to define default parameter, and return the updated value

def myfunction(open_numbers = []):
    y = 1
    open_numbers.append(y)
    return open_numbers

Then you can call it with passing parameter myfunction([1]) or without myfunction()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM