EthicsComputerCourses
Join training +91 90532 10052

Functions

Intro to Programming · Lesson 15 of 25 Beginner 7 min read Updated

You have been using functions since your first program: print(), len() and console.log() are all functions. A function is a named block of code that does one job. You write it once and then call it, by name, as many times as you need.

In this lesson you will write your own functions, give them information through parameters, get answers back with return, and learn the difference between printing a value and returning it, which confuses almost every beginner.

Why use functions?

  • No repetition. If the same five lines appear in three places, put them in a function and call it three times. A fix then happens in one place.
  • A name for an idea. percentage(423, 500) is easier to read than the maths it hides.
  • Smaller pieces. A big problem becomes a set of small functions, each easy to test on its own.

Defining and calling a function

In Python, def starts a function definition, followed by the name, brackets and a colon. The body is indented. In JavaScript, the keyword is function and the body goes inside curly brackets.

PythonRun it yourself
def announce():
    print("The Ajmer Express is arriving on platform 3.")
    print("Please stand behind the yellow line.")

announce()
announce()
Output
The Ajmer Express is arriving on platform 3.
Please stand behind the yellow line.
The Ajmer Express is arriving on platform 3.
Please stand behind the yellow line.
JavaScriptRun it yourself
function announce() {
  console.log("The Ajmer Express is arriving on platform 3.");
  console.log("Please stand behind the yellow line.");
}

announce();
announce();
Output
The Ajmer Express is arriving on platform 3.
Please stand behind the yellow line.
The Ajmer Express is arriving on platform 3.
Please stand behind the yellow line.

Defining a function does not run it. The code inside runs only when you call it with its name followed by brackets: announce().

Parameters: giving a function information

A function becomes much more useful when you can give it information. The names inside the brackets of the definition are parameters. The actual values you pass when you call it are arguments.

PythonRun it yourself
def greet(name, city):
    print(f"Namaste {name}! How is the weather in {city}?")

greet("Ananya", "Kochi")
greet("Farhan", "Lucknow")
Output
Namaste Ananya! How is the weather in Kochi?
Namaste Farhan! How is the weather in Lucknow?

When you call greet("Ananya", "Kochi"), the parameter name gets the value "Ananya" and city gets "Kochi", matched in order.

Returning a value

Many functions work something out and hand the answer back to the code that called them. The return statement does this, in both languages:

PythonRun it yourself
def percentage(obtained, maximum):
    return obtained / maximum * 100

aarav = percentage(423, 500)
print(f"Aarav: {aarav:.1f}%")
print(f"Rohan: {percentage(361, 500):.1f}%")
Output
Aarav: 84.6%
Rohan: 72.2%
JavaScriptRun it yourself
function percentage(obtained, maximum) {
  return (obtained / maximum) * 100;
}

const aarav = percentage(423, 500);
console.log(`Aarav: ${aarav.toFixed(1)}%`);
console.log(`Rohan: ${percentage(361, 500).toFixed(1)}%`);
Output
Aarav: 84.6%
Rohan: 72.2%

A call to a function that returns a value can be used anywhere a value can go: stored in a variable, used in a sum, or put inside an f-string. return also ends the function immediately; any lines after it in that run are skipped.

This is the most important idea in this lesson. print() shows a value to a person. return gives a value back to the program. A function that only prints gives nothing back:

PythonRun it yourself
def add_and_print(a, b):
    print(a + b)

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

x = add_and_print(2, 3)
y = add_and_return(2, 3)
print("x is", x)
print("y is", y)
Output
5
x is None
y is 5

add_and_print showed 5 on the screen but returned nothing, so x holds None, Python's "no value". In JavaScript, a function without return gives undefined. If you want to use the answer later, return it. Print it only at the end, when you show results to the user.

Default values and local variables

A parameter can have a default value, used when the caller does not pass one. Here, delivery costs ₹40 unless you say otherwise:

JavaScriptRun it yourself
function orderTotal(amount, delivery = 40) {
  const total = amount + delivery;
  return total;
}

console.log(orderTotal(350));
console.log(orderTotal(650, 0));
Output
390
650

Python writes the same default as def order_total(amount, delivery=40):.

The variable total was created inside the function, so it is a local variable: it exists only while the function runs. Code outside the function cannot see it. This is a good thing, because two functions can each have their own total without disturbing each other.

Advanced: functions that use other functions

Small functions can be combined into bigger ones. Here report() calls percentage() and grade():

PythonRun it yourself
def percentage(obtained, maximum):
    return obtained / maximum * 100

def grade(pct):
    if pct >= 90:
        return "A+"
    elif pct >= 75:
        return "A"
    elif pct >= 60:
        return "B"
    return "C"

def report(name, obtained):
    pct = percentage(obtained, 500)
    print(f"{name}: {pct:.1f}%, grade {grade(pct)}")

report("Meera", 468)
report("Kabir", 391)
report("Isha", 320)
Output
Meera: 93.6%, grade A+
Kabir: 78.2%, grade A
Isha: 64.0%, grade B

Notice the last line of grade(): if none of the if branches returned, the function reaches return "C". Each function is short and does one job, so each one is easy to check.

JavaScript also has a short way to write small functions, called an arrow function: const square = (n) => n * n;. This is the style you saw in the sorting example in Lists & Arrays.

Common mistakes

  • Forgetting the brackets. announce without () does not call the function; it just refers to it. Write announce().
  • Printing instead of returning. If you need the answer later, return it. Otherwise you get None or undefined.
  • Wrong number of arguments. Calling greet("Ananya") gives TypeError: greet() missing 1 required positional argument: 'city' in Python.
  • Calling before defining in Python. Python runs top to bottom, so the def must come before the first call.

Key points

  • A function is a named block of code that runs when you call it with brackets.
  • Python defines functions with def name(params):; JavaScript uses function name(params) { }.
  • Parameters receive the arguments passed in a call, matched in order.
  • return sends a value back to the caller and ends the function.
  • print() shows a value to people; return gives it to the program.
  • Parameters can have default values, and variables created inside a function are local to it.

Exercise

An auto-rickshaw charges ₹30 for the first 2 km and ₹15 for each km after that. Write a function fare(km) that returns the fare. Call it for 1 km, 5 km and 12 km, printing a line such as 5 km costs ₹75 for each. Write it in Python and in JavaScript.

Show solution
Python
def fare(km):
    if km <= 2:
        return 30
    return 30 + (km - 2) * 15

for km in [1, 5, 12]:
    print(f"{km} km costs ₹{fare(km)}")
Output
1 km costs ₹30
5 km costs ₹75
12 km costs ₹180
JavaScript
function fare(km) {
  if (km <= 2) {
    return 30;
  }
  return 30 + (km - 2) * 15;
}

for (const km of [1, 5, 12]) {
  console.log(`${km} km costs ₹${fare(km)}`);
}

The function returns the fare instead of printing it, so the loop decides how to show it. If km is 2 or less, the first return ends the function early.

Quick Quiz

1. What does defining a function do?

2. A Python function has no return statement. What does a call to it give back?

3. In def greet(name): and the call greet("Isha"), what is "Isha"?

4. With function total(amount, delivery = 40), what does total(100) return if it adds the two?

Learn Intro to Programming with a mentor

Free lessons get you started. Our Python Programming training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call