Let's keep looking at functions and their components. Today, we'll be looking at expressions. Let's discuss what it is and what is the difference between functions and expressions.
What are expressions
An expression in programming returns a result that we can use. You probably already know a lot about them and the principles of their construction.
For example, addition, subtraction, and concatenation are all expressions:
1 + 5 * 3
'He' + 'Let'
# Variables can be part of an expression
rate * 5
The peculiarity of expressions is that they return a result that we can use again: for example, they can be assigned to a variable or printed. It is what it looks like in the code:
# Here we see the `1 + 5` expression
sum = 1 + 5
print(1 + 5)
But not everything in programming is an expression. The definition of a variable is an instruction, which means it can't be part of an expression. In other words, this code will lead to an error:
# That code will not work
10 + sum = 1 + 5
Let us see whether we can take a function call as an expression.
Functions as expressions
We know that functions return results, so they are expressions. It leads to a lot of possibilities. For example, we can use a function call directly in mathematical operations. It is how we can get the last character index in a word:
name = 'python'
# Indexes start with zero
# We see a function call and subtraction together
last_index = len(name) - 1
print(last_index) # => 5
This code has no new syntax. We have merely connected parts we already know. We could go even further:
print(len(name) - 1) # => 5
All of this applies to any function, e.g., string functions:
name = 'python'
# We used interpolation
print(f'Last character: {name[len(name) - 1]}')
# 'Last character: n'
As you'll see later, we can combine expressions to produce increasingly complex behavior in different places. The more you learn and practice Python, the better you understand the topic. Over time, you'll learn how to connect code fragments to get the needed results.