Skip to content
Programming Foundations with Python
Path outline

Lesson

Functions

Pass values into a function and return its result.

Naming a calculation

A function groups instructions so that you can reuse a calculation. You have already called g() to print text. A function can also receive values and return a result. The names inside its parentheses are parameters. When you call the function, the supplied values become those parameters for that call.

Keep a function focused on one job. A function that calculates a value can return it, while the surrounding program handles input and output. This separation makes small examples easier to inspect and larger solutions easier to change.

A complete example

This function converts minutes into seconds.

Python 3
def seconds(minutes):
    return minutes * 60

duration = int(input())
answer = seconds(duration)
print(answer)

With input 3, the output is 180. Execution begins with the definition, which records the function without running its body. The program then reads duration, calls seconds with that value, receives the returned value, and prints it.

The return statement ends the current function call. Instructions after an unconditional return inside the same block do not run. print displays something, but it does not return that displayed value to a caller. Confusing those two actions is a common cause of unexpected output such as None.

Parameters and scope

A parameter exists inside its function call. Changing it does not reassign the caller's integer variable. Prefer passing values into functions and returning results instead of changing a global variable. Some optional exercises ask specifically about global variables, but they are not the default approach.

A function may have no parameters, one parameter, or several. A call must supply the expected arguments. Indent every instruction in the body consistently, and remove that indentation when the surrounding program continues.

Two submission styles

Problems 1410, 1411, and 1412 request complete programs. Define the function, call it, and print or return according to the statement. Problem 1413 is different: its grader reads input and calls your g(n). Submit only that function, without input() or print().

For 1413, the sum 1 through n can be computed as n * (n + 1) // 2. Pairing the smallest and largest terms explains the formula. Use integer division because the result is an integer.

Before submitting, decide who reads input, who prints output, and what the function must return. The statement is authoritative. A correct calculation with the wrong submission shape still fails.

Sign in to save your progress.

Sign in

Practice