I assume do_this and do_that are actually dependent on some argument of foo, since otherwise you could just move them out of foo and call them directly.

I suggest reworking the whole thing as a class. Something like this:

class Foo(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def do_this(self):
        pass

    def do_that(self):
        pass

    def __call__(self):
        self.do_this()
        self.do_that()

foo = Foo(x, y)
foo()
foo.do_this()
Answer from Lauritz V. Thaulow on Stack Overflow
Top answer
1 of 7
33

I assume do_this and do_that are actually dependent on some argument of foo, since otherwise you could just move them out of foo and call them directly.

I suggest reworking the whole thing as a class. Something like this:

class Foo(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def do_this(self):
        pass

    def do_that(self):
        pass

    def __call__(self):
        self.do_this()
        self.do_that()

foo = Foo(x, y)
foo()
foo.do_this()
2 of 7
20

These previous answers, telling you that you can not do this, are of course wrong. This is python, you can do almost anything you want using some magic code magic.

We can take the first constant out of foo's function code, this will be the do_this function. We can then use this code to create a new function with it.

see https://docs.python.org/2/library/new.html for more info on new and https://docs.python.org/2/library/inspect.html for more info on how to get to internal code.

Warning: it's not because you CAN do this that you SHOULD do this, rethinking the way you have your functions structured is the way to go, but if you want a quick and dirty hack that will probably break in the future, here you go:

import new
myfoo = new.function(foo.func_code.co_consts[1],{}) 
myfoo(x,y) # hooray we have a new function that does what I want

UPDATE: in python3 you can use the types module with foo.__code__:

import types
myfoo = types.FunctionType(foo.__code__.co_consts[1], {})
myfoo()  # behaves like it is do_this()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: do_this() missing 2 required positional arguments: 'x' and 'y'
🌐
Reddit
reddit.com › r/learnprogramming › [python] | how to call nested functions
r/learnprogramming on Reddit: [Python] | How to call nested functions
October 17, 2021 -

This is the code I am trying to run:

x = 1
def f1():
    x = 2

    def f2():
        global x
        x = 3

print(x)
f1()
print(x)
f2()
print(x)

Output:

1
1
Traceback (most recent call last):
    f2()
NameError: name 'f2' is not defined

What I meant to do was call the f2() function but then it showed an error.

My question is how do I call the f2() function outside the nested block?

Discussions

Python - Proper way to call nested functions? - Stack Overflow
So if you were to run python test.py -test test.txt it should run the file command on it to get the file type · I know if I keep messing around I'll get it one way or another, but I typically start to over complicated things so its harder down the line later. So what is the proper way to call nested functions? Thanks in ... More on stackoverflow.com
🌐 stackoverflow.com
Call a nested function in Python - Stack Overflow
Is it possible to call a nested function defined inside an existing function: For example: def first(x): def second(): print(x) return second I know I can do something like this: ... More on stackoverflow.com
🌐 stackoverflow.com
September 22, 2017
How to call a function that is nested in python - Stack Overflow
I'm trying to be able call a function that is nested. def function1(): #code here def function2(): return #variable def function3(): x = #the variable that is returned in funct... More on stackoverflow.com
🌐 stackoverflow.com
How to call nested function independently in Python script - Stack Overflow
In the below Python code, I am trying to call the nested function (at step2) independently but getting an error. Condition is step1 should execute before step2, this is to ensure that c1 gets the s... More on stackoverflow.com
🌐 stackoverflow.com
🌐
CodeSpeedy
codespeedy.com › home › how to call a nested function: python nested function call!
Nested Function Call : How to call a Nested Function in Python
October 16, 2020 - So in this manner, the nested function is called every time we call the func() function automatically because it is called inside the func() function. Python Closures or you can say nested function objects can be used to protect or filter some functionalities inside that function.
🌐
freeCodeCamp
freecodecamp.org › news › nested-functions-in-python
Nested Functions in Python
January 6, 2020 - In the code above, the inner function is only available from within the function outer. If you try to call inner from outside the function, you'll get the error above.
🌐
YouTube
youtube.com › watch
Python nested function calls 🖇️ - YouTube
Python nested function calls#python #nested #functions# -------------------------------------------------------------------------------------# nested functio...
Published: January 25, 2021
Find elsewhere
🌐
Python Morsels
pythonmorsels.com › nested-functions
Nested functions in Python - Python Morsels
June 10, 2026 - This ability to define functions within functions isn't seen very often, except when using a specific Python feature: decorators. A decorator is a function that accepts a function and returns a new function that replaces the original function. Decorators almost always involve nested functions: def log_me(func): def wrapper(*args, **kwargs): print("Calling with", args, kwargs) return_value = func(*args, **kwargs) print("Returning", return_value) return return_value return wrapper
🌐
Berkeley
pythonnumericalmethods.berkeley.edu › notebooks › chapter03.03-Nested-Functions.html
Nested functions — Python Numerical Methods
Nested functions are useful when ... the parent function perform its task while hiding in the parent function. TRY IT! Call the function my_dist_xyz for x = (0, 0), y = (0, 1), z = (1, 1). Try to call the nested function my_dist in the following cell....
🌐
Stack Abuse
stackabuse.com › python-nested-functions
Python Nested Functions
December 21, 2018 - The function1() will then go ahead and call function2() as it has been defined inside it. It is important to mention that the outer function has to be called in order for the inner function to execute. If the outer function is not called, the inner function will never execute.
🌐
TutorialsPoint
tutorialspoint.com › How-do-nested-functions-work-in-Python
How do nested functions work in Python?
September 28, 2023 - When run, the above code will return no results because the outer function is never called. The scope of a variable is the location where we can find a variable and access it if necessary. It is well-understood how to access a global variable within a function, but what about accessing the variable of an outside function? The following program demonstrates the scope of the nested functions − · # creating an outer function def outerFunc(): sample_str = 'Hello tutorialspoint python' # creating an inner function def innerFunc(): print(sample_str) # calling an inner function inside the outer function innerFunc() # calling outer function outerFunc()
🌐
Dive into Python
diveintopython.org › home › learn python programming › functions in python › nested functions
Nested Functions in Python - Powerful Tool for Organized Code
May 3, 2024 - To create a nested function in Python, follow these steps: Create the outer function. Define the inner function within the outer function. Call the inner function within the outer function or return it.
🌐
Linux Hint
linuxhint.com › nested-functions-python
Linux Hint – Linux Hint
September 1, 2021 - Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
Analytics Vidhya
analyticsvidhya.com › home › how nested functions are used in python?
How nested functions are used in Python? - Analytics Vidhya
March 4, 2025 - Let’s look at examples of the ... in Python and how to use them to encapsulate code, closures, and decorators. Nested (or inner, nested) functions are functions that we define inside other functions to directly access the variables and names defined in the enclosing function. Nested functions have many uses, primarily for creating closures and decorators. ... Hello, World! In this code, we define internally to display a string . To do this, we call on the last ...
Top answer
1 of 2
3

To answer your first question: to call all of the functions you need to put the names of your functions into the main() function. But, you had several other errors so I have decided to walk you through the program, step-by-step.

First, we set the prices:

secA = 20
secB = 15
secC = 10

Here is the first function, getTickets()

def getTickets():

    global A
    A = int(input("Please enter the number of tickets sold in section A: "))

    global B
    B =int(input("Please enter the number of tickets sold in section B: "))

    global C
    C =int(input("Please enter the number of tickets sold in section C: "))

Notice the word global before I use the variable. This tells the computer that this variable can be used everywhere. Next, notice the double parentheses - since both int() and input() are functions, so we need to show that by doing that.

I fixed your code for the ticketsValid() function. Usually, it isn't a good idea to nest functions, so this is at the same indentation level as the above code.

def ticketsValid(A,B,C):
    while A > 300 or A < 0:
        print("ERROR: Section A has a limit of 300 seats\n")
        A = int(input("Please enter the number of tickets sold in section A: "))
    while B > 500 or B < 0:
        print("ERROR: Section B has a limit of 500 seats")
        B =int(input("Please enter the number of tickets sold in section B: "))
    while C > 200 or C < 0:
        print("ERROR: Section C has a limit of 200 seats")
        C =int(input("Please enter the number of tickets sold in section C: "))

This gets the variables from above, and checks to see if they are valid. Notice that I added a check for negative numbers - you can't sell negative tickets.

Then we come to calcIncome(A,B,C):

def calcIncome(A, B, C):
    total = A * secA + B * secB + C * secC
    print ("The income generated is $%d" % (total))

First, we multiply the sections by the set prices to calculate the total. Then, we print it.

Lastly, we need to call the functions. I used your idea for a main() function, which uses the other functions. It looks like this.

def main():
    getTickets()
    ticketsValid(A,B,C)
    calcIncome(A, B, C)

It simply calls the other functions, in the correct order, when run.

Lastly, we call the main() function by typing:

main()

I hope that this answered your question. If not, feel free to comment. If so, please check the green check mark next to my answer.

2 of 2
1

If you only want to know how to use a nested function:

def f():
    def g(): #this defines a function but does not call it
        print "run g"
    g() # this calls g.

Typically, nested functions should not be available outside its parent function. Since the point of using a nested function is that the function only helps its parent function to do things. If you want it outside, consider define it as a new function.

In your case, you need to consider how to break up your code into parts.
If I were you, I would use getTickets() to get tickets.
The ticketsValid is fine, though I would let it return a boolean. calcIncome would return the total income. So the general design is like:

def main():
    (A, B, C) = getTickets()
    if(ticketsValid(A, B, C)):
        income = calcIncome(A, B, C)
        print("The income generated from all sections is: ", income)

def getTickets():......
def ticketsValid(A, B, C):......
def calcIncome(A, B, C):......

I think this would be a better design.

🌐
DEV Community
dev.to › divshekhar › python-inner-function-nested-functions-1dbn
Python Nested Function - DEV Community
May 23, 2023 - Python offers many features and one such feature is that it has the ability to implement Inner Function or Nested Functions. In Simple terms, You can define a Function within another Function. Let’s Learn about Python Inner Function / Nested Function. def outerFunction(a, b): def innerFunction(c, d): return c*d return innerFunction(a, b) ... In the above code, the outer function is called with two integer arguments and the outer function has an inner function that calls and returns the inner function with the arguments of the outer function.