Functions and Scope
A function packages up reusable logic so you’re not repeating yourself every time you need to perform the same task. Once you’ve written and tested a function, you can call it from anywhere in your program with confidence that it behaves the same way each time.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Yash")) # Hello, Yash!
print(greet("Yash", "Welcome")) # Welcome, Yash!
Parameters vs arguments
name and greeting are parameters — placeholders defined when you write the function. The values you pass in when calling the function, like "Yash", are arguments. greeting has a default value, so it’s optional; if you don’t supply one, Python uses "Hello" automatically.
Keyword arguments
def describe_course(title, lessons, level="Beginner"):
return f"{title}: {lessons} lessons ({level})"
# calling by position:
describe_course("Python", 11)
# calling by keyword -- order doesn't matter:
describe_course(lessons=11, title="Python", level="Basic to Pro")
Calling a function with keyword arguments makes the call self-documenting — anyone reading describe_course(lessons=11, title="Python") instantly knows what each value means, without needing to check the function’s definition.
Scope
A variable created inside a function only exists inside that function — this is called local scope. It won’t leak out and clash with a variable of the same name elsewhere in your script, which is exactly why functions are safe to reuse without worrying about accidentally overwriting something important elsewhere.
def add_tax(price):
total = price * 1.18
return total
print(add_tax(100)) # 118.0
# print(total) would raise a NameError here -- total only exists inside add_tax
Return values
A function that doesn’t explicitly return anything returns None by default — this is a common source of bugs when someone forgets the return keyword and then tries to use the function’s result. A function can also return multiple values at once, which Python actually returns as a tuple:
def min_and_max(numbers):
return min(numbers), max(numbers)
lowest, highest = min_and_max([4, 9, 1, 7])
print(lowest, highest) # 1 9
Why this matters
Functions are the building block for everything that follows in this course — every class method you’ll write in the object-oriented programming lesson is really just a function that lives inside an object, and every decorator you’ll see in the advanced lessons is a function that wraps another function.