Python Forum
In this function y initially has no value, but a call to foo() gives no error. Why?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
In this function y initially has no value, but a call to foo() gives no error. Why?
#1
This is from Reuven Lerner's book Python Workout.

I don't really understand why I don't get an error when no value is passed to y.
Or why, the second time around, I get the expected result.
(I added the print()s to show what is happening.

def foo(x):
    def bar(y):
        print(f'y is {y}')
        print(f'x is {x}')
        print(f'x * y is {x*y}')
        return x * y
    print(f'bar is {bar}')
    return bar
I call the function with g = foo(2), but y has no value. I expected an error, but I get:

Quote:g = foo(2) # returns: bar is <function foo.<locals>.bar at 0x7ff37b475268>

Why is there no error when y has no value??

Normally, if a function requires an argument and none is supplied, you will get an error.

Now I try:

print(g(20))
but I don't get:

Quote:foo(20) # returns: bar is <function foo.<locals>.bar at 0x7ff37b475268>

I get the intended result:

Quote:y is 20
x is 2
x * y is 40
40

How did 20 get passed to y??
Reply


Messages In This Thread
In this function y initially has no value, but a call to foo() gives no error. Why? - by Pedroski55 - Dec-16-2020, 03:07 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How do I call sys.argv list inside a function, from the CLI? billykid999 3 802 May-02-2023, 08:40 AM
Last Post: Gribouillis
  UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 error from Mysql call AkaAndrew123 1 3,468 Apr-28-2021, 08:16 AM
Last Post: AkaAndrew123
  how to call an object in another function in Maya bstout 0 2,091 Apr-05-2021, 07:12 PM
Last Post: bstout
  Struggling for the past hour to define function and call it back godlyredwall 2 2,233 Oct-29-2020, 02:45 PM
Last Post: deanhystad
  list call problem in generator function using iteration and recursive calls postta 1 1,922 Oct-24-2020, 09:33 PM
Last Post: bowlofred
  function call at defined system time? Holon 5 3,257 Oct-06-2020, 03:58 PM
Last Post: snippsat
  How to call/read function for all elements in my list in python johnny_sav1992 1 2,093 Jul-27-2020, 04:19 PM
Last Post: buran
  Python: Call function with variabele? Ending in error. efclem 5 2,977 Apr-22-2020, 02:35 PM
Last Post: buran
  How to mock an object that is created during function call? Schlangenversteher 0 1,983 Jan-31-2020, 01:36 PM
Last Post: Schlangenversteher
  Is there a way to search for function call? mtran 2 2,290 Jan-14-2020, 02:07 AM
Last Post: mtran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020