Is a function call an expression in python?
Asked Answered
L

3

5

According to this answer, a function call is a statement, but in the course I'm following in Coursera they say a function call is an expression.

So this is my guess: a function call does something, that's why it's a statement, but after it's called it evaluates and passes a value, which makes it also an expression.

Is a function call an expression?

Let answered 21/5, 2013 at 0:25 Comment(2)
The term "does something" is very vague and misleading, don't read too much into the words.Desinence
I think that answer is a bit confusing, or maybe even misleading. But if you read the comments to the answer, they explain everything. (The other answers help as well). A function call is an expression. Since any expressions is also an expression statement, that means a function call is also a statement.Ennead
C
13

A call is an expression; it is listed in the Expressions reference documentation.

If it was a statement, you could not use it as part of an expression; statements can contain expressions, but not the other way around.

As an example, return expression is a statement; it uses expressions to determine it's behaviour; the result of the expression is what the current function returns. You can use a call as part of that expression:

return some_function()

You cannot, however, use return as part of a call:

some_function(return)

That would be a syntax error.

It is the return that 'does something'; it ends the function and returns the result of the expression. It's not the expression itself that makes the function return.

If a python call was not an expression, you'd never be able to mix calls and other expression atoms into more complex expressions.

Convenance answered 21/5, 2013 at 0:26 Comment(1)
Wow! Thanks everyone! I leaned a LOT thanks to you guys! What a great first experience here in S.O.! :)Let
C
0

Function calls are expressions, so you can use them in statements such as print or =:

x = len('hello')        # The expression evaluates to 5
print hex(48)           # The expression evaluates to '0x30'

In Python, functions are objects just like integers and strings. Like other objects, functions have attributes and methods. What makes functions callable is the __call__ method:

>>> def square(x):
        return x * x

>>> square(10)
100
>>> square.__call__(10)
100

The parentheses dispatch to the __call__ method.

This is at the core of how Python works. Hope you've found these insights helpful.

Chesterfieldian answered 21/5, 2013 at 0:51 Comment(1)
Thank you very much for your time! It is really useful! I tried to select both answers, but I can't. Learned a lot! All the best!Let
L
0

expression are also statements in python. A function is an expression because it returns a value but expressions in python are also statements. expression statements

Longlegged answered 19/7, 2021 at 12:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.