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.
A function with one or more parameters has a list of parameters surrounded by parentheses after its name in the function definition:
1 2 3 4 | def welcome_student(name): print(f"Hi, {name}! Welcome to class.") |
When we call the function, we just need to pass one value as argument and that value will be replaced where we use the parameter in the function definition:
1 2 3 4 | >>> welcome_student("Jack") Hi, Jack! Welcome to class. |
Here we have another example – a function that prints a pattern made with asterisks. You have to specify how many rows you want to print:
1 2 3 4 5 6 7 | def print_pattern(num_rows): for i in range(num_rows): for num_cols in range(num_rows-i): print("*", end="") print() |
You can see the different outputs for different values of num_rows
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | >>> print_pattern(3) *** ** * >>> print_pattern(5) ***** **** *** ** * >>> print_pattern(8) ******** ******* ****** ***** **** *** ** * |