Home > Software engineering >  Why the print statement is being executed from the function if the function is not called?
Why the print statement is being executed from the function if the function is not called?

Time:03-03

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?

CodePudding user response:

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.

CodePudding user response:

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).

  • Related