Functions. Advanced
More on functions
More on Functions
The concepts in this lesson are not strictly necessary for competitive programming — you can solve most problems knowing only the basics from the previous lesson. However, they are genuinely useful Python features that will make your code cleaner and more expressive once you are comfortable with the fundamentals.
Scope
Scope refers to where a variable is visible and accessible. In Python, variables defined inside a function are local — they only exist within that function and disappear when it returns:
Variables defined outside all functions are global — they are visible everywhere:
Modifying a Global Variable
Reading a global variable from inside a function works fine. But if you want to modify it, you must declare it with global:
Without global, Python would treat count inside the function as a new local variable and raise an error.
In competitive programming, global variables are sometimes used to share state across functions — for example, a visited array in graph traversal.
Nested Functions
You can define a function inside another function. The inner function has access to variables from the outer function:
The inner function is only visible inside outer — you cannot call it from outside.
A practical use: wrapping a recursive helper inside the main function to keep your code organized:
Keyword Arguments
When calling a function, you can pass arguments by name — these are called keyword arguments. This makes calls more readable and lets you pass arguments in any order:
**kwargs — Arbitrary Keyword Arguments
**kwargs lets a function accept any number of keyword arguments. They arrive as a dictionary:
Similarly, *args collects any number of positional arguments into a tuple:
You can combine them:
Lambda Functions
A lambda is a small anonymous function written in a single line. The syntax is:
It is equivalent to a regular function that returns the expression:
Lambda functions are most useful when you need a short function as an argument to another function — most commonly with sorted(), min(), max(), or map():
In competitive programming, lambdas inside sorted() or key= are the most common use case. For anything more complex than a single expression, write a regular function — it will be clearer.