Functions
Function and basics of working with it
Functions
As programs grow larger, writing everything in one place becomes messy and hard to maintain. Functions let you give a name to a block of code, reuse it anywhere, and break your program into clear, manageable pieces.
Defining a Function
Use the def keyword, followed by the function name, parentheses, and a colon. The function body is indented:
The function does nothing until you call it. You can call it as many times as you want.
Parameters
Parameters let you pass values into a function:
A function can take multiple parameters:
The names a and b only exist inside the function. The values you pass in (3 and 5) are called arguments.
Return Values
A function can send a value back to the caller using return:
Without return, a function returns None by default:
return Exits the Function Immediately
As soon as Python hits a return statement, the function stops — no code below it runs:
Each return exits early as soon as a condition is met. This is a very common pattern for keeping functions readable.
Returning Multiple Values
Python functions can return multiple values as a tuple:
Default Arguments
You can give parameters a default value. If the caller does not provide that argument, the default is used:
Parameters with defaults must come after parameters without defaults:
Passing Lists to Functions
When you pass a list to a function, you are not passing a copy — you are passing a reference to the same list in memory. This means the function can modify the original list:
This is different from passing integers or strings, which are immutable — a function can never change the original integer variable:
If you want to avoid modifying the original list, pass a copy using [:]:
Practical Examples
Checking if a Number is Prime
Sum of a List
Reversing a String
Reading Input into a List
Wrapping common input patterns in a function keeps your CP code clean: