Skip to main content
Practice

Keyword Arguments and Variable Scope

Functions can behave very differently depending on how parameters are set and where variables are defined.

In this lesson, we'll explore keyword arguments and variable scope.


Calling with Keyword Arguments

Sometimes you may not remember the order of arguments to pass to a function.

In such cases, you can use keyword arguments.

By using keyword arguments when calling a function, you can explicitly specify the names of the parameters.


Example of using keyword arguments
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")

# Calling the function with keyword arguments
greet(name="John Doe", age=30)

# Can change the order of arguments
greet(age=25, name="Jane Smith")

In the code above, the greet function takes two parameters: name and age.

When calling the function, passing arguments as name="John Doe", age=30 specifies the parameters explicitly, so you don't need to remember their order.

This way, using functions with keyword arguments can improve code readability by eliminating the need to remember parameter order.


Local Variables Defined Inside Functions

Variables defined inside a function are called local variables. Local variables disappear after the function execution ends.

These local variables cannot be accessed outside the function, and having the same variable name in different functions does not cause interference.

Example of using local variables
# Function to calculate the area of a square
def calculate_square_area(side):
# Calculate area by squaring the side
area = side ** 2
# Return the area
return area

# Calculate the area of a square with a side length of 5
result = calculate_square_area(5)

# Prints 25
print(result)

# Variables defined inside the function are not accessible outside the function
# print(area)
# NameError: name 'area' is not defined

In the code above, the area variable is only valid within the calculate_square_area function and does not exist outside the function.


Variables That Persist Outside Functions: Global Variables

Conversely, variables defined outside functions are called global variables and are accessible in all functions.

However, to modify global variables inside a function, you must use the global keyword.

Example of using global variables
count = 0  # Global variable

def increment():
# Use the global variable count inside the function
global count
count += 1 # Increase the global variable count

increment()
print(count) # Prints 1

increment()
print(count) # Prints 2

By using the global keyword, you can modify global variables within a function.

However, overuse of global variables can decrease code readability and make debugging more difficult, so it is recommended to use them sparingly and only when necessary.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.