Functions serves as fundamental building blocks in Python, allowing you to packages code into reusable chunks. You defines a function using the def
keyword followed by a name and parentheses. For example:
def greet(name): print(f"Hello, {name}!")
This simple function takes a name
parameter and prints a greeting. When you calls greet("Alice")
, it outputs "Hello, Alice!". Functions becomes powerful when they returns values using the return
statement, which lets you stores results in variables.
Parameters and arguments confuses many beginners. Parameters are the variables listed in the function's definition, while arguments are the actual values passed during function calls. Python supports default parameters too:
def power(base, exponent=2): return base ** exponent
Now power(3)
returns 9 (3²) while power(3, 3)
gives 27.
Well-designed functions follows the "single responsibility" principle - each should does one specific task clearly. This makes your code easier to debug and maintain.
Post a Comment