DEV Community

Cover image for # šŸ Python Functions: 13–19 — Scope, Arguments, Nested Functions & More
Karthick (k)
Karthick (k)

Posted on

# šŸ Python Functions: 13–19 — Scope, Arguments, Nested Functions & More

While learning Python functions, I came across several concepts that initially looked confusing. After practising them one by one, they became much easier to understand.

In this post, I’m sharing my notes and examples for:

  • Positional-only arguments
  • Keyword-only arguments
  • Variable scope
  • Local vs global variables
  • global
  • Nested functions
  • Returning multiple values
  • Functions as objects

1. Positional-Only Arguments /

Sometimes we want a function parameter to be passed only by position, not by its parameter name.

We can use / for this.

def student(name, age, /):
    print(name, age)
Enter fullscreen mode Exit fullscreen mode

This works:

student("Karthick", 25)
Enter fullscreen mode Exit fullscreen mode

But this does not:

student(name="Karthick", age=25)
Enter fullscreen mode Exit fullscreen mode

Everything before / is positional-only.

Example

def calculate(a, b, /):
    return a + b

print(calculate(10, 20))
Enter fullscreen mode Exit fullscreen mode

Output:

30
Enter fullscreen mode Exit fullscreen mode

The / tells Python that a and b must be supplied positionally.


2. Keyword-Only Arguments *

We can also force parameters to be passed using their names.

For this, we use *.

def student(name, *, age):
    print(name, age)
Enter fullscreen mode Exit fullscreen mode

This works:

student("Karthick", age=25)
Enter fullscreen mode Exit fullscreen mode

But this does not:

student("Karthick", 25)
Enter fullscreen mode Exit fullscreen mode

Everything after * is keyword-only.

Easy way to remember

/  → before / = positional-only

*  → after * = keyword-only
Enter fullscreen mode Exit fullscreen mode

3. Variable Scope

Scope means where a variable can be accessed in a program.

For example:

def test():
    x = 10
    print(x)

test()
Enter fullscreen mode Exit fullscreen mode

Here, x is available inside the function.

But:

print(x)
Enter fullscreen mode Exit fullscreen mode

outside the function will cause an error because x belongs to the function's local scope.


4. Local vs Global Variables

Local Variable

A variable created inside a function is normally a local variable.

def test():
    x = 100
    print(x)

test()
Enter fullscreen mode Exit fullscreen mode

Here, x is local to test().

Global Variable

A variable created outside a function is a global variable.

x = 50

def test():
    print(x)

test()
Enter fullscreen mode Exit fullscreen mode

Output:

50
Enter fullscreen mode Exit fullscreen mode

The function can access the global variable.

Easy rule

Created inside a function → Local variable

Created outside a function → Global variable
Enter fullscreen mode Exit fullscreen mode

5. The global Keyword

What if we want to modify a global variable from inside a function?

We can use global.

x = 10

def change():
    global x
    x = 20

change()

print(x)
Enter fullscreen mode Exit fullscreen mode

Output:

20
Enter fullscreen mode Exit fullscreen mode

Without global, this:

def change():
    x = 20
Enter fullscreen mode Exit fullscreen mode

would create a new local x instead of modifying the global one.

Important point

global x does not create a global variable.

It tells Python:

"Inside this function, I want to use the existing global x."


6. Nested Functions

A function defined inside another function is called a nested function.

def outer():

    def inner():
        print("Hello")

    inner()

outer()
Enter fullscreen mode Exit fullscreen mode

Output:

Hello
Enter fullscreen mode Exit fullscreen mode

Here:

outer()
   ↓
inner()
   ↓
Hello
Enter fullscreen mode Exit fullscreen mode

The inner function can also access variables from the outer function.

def outer():
    name = "Karthick"

    def inner():
        print(name)

    inner()

outer()
Enter fullscreen mode Exit fullscreen mode

Output:

Karthick
Enter fullscreen mode Exit fullscreen mode

inner() doesn't have its own name, so it can access name from outer().


7. Functions Returning Multiple Values

A Python function can return multiple values.

def calculate(a, b):
    return a + b, a * b, a - b
Enter fullscreen mode Exit fullscreen mode

We can store the returned values separately:

sum_value, product, difference = calculate(5, 2)

print(sum_value)
print(product)
print(difference)
Enter fullscreen mode Exit fullscreen mode

Output:

7
10
3
Enter fullscreen mode Exit fullscreen mode

Python actually packs the returned values into a tuple:

(7, 10, 3)
Enter fullscreen mode Exit fullscreen mode

Then we unpack them:

(7, 10, 3)
 ↓   ↓   ↓
sum product difference
Enter fullscreen mode Exit fullscreen mode

Important rule

The number of variables should match the number of values being unpacked.

For example:

def test():
    return 10, 20, 30

a, b, c = test()
Enter fullscreen mode Exit fullscreen mode

This works.

But:

a, b = test()
Enter fullscreen mode Exit fullscreen mode

causes an error because there are 3 returned values but only 2 variables.


8. Functions as Objects

One of the interesting things about Python is that functions are objects.

Consider:

def greet():
    return "Hello"
Enter fullscreen mode Exit fullscreen mode

We can assign the function to another variable:

x = greet
Enter fullscreen mode Exit fullscreen mode

Notice that there are no parentheses.

Now x refers to the same function.

So we can do:

print(x())
Enter fullscreen mode Exit fullscreen mode

Output:

Hello
Enter fullscreen mode Exit fullscreen mode

Important difference

x = greet
Enter fullscreen mode Exit fullscreen mode

means:

x refers to the function itself.

Whereas:

x = greet()
Enter fullscreen mode Exit fullscreen mode

means:

Call the function and store its returned value in x.

For example:

def square(n):
    return n * n

operation = square

result = operation(5)

print(result)
Enter fullscreen mode Exit fullscreen mode

Output:

25
Enter fullscreen mode Exit fullscreen mode

The flow is:

square
  ↓
function object
  ↓
operation = square
  ↓
operation(5)
  ↓
square(5)
  ↓
25
Enter fullscreen mode Exit fullscreen mode

This is the foundation for passing functions to other functions.

I'm continuing my Python function learning with the next concept: passing functions to other functions.

Top comments (0)