Function
A reusable, named block of code that can take inputs and return a result.
You define a function with the def keyword, an optional list of parameters in parentheses, and an indented body. Calling the function runs that body, and a return statement hands a value back to whoever called it. A function with no return hands back None.
Functions let you write a piece of logic once and reuse it with different inputs, which keeps programs short and easier to fix.
def greet(name): # "name" is a parameter
return "Hello, " + name + "!"
message = greet("Sam") # call it with an argument
print(message)
Output
Hello, Sam!
Where this shows up in real Python
Functions organise scripts, remove repetition, and make larger programs easy to read and test one piece at a time.
Commonly used Function tools
Patterns you’ll reach for constantly once you write your own:
def greet(name='friend')— default values make an argument optional*args, **kwargs— accept any number of positional/keyword argumentsdef total(x: int) -> int— type hints document inputs and outputreturn— hand a value back (no return means None)
Official documentation: Python Tutorial: Defining Functions