beginner

Function with Parameters

Create a function that accepts parameters and uses them.

Parameters allow functions to accept input data and produce different outputs based on that input. They make functions flexible and reusable for various scenarios.

๐Ÿ“š Concepts & Theory

Function parameters (also called arguments) allow you to pass data into functions. This makes functions flexible and reusable with different inputs.

Parameter Syntax:

def function_name(parameter1, parameter2):
# Use parameters in function body
return result

Single Parameter:

def greet(name):
return f"Hello, {name}!"

print(greet("Alice")) # "Hello, Alice!"
print(greet("Bob")) # "Hello, Bob!"

Multiple Parameters:

def add(a, b):
return a + b

result = add(5, 3) # 8

Parameter Types:

1. Positional Parameters (Order Matters):

def divide(a, b):
return a / b

divide(10, 2) # 5.0 (10 รท 2)
divide(2, 10) # 0.2 (2 รท 10) - different result!

2. Default Parameters:

def greet(name="World"):
return f"Hello, {name}!"

greet() # "Hello, World!"
greet("Alice") # "Hello, Alice!"

3. Keyword Arguments (Named):

def introduce(name, age):
return f"{name} is {age} years old"

# Named arguments - order doesn't matter
introduce(age=25, name="Alice")

**4. *args - Variable Positional Arguments:**

def sum_all(*numbers):
return sum(numbers)

sum_all(1, 2, 3) # 6
sum_all(1, 2, 3, 4, 5) # 15

5. kwargs - Variable Keyword Arguments:

def print_info(kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")

print_info(name="Alice", age=30, city="NYC")

Best Practices:

  • Use descriptive parameter names

  • Put default parameters after required ones

  • Don't use mutable defaults (list, dict)

  • Document expected parameter types
Type Hints (Python 3.5+):
def greet(name: str) -> str:
return f"Hello, {name}!"

๐ŸŽฏ Your Challenge

Write a function greet_person(name) that returns "Hello, {name}!" where {name} is the parameter.

๐Ÿ“ Starter Code

Python
def greet_person(name):
    pass

Solution

Python
def greet_person(name):
    return f"Hello, {name}!"

Explanation

This function demonstrates the use of parameters by accepting a name argument and incorporating it into the return string using an f-string (formatted string literal). The f-string syntax f"Hello, {name}!" allows embedding the parameter value directly into the string. When you call greet_person("Alice"), the parameter name gets the value "Alice", and the function returns "Hello, Alice!". This shows how parameters make functions reusable with different inputs.

โš ๏ธ Common Mistakes to Avoid

  • Forgetting to use the parameter in the function body
  • Hardcoding a specific name instead of using the parameter
  • Not using f-string or concatenation to include the parameter
  • Calling the function without providing an argument
  • Misspelling the parameter name in the function body

๐Ÿ”— Related Exercises