def / return
Try it yourself →Defines your own function (command).
Syntax
def name(param):
return valueDescription
Binds a repeated task to a name. It takes data via parameters and returns a result with return. If there's no return, it returns None.
Parameters
| parameter(optional) | The input(s) given to the function. |
Returns
The value specified with return.
Example
def square(x):
return x * x
print(square(5))Expected output
25
When to use?
Avoiding code repetition, breaking the program into readable pieces.
Common mistakes
- ⚠️ If you don't write return, the function returns None; print and return are different.