PY

Python Fundamentals

18 lessons

Progress0%
1. Introduction to Python
1What is Python?2Setting Up Python
2. Variables and Data Types
1Variables in Python2Data Types
3. Control Flow
Conditional StatementsLoops
4. Functions
Function Basics
5. Data Structures
Lists Deep DiveTuples & SetsDictionaries & Comprehensions
6. Advanced Functions
Closures & Higher-Order FunctionsDecorators & Lambda
7. Object-Oriented Python
Classes & InstancesInheritance & Dunder Methods
8. Exception Handling
try / except / finallyCustom Exceptions & Context Managers
9. Modules & File I/O
Modules & PackagesFile I/O & JSON
All Tutorials
PythonFunctions
Lesson 7 of 18 min
Chapter 4 · Lesson 1

Function Basics

Functions are reusable blocks of code defined with the def keyword.

Defining Functions: def function_name(parameters):

Parameters:

  • Required parameters: must be provided
  • Default parameters: have default values
  • *args: variable positional arguments
  • **kwargs: variable keyword arguments

Return Values:

  • Use return to send back a value
  • Functions return None by default
  • Can return multiple values (tuple)

Docstrings: Document your functions with triple quotes.

Scope:

  • Local: defined inside function
  • Global: defined outside function
  • Use global keyword to modify global variables

Code Examples

Python Functionspython
# Basic function
def greet(name):
    """Greet a person by name."""
    return f"Hello, {name}!"

print(greet("Alice"))

# Default parameters
def greet_with_title(name, title="Mr."):
    return f"Hello, {title} {name}!"

print(greet_with_title("Smith"))
print(greet_with_title("Smith", "Dr."))

# Multiple return values
def get_stats(numbers):
    """Return min, max, and average."""
    return min(numbers), max(numbers), sum(numbers)/len(numbers)

minimum, maximum, average = get_stats([1, 2, 3, 4, 5])
print(f"Min: {minimum}, Max: {maximum}, Avg: {average}")

# *args - variable arguments
def sum_all(*numbers):
    return sum(numbers)

print(f"Sum: {sum_all(1, 2, 3, 4, 5)}")

# **kwargs - keyword arguments
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

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

# Lambda functions
square = lambda x: x ** 2
print(f"Square of 5: {square(5)}")

# Lambda with sorted
people = [("Alice", 30), ("Bob", 25), ("Charlie", 35)]
sorted_by_age = sorted(people, key=lambda p: p[1])
print(f"Sorted: {sorted_by_age}")

Python functions are flexible with *args and **kwargs allowing variable numbers of arguments.

Quick Quiz

1. What does **kwargs allow you to do?

Was this lesson helpful?

PreviousNext