Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

PB
Programming Basics
0/10 completed
Beginner
How computers workWhat is a program?Thinking in algorithmsData, variables and types
Intermediate
Decisions and loopsBreaking problems into functionsErrors and debugging
Advanced
Reading documentation and learning on your ownClean code basics
Pro
Thinking like a software engineer
Tracks / Programming Basics / Intermediate

Breaking problems into functions

A function is a named, reusable block of code that does one job. Functions are how programmers tame complexity: big problems become a set of small, testable pieces.

Defining and calling a function

Python · editable
JavaScript · editable
  • name is a parameter: the function's input.
  • "Asha" is an argument: the actual value passed in.
  • return sends a result back to whoever called the function.

Think of a function as a machine: inputs → work → output.

Why use functions?

  1. Reuse: write once, use everywhere.
  2. Readability: calculate_tax(order) explains itself.
  3. Testing: small functions are easy to check one at a time.
  4. Change in one place: fix a bug once, not in ten copies.

DRY: Don't Repeat Yourself. If you copy-paste code for the third time, turn it into a function.

Decomposition: top-down problem solving

Problem: "Print a receipt for a shopping cart, with a 10% discount on orders over ₹1000 and 18% tax."

Don't write it as one giant block. Name the steps first, then write each as a function:

Python · editable

Each function is tiny and obvious. print_receipt reads like the problem statement. That's good design.

Return vs print

A common beginner mistake is printing inside a function instead of returning. Printed values can't be reused:

JavaScript · editable

Scope: variables live inside their function

Python · editable

Local variables keep functions independent, so they don't interfere with each other.

Default and named arguments

Python · editable

Good function habits

  • One job per function. If you need "and" to describe it, split it.
  • Name it with a verb: calculate_total, is_valid_email, send_invite.
  • Keep it short: usually under 20–30 lines.
  • Prefer returning values over changing global variables.

Practice

Decompose this problem into at least three functions: "Given a list of exam scores, print the average, the highest score, and the grade (A ≥ 90, B ≥ 75, C ≥ 50, otherwise F) for the average."

Python · editable
✎ Check your understanding

1.What's the difference between a parameter and an argument?

2.Why is returning a value usually better than printing inside a function?

← Decisions and loops