Functions - Creating Your Own Commands

A function is a reusable block of code with a name. You define it once with 'def', then call it whenever you need it. Functions can take inputs (parameters) and return outputs. They help avoid repeating code and make programs organized.

# Creating and using functions
# Example 1: Simple greeting function
def say_hello():
    """This function says hello"""
    print("Hello!")
    print("Welcome to Python!")

# Using the function
print("Calling function first time:")
say_hello()
print("\nCalling function second time:")
say_hello()

# Example 2: Function with parameters
def greet_person(name):
    """Greets a person by name"""
    print(f"Hello, {name}! Nice to meet you!")

# Using with different names
greet_person("Alice")
greet_person("Bob")

# Example 3: Function that returns a value
def calculate_area(length, width):
    """Calculates area of rectangle"""
    area = length * width
    return area

# Using the function
room_area = calculate_area(10, 12)
print(f"\nRoom area: {room_area} square feet")

# Example 4: Function with default value
def order_coffee(flavor="regular"):
    """Orders coffee, default is regular"""
    print(f"One {flavor} coffee coming up!")

order_coffee("cappuccino")  # With specified flavor
order_coffee()              # Uses default

# Example 5: Temperature converter
def celsius_to_fahrenheit(celsius):
    """Converts Celsius to Fahrenheit"""
    fahrenheit = (celsius * 9/5) + 32
    return fahrenheit

temp_c = 25
temp_f = celsius_to_fahrenheit(temp_c)
print(f"\n{temp_c}°C = {temp_f}°F")