Functions
def add(a, b):
return a + b
total = add(2, 3)Values go in, the function does its work, and a result comes out.
1Level 1 · BasicsBasics
You've been using functions since lesson one: print(), len(), input(). Now you'll write your own. A function is a named, reusable block of code: write it once, use it many times.
Defining and calling a function
def greet():
print("Hello!")
print("Welcome to LearnPy Hub")
greet() # call it
greet() # and again
def starts a definition, then the name, brackets and a colon. The indented body runs only when you call the function by writing its name with brackets.
Parameters: giving a function input
def greet(name):
print("Hello,", name)
greet("Mim") # Hello, Mim
name is a parameter, a variable that receives the value you pass in (the argument). A function can take several parameters, separated by commas.
return: giving a value back
def area(width, height):
return width * height
a = area(4, 5) # a is 20
return sends a result back to whoever called the function and ends the function immediately. A function without return gives back None. Printing is not returning: printed text just appears on screen, while a returned value can be stored, compared and used in more calculations.
Default and keyword arguments
def power(base, exp=2): # exp defaults to 2
return base ** exp
power(5) # 25
power(2, 10) # 1024
power(exp=3, base=2) # 8, arguments by name
Scope: variables inside functions
Variables created inside a function are local: they exist only while the function runs and can't be seen outside it. This keeps functions independent. Pass values in as parameters and get results out with return rather than relying on outside variables.
Docstrings
A string on the first line of a function describes what it does. Tools and help() show it to other programmers.
Key points:def name(params):defines; calling runs it;returnsends a value back (otherwise you get None); defaults make parameters optional; variables inside a function are local.
See it in actionA function call gets its own space
When area() is called a new frame appears with w and h. It disappears when the function returns.
Try it yourselfExample 1: Define and call
The function body runs each time you call it, with different arguments.
Output appears hereDefine a greeting
Fill the blanks to define a function and call it, so the program prints Hello, Ayan!.
greet(name): print(f"Hello, {name}!") ("Ayan")
Example 2: Returning values
Returned values can be stored and used in further calculations.
Output appears hereReturn the area
Fill the blank so the function gives back the area and the program prints 24.
def area(w, h): w * h print(area(4, 6))
Example 3: Returning several values
Return a tuple and unpack it into separate variables.
Output appears hereBiggest of three
Write a function biggest(a, b, c) that returns the largest of three numbers without using max(). Then print biggest(4, 11, 7), which is 11.
Example 4: Print vs return
shout() returns text; say() only prints it and returns None.
Output appears herePrint is not return
double(5) + 1 should be 11, but the program crashes. Fix the function.
Example 5: Local scope
The x inside the function is a different variable from the x outside it.
Output appears hereIs it even?
Write is_even(n) that returns True or False. Read a number and print the result.
Example input10Expected outputTrue
2Level 2 · IntermediateFlexible arguments
*args and **kwargs
def total(*nums): accepts any number of positional values as a tuple. def profile(**info): collects keyword arguments into a dictionary.
Unpacking when calling
f(*my_list) spreads a list into separate arguments; f(**my_dict) spreads a dictionary into keyword arguments.
The mutable default trap
Default values are created once, when the function is defined. def add(item, box=[]): keeps the same list between calls. Use box=None and create the list inside.
Functions are values
You can store functions in a list or dictionary and pass them to other functions, such as a calculator that looks up the operation by name.
See it in actionThe mutable default trap
Watch box keep its old items on the second call.
Example 6: *args, **kwargs and unpacking
The same function accepts 2 numbers or 20.
Output appears hereExample 7: A calculator built from functions
Add a "pow" entry to the dictionary to support powers.
Output appears here3Level 3 · AdvancedClosures, keyword-only arguments and type hints
Closures
A function defined inside another remembers the outer variables even after the outer function returns. nonlocal lets it change them. This is how counters and decorators keep state.
Keyword-only and positional-only
Arguments after a lone * must be named: def send(to, *, urgent=False). Arguments before / can't be named. This makes calls clearer and safer.
Type hints and docstrings
def area(w: float, h: float) -> float: documents what goes in and out. Tools like mypy check them; help(area) shows the docstring.
Pure functions
A pure function only uses its inputs and returns a result, without changing anything outside. Pure functions are easy to test and reuse.
See it in actionA closure remembers
Watch each counter keep its own count in its own frame.
Example 8: Keyword-only arguments and hints
Remove the
Output appears heregreet just names the function, while greet() calls it. And if a function prints its answer instead of returning it, result = f(3) stores None.What does this print?
def f(x):
x * 2
print(f(3))50 graded problems are waiting in Topic Practice.