Drupal 8 : how to write custom PHP functions and call the function from a custom page?

I am new to Drupal web development. I have already used Wordpress platform by building a custom plugin to write custom php functions, and calling the function from a custom page was easy.
example:

<?php
function givenumber(){
return 50;
}
?>;

Which I call by using:

<?php echo givenumber(); ?>

How can I achieve similar with Drupal 8?
Do I need to create a custom module for writing the custom php functions?
How do I call a function from a custom page?

Please help.

Well yes, modules are the only way to extend Drupal as far as I know. Modules are to Drupal what plugins are to wordpress.

There is a lot of documentation on it though; that’s probably a good place to start: https://www.drupal.org/docs/8/creating-custom-modules