Functions & Modules
Functions: Writing Reusable Code
Functions are the building blocks of any non-trivial Python program. They allow you to encapsulate a piece of logic and reuse it without copying and pasting code. You define a function using the def keyword, followed by a name, parentheses, and a colon. The code inside the function is indented. Functions can accept inputs called parameters and can return outputs using the return statement. A simple function might look like this: def greet(name): return f"Hello, {name}!" Then you can call it with greet("Bob"). Functions make your code more organized and easier to debug. If there is a mistake, you fix it in one place. They also let you think at a higher level. Instead of worrying about every detail, you can think about the steps your program takes, each step being a function. You can also set default values for parameters, making them optional. For example, def greet(name="Guest"): returns "Hello, Guest!" if no name is provided. As you write more complex programs, you will start creating your own modules—files containing related functions. This modular approach is key to building maintainable applications. Start by taking repetitive code from your earlier projects and turning it into functions.
3,882
Views
201
Words
1 min read
Read Time
Apr 2025
Published