1 of 6
Functions are reusable blocks of code you give a name to, so you can run them whenever you want without rewriting the same code.
print("Welcome, Alex!") print("Your adventure begins!") print("Welcome, Sam!") print("Your adventure begins!") print("Welcome, Jordan!") print("Your adventure begins!")
That's a lot of copy-paste! What if you want to change the message? You'd have to edit it 3 times.
def welcome(name): print(f"Welcome, {name}!") print("Your adventure begins!") welcome("Alex") welcome("Sam") welcome("Jordan")
Now if you want to change the message, you only change it once inside the function.
def function_name(parameter1, parameter2): # code goes here (indented!) return result
def β keyword that says "I'm creating a function"return β sends a value back (optional)This is the most important thing to understand:
# This function PRINTS (shows text, but gives back nothing) def greet(name): print(f"Hi {name}!") # This function RETURNS (gives back a value you can use) def double(number): return number * 2
Why does it matter?
# With return β you can save and use the result result = double(5) print(result) # 10 print(double(5) + 3) # 13 # With print β the value is gone after printing result = greet("Alex") # Prints "Hi Alex!" but... print(result) # None! There's nothing to save
Rule of thumb:
def add(a, b): return a + b # Calling the function: answer = add(3, 5) print(answer) # 8 # You can also use it directly: print(add(10, 20)) # 30
The values you pass in (3, 5) are called arguments. They get matched to the parameters (a, b) in order.
β Standard library: heapq, collections, itertools, math, random, functools, datetime, bisect
β Functions, classes, recursion, print()
β No file system, subprocess, OS access, or network requests
β No pip install (all supported modules are pre-loaded)
β±οΈ 5 second execution time limit