Lesson 8 of 12
Learn functions with flowchart blocks: give a job a name, Call it with values, and Return the answer. Open working examples and see them as real code.
About 6 minutes · 3 parts, each with a program to try
Part 1 of 3
A Function block starts a small flowchart with a name, like discount, and the values it's given, like price.
Write a job once, then use it as often as you like.
def lineTotal(price, qty): cost = price * qty return cost
print("Stationery shop: pens ₹10 each, notebooks ₹45 each")pens = int(input("How many pens? "))pensCost = lineTotal(10, pens)books = int(input("How many notebooks? "))booksCost = lineTotal(45, books)total = pensCost + booksCostprint("Pens: ₹" + str(pensCost))print("Notebooks: ₹" + str(booksCost))print("Total to pay: ₹" + str(total))Part 2 of 3
A Call block runs the function with real values, like discount(500). Its Return block gives the answer back, and the Call keeps it in a value.
Press Step and watch the program jump into the function and back.
def gradeFor(score): if score >= 80: return "A" elif score >= 60: return "B" elif score >= 40: return "C" else: return "Fail"
marks = [92, 67, 48, 30]for mark in marks: grade = gradeFor(mark) print("Mark " + str(mark) + " is grade " + grade)print("All marks graded!")Part 3 of 3
A function can Call itself, with a smaller problem each time: fact(5) is 5 * fact(4). That's recursion.
It needs a stop (the base case), like n <= 1. Open Values and Step: each call waits on the call stack until the one above it gives back its answer.
def fact(n): if n <= 1: return 1 else: smaller = fact(n - 1) return n * smaller
n = int(input("Factorial of which number? "))answer = fact(n)print(str(n) + "! = " + str(answer))Quick check