Ch 8 · Functions · Python

Topic 8 of 13 in Python — Complete Tutorial (Beginner) — 4 lessons.

What is a Function?

A function is a named, reusable block of code that performs a specific task. Instead of writing the same instructions in many places, you write them once inside a function, give it a clear name, and call that name whenever you need the task done. Programmers call this principle DRY — "Do not Repeat Yourself." Every time you copy and paste the same code, that is a hint it should become a function.

Parameters and Return Values

Parameters are the inputs a function expects, listed inside the brackets. When you call the function, you pass actual values (called arguments) in the same order. Inside the function, parameters behave like normal variables. You can also give a parameter a default value with =, which is used when the caller leaves it out.

Lambda Functions

A lambda is a tiny, anonymous function written on a single line. Instead of def, you write lambda, the parameters, a colon, and a single expression whose value is returned automatically. Lambdas are handy for short, throwaway functions — especially when you need to pass a quick function to another function, such as telling sorted() how to order items. For anything longer than one expression, use a normal def function.

Functions Working Together

Real programs are built from many small functions, each doing one job, that call one another. The example below has one function to work out a grade, one to check if a student passed, and one that prints a full report by calling the other two. This is called function composition — combining small, focused functions into a larger workflow — and it is the hallmark of well-organised code.

All topics in Python Beginner

  1. Introduction to Programming & Python
  2. Your First Python Program
  3. Variables — Your Data Containers
  4. Data Types — Kinds of Values
  5. Operators & Expressions
  6. Conditional Statements
  7. Loops & Iterations
  8. Functions
  9. Lists — Collections of Data
  10. Dictionaries & Classes
  11. Strings — Working with Text
  12. Error Handling
  13. Mini-Projects & Practice