Python: Functions and Classes

 



This tutorial documents the usage of functions and classes in Python3.

Function in Python is some reusable code, often executed with various parameters (so it is parametrized) and intended for better code style and usability.


Example of function declaration:


When you develop your code - you may decide to quickly declare functions before their code is available, so it will be "empty" declaration of function


Empty function declaration


def test_function():
pass

   


When function consist of self sufficient code and does not require any arguments (parameters) to be passed into its code - you may have functions which does not accept any arguments.


Function declaration and usage (call a function) - without arguments


def test_function():
print("Hello World")

test_function()

   


Functions which do have arguments - are more common as it represents more flexible code style


Function declaration and usage (call a function) - with arguments


def test_function(word1, word2):
print(word1 + " " + word2)

test_function("Hello", "World")

   


Functions may have unknown number of arguments - in this case code may iterate over all parameters as needed per logic


Function declaration and usage - with unknown number of arguments


def test_function(*parameters):
for _ in parameters:
print(_, end =" ")
print("- all parameters were printed")

test_function("Hello", "World")

   


Functions may also receive their arguments in the form of "key = value" pairs. This way not only number of parameters may be unknown but also order of those arguments.  


Function declaration and usage - with unknown number of arguments by arbitrary declaration 


def test_function(**parameters):
print(parameters["first_word"] + " " + parameters["second_word"])

test_function(second_word = "World", first_word = "Hello")

   






Page is under construction.



Post a Comment

Previous Post Next Post