Functions and Scope
Functions and Modules — cheat sheet
Put repeated work in named functions, then use built-in tools and modules to keep code organized.
Define and return
def greet(name):
print(f"Hello, {name}!")Define reusable code with def and an indented body.
def add(left, right):
return left + rightreturn sends a result back to the caller.
result = add(3, 4)Call a function with arguments in parentheses.
def split_name(full_name):
return full_name.split()A function can return multiple values as a tuple.
Arguments
def introduce(name, age):
print(name, age)Parameters receive values passed into a function.
introduce(age=12, name="Mina")Keyword arguments name the parameter they fill.
def welcome(name, greeting="Hello"):
print(greeting, name)A default makes an argument optional.
def show_order(item, *extras, **details):
print(item)*extras and **details collect extra arguments.
Scope and recursion
message = "outside"
def show():
print(message)A function can read a global value.
def paint(color):
print(color)A parameter is local and can shadow a global name.
score = 0
def add_point():
global score
score += 1global allows a function to reassign a global name.
def factorial(number):
if number == 0:
return 1
return number * factorial(number - 1)Recursive functions need a base case that stops calls.
Lambdas and built-ins
words = ["pear", "fig"]
ordered = sorted(words, key=lambda word: len(word))Use a lambda as a short sorting rule.
squares = list(map(lambda number: number * number, [1, 2, 3]))map transforms every item with a function.
evens = list(filter(lambda number: number % 2 == 0, [1, 2, 3]))filter keeps items whose test is true.
print(sum([2, 3]), min([2, 3]), max([2, 3]))Built-ins solve common calculations quickly.
Modules
import math
print(math.sqrt(81))Import a module, then use its names with a dot.
from math import ceil as round_up
print(round_up(4.2))Import one name and optionally give it an alias.
import random
random.seed(0)
print(random.randint(1, 10))A fixed seed makes a learning example repeatable.
if __name__ == "__main__":
print("Starting")This block runs when the file runs directly.