-1
def enumerator(fruits):
    for index, fruit in enumerate(fruits):
        print(f"Fruit: {fruit}, under the index: {index}.")

just_a_variable = enumerator(["apple", "banana", "lemon"]) # Im just assigning function call
# to the variable "just_a_variable"
# and boom, when I run the program the function is called. Makes no sense (it shouldn't work this way, does it?)

I assume this is happening because there is a print statement in the function but it still doesn't make sense. if I change the print statement to "return" it suddenly doesn't compile, that is what I was expecting from just using print. I'm I missing something here?

  • 2
    If you don't think the last line is calling `enumerator` (which it is), what do you think you would do differently so that you *were* calling it? – Scott Hunter Mar 02 '22 at 15:37
  • 1
    if you replace the print to "return", it will return only string for fist iter of loop, i.e. "Fruit: apple, under the index: 0." – Alex Mar 02 '22 at 15:43

2 Answers2

1

In general if you add parenthesis after a function (like one of the two examples below), it is called.

function_name(arguments)
variable = function_name(arguments)

 

If you just want a variable to point to a function:

variable = function

Then the following two statements will become identical:

variable(arguments)
function(arguments)

Having said so, this seems a bit useless to me. With you function defined the way it currently is, there isn't a way I know to "assign" it to a variable and pass arguments at the same time.


This does change the structure of your code, but you can perhaps use yield instead of return.

eccentricOrange
  • 876
  • 5
  • 18
0

The line just_a_variable = enumerator(["apple", "banana", "lemon"]) is calling function enumerator. Technically, that is what the parenthesis after enumerator do.

Perhaps you noticed that simply running the file is running that line (and calling enumerator). As a scripting language, this is how Python works (in contrast to Java or other compiled languages).

Joshua Fox
  • 18,704
  • 23
  • 87
  • 147