Great! Now that we have reviewed some basics, let's talk about some useful aspects of the programming language.
Creating Functions
You may already be aware of built-in
functions. Built-in functions are specified by the programming language directly via reserved keywords
-- terms taken by the language itself. Such functions are available for the user to freely use in their programs. An example of one such very common built-in function in Python is print()
.
But what if you wanted to create a custom function to perform a task of your choice? You can create a user-defined function in that case, and Python fully supports this.
Let's now see how user-defined functions in Python work. A function definition starts with a def
keyword, followed by the function name, parenthesis, and a colon. You can also provide function parameters within the parenthesis. However, they are entirely optional, and functions exist without parameters as well.
To use this custom function in a program, it needs to be called, or invoked, within your code. This is shown in the code block below, where the function is now utilized. As output, "Hello World!" is printed on the console.
Functions help modularize
code, as the program gets divided into different blocks (or "subroutines") which can be reused. Suppose you have a program that performs file writing when triggered by a certain condition. Instead of writing the same lines of code repeatedly, a function can be made which performs this specific task. This function is then called whenever this task is required.
xxxxxxxxxx
function myFunction() {
console.log("Hello World!");
}
myFunction();