In Python, we can define functions to make our code reusable, more readable, and organized. This is the basic syntax of a Python function:
1 2 3 4 | def <function_name>(<param1>, <param2>, ...): <code> |
Tip: a function can have zero, one, or multiple parameters.
To define two or more parameters, we just separate them with a comma:
Example:
1 2 3 4 | def print_sum(a, b): print(a + b) |
Now when we call the function, we must pass two arguments:
1 2 3 4 5 6 7 8 9 10 11 12 13 | >>> print_sum(4, 5) 9 >>> print_sum(8, 9) 17 >>> print_sum(0, 0) 0 >>> print_sum(3, 5) 8 |
We can adapt the function that we just saw with one parameter to work with two parameters and print a pattern with a customized character:
1 2 3 4 5 6 7 | def print_pattern(num_rows, char): for i in range(num_rows): for num_cols in range(num_rows-i): print(char, end="") print() |
You can see the output with the customized character is that we call the function passing the two arguments:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | >>> print_pattern(5, "A") AAAAA AAAA AAA AA A >>> print_pattern(8, "%") %%%%%%%% %%%%%%% %%%%%% %%%%% %%%% %%% %% % >>> print_pattern(10, "#") ########## ######### ######## ####### ###### ##### #### ### ## # |