Functions are reusable blocks of code that perform a specific task. They help organize code and avoid repetition.
Use the def keyword to define a function:
def greet(name):
return f"Hello, {name}!"
message = greet("World")
print(message) # Output: Hello, World!
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
def sum_all(*args):
return sum(args)
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
Lambda functions are small anonymous functions:
square = lambda x: x ** 2
add = lambda a, b: a + b
Modules are files containing Python code that can be imported into other programs.
import math
import random
from datetime import datetime
from os import path
Python's standard library includes many useful modules:
Save a Python file and import it:
# mymodule.py
def say_hello():
return "Hello!"
# main.py
import mymodule
print(mymodule.say_hello())