Loading
0x40Lesson 5 of 10

Write reusable functions

Define functions, pass arguments and return results.

12 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Create a function that accepts input and returns a value.

A function packages reusable work. Define one with def, give it a name and parameters, then indent its body. return sends a result back to the caller; print only displays a value.

main.py
1def greet(name):
2    return "Hello, " + name
3
4print(greet("Sam"))
Output
Hello, Sam

Parameters are names listed in the definition; arguments are values supplied when calling the function. A function without an explicit return gives back None.

Key takeaways

  • Create a function that accepts input and returns a value.

  • Read the output to check what your program did.

  • Keep indentation consistent in Python blocks.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write Python

Write Python in the editor and run it against sample inputs. Python runs locally in your browser using a WebAssembly runtime.

Exercise 1

Create a greeting function

+25 XP

Define greet(name) so it returns Hello, followed by the supplied name. Read one name and print the function result.

  • Greet Ada
  • Greet Lin
main.py
Loading editor…

Python runs in a sandboxed browser worker with a 60 second time limit. Its runtime loads from the Pyodide CDN; your code stays in this browser.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…