print, len, and input, and we’ve distinguished between functions and methods. In Python, functions can come from the core language, external modules, or be defined by you.
Encapsulating repeated code into functions enhances readability and minimizes potential bugs.
Why Use Functions?
Repeating blocks of code can make your programs harder to maintain and increase the risk of errors. By defining a function, you bundle the code into a reusable unit, reducing redundancy and improving clarity. Consider the following example where the same input logic is repeated multiple times:input_number:
Defining the Function
We create a function using Python’sdef keyword. The function starts with the function name and parentheses, followed by a colon to indicate the beginning of the function body. In this case, the function prompts the user for a number, converts the input to an integer using int(), and returns the value.
Here’s how to rewrite the repetitious code using our new input_number function:
input_number(), the function executes its internal code, prompting the user, converting the input to an integer, and returning the resulting value. For example, the variable input1 holds the number provided by the user.
Important Consideration
It is crucial to define a function before calling it. If you attempt to use a function before its definition, Python will throw an error:input_number when it is called.
Always define your functions before invoking them to avoid
NameError issues.