Addition, concatenation, finding the remainder of a division, and the other operations we've discussed are fundamental features of programming languages.
Mathematics isn't limited to arithmetic. There are other areas with their operations ⎯ geometry, for example. The same goes for strings: you can flip them, change a letter's case, delete extra characters – and that's just the tip of the iceberg.
And at higher levels, there's application-specific logic. Programs withdraw money, calculate taxes, and generate reports. The number of actions is endless and different for each program. And you have to be able to express them in code. For expressing other operations, we have a feature in programming called functions.
Functions can be built-in or added by the programmer. We're already familiar with one built-in function — print()
.
Functions are one of the key constructs in programming. Without them, it's impossible to do almost anything.
Programmers should learn them as early as possible since everything after this will be very function-heavy. First, we'll learn how to use the functions we've already created, and then we'll learn how to create our own.
We will start with fundamental functions that handle strings.
Functions for working on strings
The len()
function counts the number of characters in a string. We call it below:
# Calling the `len` function with the parameter 'Hello!'
result = len('Hello!')
print(result) # => 6
Parameters or arguments are the information the function receives when we call it. Based on this information, it usually calculates and outputs a result.
We created a variable called result
and gave the interpreter a specific action. We should add into the variable the result returned by the len()
function when it's called.
In this sense, functions are like operations — they always return the result of their work. The entry len('Hello!')
means that we call the len
function to which we passed the parameter 'Hello!'
. The len()
function counts the length of the string we passed to it.
We always indicate a function call by parentheses ()
coming right after the function name. The parentheses may contain any number of parameters or none at all. The number of parameters depends on the function used.
For example, let us observe the pow()
function, which raises a given number to the right power. It takes two parameters as input: Python raises the first parameter by the degree set in the second parameter:
result = pow(2, 3) # 2 * 2 * 2
print(result) # => 8
We've figured out how to use the simple built-in functions. But that's not all of them. You will learn more about it in the following lessons and other Hexlet courses.