Unit 3
Functions
Name a piece of thinking once as a Python function, then use it again and again.
Read
Naming a piece of thinking
A school canteen in Pune sells samosas for ₹15. Every time a student asks "how much for 4?", the cashier does the same little thinking: multiply the price by the count. If the canteen computer had to repeat that thinking in every part of its program, it would be copying the same lines over and over, and if the price rule changed, someone would have to find every copy.
There is a better way: give the thinking a name and write it once. That is a function.
A function is a named recipe
You have already used functions:
print("hello"),len(name),max(3, 9). Each has a name, takes some inputs and does a job. Now you will write your own.def double(n): return n * 2This defines a function. It does not run anything yet; it teaches Python a new word. To use it, call it:
print(double(3)) # shows 6 print(double(10)) # shows 20When Python reaches
double(3), it runs the body withnset to 3, gets the answer 6, and the call is replaced by that return value, just as if you had typed 6.Anatomy of a function
defstarts the definition. Then comes the name, inlower_case_with_underscores, and the parameters in brackets, then a colon.- The body is indented (4 spaces). Python uses the indentation to know where the function ends.
- Parameters are names for the inputs inside the function. The actual values you pass when you call it are the arguments.
returnhands a value back and ends the function.
Example. The canteen price rule:
def price(count, cost_each): return count * cost_each print(price(4, 15)) # 60 print(price(2, 30)) # 60Arguments are matched to parameters by position: the first argument goes to
count, the second tocost_each.price(15, 4)still gives 60 here because multiplication is commutative, but a function likedef take_away(a, b): return a - bgives different answers fortake_away(10, 3)(7) andtake_away(3, 10)(-7). Order matters.returnis notprintThis is the most common mistake in the whole topic.
def double_print(n): print(n * 2) # shows the value on screen, gives back nothing def double_return(n): return n * 2 # gives the value back to the caller a = double_return(5) + 1 # a is 11 b = double_print(5) + 1 # shows 10, then ERROR: None + 1printis for people: it puts text on the screen.returnis for the program: it passes a value to the code that called the function so that it can be stored, added or passed to another function. A function with noreturngives back the special valueNone.Misconception. "A function that shows the right number on the screen works." Only if all you ever wanted was to look at it. If you want to use the answer in the next calculation, the function must
returnit.Functions can use other functions
Once you have named a piece of thinking, you can use it inside other thinking.
def price_with_gst(price, rate): return price + price * rate / 100 def bill(price, qty): return price_with_gst(price, 18) * qty print(bill(100, 3)) # 354.0Trace
bill(100, 3): Python callsprice_with_gst(100, 18). That gives . Then . If the GST rule changes, you fixprice_with_gstonce, and every function that uses it is right.Example. An even/odd checker:
def is_even(n): return n % 2 == 0 print(is_even(10)) # True print(is_even(7)) # Falsen % 2is the remainder after dividing by 2, and==compares. The function returnsTrueorFalse, which you can use directly in anif.Variables inside a function stay inside
Variables created inside a function, including its parameters, exist only while it runs. Two functions can both use a variable called
totalwithout interfering.def sum_to(n): total = 0 for i in range(n + 1): total = total + i return total print(sum_to(4)) # 0+1+2+3+4 = 10After the call, there is no
totalin the main program. That is a feature: you can read each function on its own.How to design a function
- Say what it does in one sentence, e.g. "gives the price including GST."
- List the inputs (parameters) and the output (return value).
- Pick a name that says what it does:
price_with_gst, notf1. - Write it, then test it on 2 or 3 inputs where you already know the answer, including an edge case like 0.
Try it: Predict the value of each call, then check in the lab. (a)
double(-4)(b)price_with_gst(50, 5)(c)is_even(0).Reuse is the point
A function names a piece of thinking so you can reuse it. Reuse gives you three things: less typing, fewer bugs (one copy to get right) and clearer programs (
bill(100, 3)says more than six lines of arithmetic). Large programs are built from small functions, each checked on its own.Summary
def name(parameters):defines a function;name(arguments)calls it.returnsends a value back to the caller;printonly shows it. NoreturnmeansNone.- Arguments match parameters by position.
- Functions can call other functions; variables inside stay inside.
- Test with inputs whose answers you know first.
Lab
Function workshop
Five small jobs, each needing a Python function. Finish the return line, run the tests, and fix it until they pass. The last job asks you to reuse a function you wrote earlier.
Your goals
- Write double, celsius_to_f, price_with_gst and is_even so every test passes.
- Write bill by calling price_with_gst (reuse).
- Read the "Should give" and "Yours gives" columns to find and fix a wrong return line.
The interactive lab opens once you register. Register to do this.
Quick check
Functions check
Eight questions on writing and reading Python functions.
1.Which Python keyword starts a function definition?
Answer with a word or phrase
2.What does `return` do inside a function?
- Hands a value back to the code that called the function, and ends the function.
- Prints a value on the screen.
- Starts the function over from the top.
Choose one
3.What does this program give for f(4)? def f(x): return x * x + 1
Answer with a number
4.What is g(3, 10)? def g(a, b): return a - b
Answer with a number
5.What does this program show? def double(n): n * 2 print(double(5))
- 10
- None
- 5
- An error message before anything prints
Choose one
6.In this code, which word is the parameter? def greet(name): return "Hello, " + name greet("Asha")
- name
- greet
- "Asha"
Choose one
7.Which are good reasons to write a function? Choose all that apply.
- You can reuse the same thinking without copying it
- If you find a bug you fix it in one place
- Python makes the program run twice as fast just because it contains functions
- A good name makes the program easier to read
Choose all that apply
8.What does twice(5) give? def inc(x): return x + 1 def twice(x): return inc(inc(x))
Answer with a number
Answering and checking are for registered learners. Register to do this.
Quick check
New puzzles with functions
Read, trace and fix functions you haven't seen before.
1.What is mystery(mystery(2, 6), 10)? def mystery(a, b): return (a + b) / 2
Answer with a number
2.You have this function for two numbers. def bigger(a, b): if a > b: return a return b Which function correctly returns the biggest of THREE numbers?
- def biggest(a, b, c): return bigger(bigger(a, b), c)
- def biggest(a, b, c): return bigger(a, b, c)
- def biggest(a, b, c): return bigger(a, b)
- def biggest(a, b, c): print(bigger(a, b))
Choose one
3.What is f(4)? def f(n): total = 0 for i in range(n): total = total + i return total
Answer with a number
4.What happens when this program runs? def square(n): print(n * n) total = square(3) + square(4)
- total becomes 25.
- It prints 9 and 16, then fails with an error, because square gives back nothing (None) to add.
- It prints 25.
- It prints nothing, because the function is never called.
Choose one
Answering and checking are for registered learners. Register to do this.
Your turn
Write and explain three functions
Complete the three functions in the starter code. Each must return its answer (not print it).
discounted(price, percent)returns the price after taking offpercentper cent.discounted(200, 10)is180.0anddiscounted(50, 0)is50.0.is_leap_year(year)returnsTrueorFalse. A year is a leap year if it is divisible by 4, except century years (divisible by 100), which must also be divisible by 400. So 2024 and 2000 are leap years; 1900 and 2023 are not.total_cost(price, percent, qty)must calldiscountedand multiply byqty.total_cost(200, 10, 3)is540.0.
Then, in comments at the bottom, explain in 2-4 sentences: (a) the difference between
returnandprintin your functions, and (b) one benefit oftotal_costcallingdiscountedinstead of copying its formula.How it's judged
- Correct functions with return
- Reuse
- Explanation
Writing and submitting your answer is for registered learners. Register to do this.
Like what you see?
Register for free to answer the quick checks, do the activities and save your work. Your work is saved on your device and syncs to your account.