Function Definitions

Carson West

Return Values

Function Definitions

Python functions are defined using the def keyword, followed by the function name, parentheses (), and a colon :. The function body is indented.

def my_function(param1, param2):
  """This is a docstring describing the function."""
  # Function body
  result = param1 + param2
  return result

# Calling the function
output = my_function(5, 3) 
print(output)  # Output: 8
def greet(name, greeting="Hello"):
  print(f"{greeting}, {name}!")

greet("Alice")  # Output: Hello, Alice!
greet("Bob", "Good morning")  # Output: Good morning, Bob!
def describe_pet(animal_type, pet_name):
    """Display information about a pet."""
    print(f"\nI have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name.title()}.")

describe_pet(animal_type='hamster', pet_name='harry')