Python Examples

A collection of practical Python examples to help you understand common patterns and use cases.


Basic Function Example

Functions are fundamental building blocks in Python. They are reusable blocks of code that perform a specific task, defined with the `def` keyword.

Functions help organize code, make it more readable, and allow for easy reuse, which is a core principle of DRY (Don't Repeat Yourself).

Live Example

functions.py
# A simple function to add two numbers
def add(a, b):
  return a + b

# Calling the function and storing the result
sum_result = add(5, 10)

# Displaying the result
print(sum_result) # Output: 15

# Example with a string
def greet(name):
    return "Hello, " + name + "!"

print(greet("Alice")) # Output: "Hello, Alice!"
Console Output

> 15

> "Hello, Alice!"

Key Concepts

Key parts of a function definition:

ConceptDescription
defKeyword to define a new function.
add(a, b)`add` is the function name. `(a, b)` are the parameters (inputs) the function accepts.
return a + bThe `return` statement specifies the value to be returned by the function.
add(5, 10)This is a function call, executing the function with arguments `5` and `10`.