fbpx

Written by , 7:29 pm Blogs, Python

Functions and Scope in Python

When it comes to programming, writing reusable code is essential. In Python, functions are a powerful tool that allows you to bundle a block of code into a single entity that can be called repeatedly. Let’s explore how functions work in Python, as well as the concept of scope, which defines where variables can be accessed within your code.

Why Use Functions?

Imagine you want to perform a mathematical operation, such as adding two numbers and then multiplying the sum by 2.

You could write the following code:

a = 2
b = 3
c = a + b
d = c * 2
print(d)

While this works perfectly for these specific numbers, it quickly becomes tedious if you need to perform the same operation with different numbers. Instead of rewriting the same code, you can define a function. Functions allow you to create reusable blocks of code that can be called with different inputs.

Here’s how you can define a function for this operation:

def add_and_multiply(a, b):
    c = a + b
    d = c * 2
    print(d)

Let’s break down this function definition:

  1. The def Keyword: This is used to define a function.
  2. Function Name: add_and_multiply is the name of the function. You should always provide a meaningful name after the def keyword.
  3. Parentheses (): These are used to define inputs for the function, known as parameters.
  4. Parameters: Inside the parentheses, you list the variables that will be provided when the function is called.
  5. Colon :: This indicates that the function definition begins after this point.
  6. Function Body: The code to execute when the function is called goes here, indented for clarity.

Now that the function is defined, you can call it with different sets of numbers:

add_and_multiply(2, 3) # Output: 10
add_and_multiply(4, 5) # Output: 18
add_and_multiply(6, 7) # Output: 26

When we call a function, we provide it with values, here a will be assigned the value 2 and b will be assigned the value 3.

That looks good, but let’s make it complete.

A function can also have a return value. Suppose you don’t want to print the final value of the operations, but instead want to use it for something else, what would you do?

def add_and_multiply(a, b):
    c = a + b
    d = c * 2
    return d

output = add_and_multiply(2,3)
print(output)

What did we just do there?
By writing return d the function will return the value as a variable that can be used. This allows more flexibility over our code.

Exercise 1: Write your own function

Complete the Following Function which takes two numbers as input and prints the sum multiplied by the first number.

For example, if the numbers are 5 and 6, the function should output:

5 + 6 = 11
11 * 5 = 55

Here’s a sample code for you to start with:

Output

Understanding Scope

Scope refers to the region of code where a variable can be accessed. In Python, there are two main types of scope:

  1. Global Scope: A variable is in the global scope if it is defined outside any function. These variables can be accessed anywhere in the program.
  2. Local Scope: A variable is in the local scope if it is defined inside a function. These variables can only be accessed within that function.

For example:

def my_function(): 
    x = 10 # Local variable 
    print(x) # This will work 

my_function() 
# print(x) # This will raise an error since x is not accessible here

In this code, the variable x is local to my_function and cannot be accessed outside of it.

Scope Management

Scope helps maintain clean and organized code and prevents naming conflicts. If you have a global variable and a local variable with the same name, the local variable will take precedence.

Here’s a simple exercise to illustrate this:

x = 5 # Global variable 
def my_function(): 
    x = 10 # Local variable 
    print("Inside function:", x) 

Exercise 2: Understanding Local and Global Scope

Complete the following code to understand the concept of local and global variables in Python.Write a function that demonstrates the difference between local and global scope by printing a local variable inside the function and the global variable outside of it.

Example: Given the following code, the output should be:

Inside function: 50
Outside function: 20

Here’s a sample code for you to start with:

Using the global Keyword

If you need to modify a global variable inside a function, you can use the global keyword. This tells Python that you want to use the global variable instead of creating a new local variable with the same name:

x = 10 
def my_function(): 
    global x 
    print("Before change:", x) # Accessing global x 
    x = 20 # Modifying global x 
my_function() 
print("After change:", x) # Now x is 20

Exercise 3: Using global Keyword

Complete the following function that modifies a global variable inside a function using the global keyword. Print the value of a global variable before and after changing it within the function.

Given the following code, the output should be:

Before change: 10
After change: 20
Final value of x: 20

Here’s a sample code for you to start with:

Conclusion

Understanding functions and scope in Python is crucial for writing efficient and manageable code. Functions allow you to encapsulate and reuse code, while scope helps you keep your variables organised and avoids conflicts. As you continue to explore Python, keep these concepts in mind to enhance your programming skills!

Authors

Close Search Window
Close