Accept the function as an argument:

def rk4(diff,  # accept an argument of the function to call
        x, dt)
    k1=diff(x)*dt
    k2=diff(x+k1/2)*dt
    k3=diff(x+k2/2)*dt
    k4=diff(x+k3)*dt
    return x+(k1+2*k2+2*k3+k4)/6

Then, when you call rk4, simply pass in the function to be executed:

from rk4 import rk4
import numpy as np

def diff(x):
    return x

def mercury(u0,phi0,dphi):
    x=np.array([u0,phi0])
    dt=2
    x=rk4(diff,  # here we send the function to rk4
          x, dt)
    return x
mercury(1,1,2)

It might be a good idea for mercury to accept diff as an argument too, rather than getting it from the closure (the surrounding code). You then have to pass it in as usual - your call to mercury in the last line would read mercury(diff, 1, 1, 2).

Functions are 'first-class citizens' in Python (as is nearly everything, including classes and modules), in the sense that they can be used as arguments, be held in lists, be assigned to names in namespaces, etc etc.

Answer from Benjamin Hodgson on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_functions.asp
Python Functions
In Python, a function is defined using the def keyword, followed by a function name and parentheses:
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ function
Python Functions (With Examples)
Try Programiz PRO! ... A function is a block of code that performs a specific task. Suppose we need to create a program to make a circle and color it. We can create two functions to solve this problem: ... Dividing a complex problem into smaller chunks makes our program easy to understand and reuse.
Discussions

Just a quick beginner question! How are functions executed in Python?
Googled this: https://www.geeksforgeeks.org/understanding-the-execution-of-python-program/ More on reddit.com
๐ŸŒ r/learnpython
13
1
September 14, 2022
Python define function - Stack Overflow
Writing the code into main() function and adding the following line at the end of the code will make sure all the declared functions get loaded before start of the script. ... The reason this isn't working is because is_number() is being defined after it is accessed. When Python reaches that ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Which is more pythonic? Should I have a main() function?
Quick rule of thumb: default to using a main() function, but for very quick short scripts don't. For moderately complex code, using a main() function allows you to test the function directly from the interpreter easily. Also, if you define variables in an if __name__ == '__main__' block they'll be in the global scope, which pollutes the global namespace. This should be avoided for a bunch of reasons. On the other hand, if your main function is just a few lines of code and you don't expect it to get more complex, just putting it directly in the if __name__ == '__main__' block is better because it makes your code easier to read and understand. As a clear example, if your main() function is just a single line of code defining a separate function with an uninformative name like main() serves no real purpose other than to make someone reading the code have to go find that function to understand what's going on. More on reddit.com
๐ŸŒ r/learnpython
24
11
May 16, 2015
[Python] Why use a class instead of a basic function in the __main__ part of a script?
In this example using a class gains you absolutely nothing. I would imagine the idea is to show how you COULD use a class invocation as a script's entry point if you wanted to bind more functionality to it than simply calling a single function. The init method on that class could start the loop on a long-running process and define the exit conditions, for example. I can also imagine someone who doesn't want to put a ton of logic into the name==main block, and keep it clean looking at the bottom of the script. More on reddit.com
๐ŸŒ r/learnprogramming
46
17
September 16, 2024
๐ŸŒ
Real Python
realpython.com โ€บ python-main-function
Defining Main Functions in Python โ€“ Real Python
December 21, 2023 - This is because the __name__ variable had the value "best_practices", so Python did not execute the code inside the block, including process_data(), because the conditional statement evaluated to False. Now you are able to write Python code that can be run from the command line as a script and imported without unwanted side effects. Next, you are going to learn about how to write your code to make it easy for other Python programmers to follow what you mean. Many languages, such as C, C++, Java, and several others, define a special function that must be called main() that the operating system automatically calls when it executes the compiled program.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-functions
Python Functions - GeeksforGeeks
The idea is to put some commonly ... code contained in it over and over again. We can define a function in Python, using the def keyword....
Published ย  4 days ago
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ python โ€บ python_functions.htm
Python - Functions
A Python function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ just a quick beginner question! how are functions executed in python?
r/learnpython on Reddit: Just a quick beginner question! How are functions executed in Python?
September 14, 2022 -

Hi, everyone! I've picked up Python 6 hours ago. My previous experience (more than 15 year ago) was limited to Turbo Pascal and a little C.

A normal program for me would look like:

define function

begin

call function

end

My Python program looks like:

define function1

call function2

define function2

call function 3

define function3

if cond1 call function1

elif cond2 do nothing

else call function 3

some other code

AND IT WORKS! The program does what I ask it to do without any errors. Is this normal? Does a python program start with the first function it encounters even if it's not called main() ?

Find elsewhere
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ functions-python-tutorial
Python Functions: How to Call & Write Functions | DataCamp
November 22, 2024 - Python has built-in functions (like print()), user-defined functions (your custom creations), and anonymous functions (short-lived lambda functions). Parameters are placeholders in your function definition, and arguments are the actual values you pass when calling the function. A lambda function is a one-liner, nameless function for quick tasks. The __main__ function keeps your code organized and ensures specific parts only run when the script ...
๐ŸŒ
Real Python
realpython.com โ€บ defining-your-own-python-function
Defining Your Own Python Function โ€“ Real Python
June 11, 2025 - A Python function is a named block of code that performs specific tasks and can be reused in other parts of your code. Python has several built-in functions that are always available, and you can also create your own.
Top answer
1 of 5
4

You should simply move the function above the place that calls it, or put the loop in a function of its own. The following works fine, because the name is_number inside check_lines is not resolved until the function is called.

def check_lines(lines):
    for check in lines:
        if is_number(check):
            print ("number: " + check)
        else:
            print ("String!" + check)

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False;

check_lines(lines)

In my Python scripts, I always define the functions at the top, then put a few lines of code calling them at the bottom. This convention makes it easy to follow the control flow, because it's not interspersed with definitions, and it also makes it easier to later reuse your script as a module, which is similar to a Java package: just look at the "script" code near the bottom and remove that to get an importable module. (Or protect it with an if __name__ == '__main__' guard.)

2 of 5
0

Actually, Python does act like C. The difference is, in C, before anything in module is executed, the entire file is compiled. In Python, it's run.

So, the following will work, just as it will in C:

def f(x):
    return f2(x) + 1

def f2(x):
    return x*2

The function definitions just load the code - they don't check anything in there for existence. So even though f2 doesn't exist yet when f is first seen, when you actually call f, f2 does exist in the module scope and it works fine.

This doesn't work:

print f2(x) + 1

def f2(x):
    return x*2

In this case, when the module is loaded, it is being interpreted. So if it hits a print, it will execute it immediately. This can be used to your benefit, but it does cause a problem here, since we'll lookup f2 immediately and try to dereference it, and it won't exist yet.

๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ how-to-define-functions-in-python-3
How To Define Functions in Python 3 | DigitalOcean
August 20, 2021 - A function is a block of instructions that, once defined, both performs an action once the function is called and makes that action available for later use. โ€ฆ
๐ŸŒ
Learn Python
learnpython.org โ€บ en โ€บ Functions
Functions - Learn Python - Free Interactive Python Tutorial
Functions in python are defined using the block keyword "def", followed with the function's name as the block's name.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ how-to-define-and-call-functions-in-python
How to Define And Call Functions in Python
December 11, 2025 - Defining a function in Python involves two main steps: defining the function and specifying the arguments it takes.
๐ŸŒ
Stanford CS
cs.stanford.edu โ€บ people โ€บ nick โ€บ py โ€บ python-function.html
Python Functions
Here is an example Python function named "foo". This function doesn't do anything sensible, just shows the syntax of a function. ... name - def is followed by the function's name, here foo The name is chosen by the programer to reflect what the function does Here "foo" is just a CS nonsense word ยท parenthesis - the name is followed by a pair of parenthesis and a colon (): Functions and parenthesis pairs () frequently go together in Python syntax
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-functions-define-and-call-a-function
Python Functions โ€“ How to Define and Call a Function
March 16, 2022 - I will also show you how arguments and the return keyword works in Python functions. In Python, you define a function with the def keyword, then write the function identifier (name) followed by parentheses and a colon.
๐ŸŒ
Guru99
guru99.com โ€บ home โ€บ python โ€บ how to call a function in python (example)
How to Call a Function in Python (Example)
August 12, 2024 - The function print func1() calls our def func1(): and print the command โ€ I am learning Python function None.โ€œ ยท There are set of rules in Python to define a function.
๐ŸŒ
Python Central
pythoncentral.io โ€บ python-define-function
Python Define Function: Step-by-Step Instructions | Python Central
May 1, 2025 - Indent the function body. Optionally use "return" to send a result back. Once you have defined a function, you can call it (reference it) by using its name followed by parentheses.
๐ŸŒ
Python Beginners
python-adv-web-apps.readthedocs.io โ€บ en โ€บ latest โ€บ functions.html
Functions in Python โ€” Python Beginners documentation
Everything will work fine except the last two lines. If you run the script, youโ€™ll see what the two functions print: ... Traceback (most recent call last): File "f_scope_global_vs_local.py", line 20, in <module> print(food) NameError: name 'food' is not defined
๐ŸŒ
University of Washington
faculty.washington.edu โ€บ rjl โ€บ classes โ€บ am583s2014 โ€บ notes โ€บ python_scripts_modules.html
Python scripts and modules โ€” AMath 483/583, Spring 2013 1.0 documentation
June 5, 2014 - >>> execfile('script1.py') x f(x) 0.000 1.000 2.000 5.000 4.000 17.000 >>> f <function f at 0x1c0430> >>> np <module 'numpy' from '/Library/Python/2.5/site-packages/numpy-1.4.0.dev7064-py2.5-macosx-10.3-fat.egg/numpy/__init__.pyc'> In this case f and np are in the namespace of the interactive session as if we had defined them at the prompt.
๐ŸŒ
APXML
apxml.com โ€บ courses โ€บ python-for-beginners โ€บ chapter-5-building-blocks-functions โ€บ python-defining-functions
Defining Python Functions | def Statement
Welcome to Python functions. Function call finished. Notice how the lines inside greet_user were only executed when greet_user() was called. You can call this function multiple times from different parts of your program, achieving code reuse. # Define the function (usually done near the top of a script) def greet_user(): print("Hello there!") print("To Python functions.") # Call it once print("First greeting:") greet_user() # Maybe do some other work here...