Introduction

Welcome to this exciting part of the course where we delve into the fascinating world of functions and their impact on programming. In this article, we will unravel the effects and results of functions, explore the concept of return expressions, and shed light on the enigmatic None value. Get ready to unlock a whole new level of programming proficiency!

Effects and Results: The Return Statement

In Python, functions have effects and can also produce results. To obtain a result from a function, the return statement is used. This keyword provides a clear indication of its capabilities. Let's explore the two different variants of the return statement separately.

1. Return Without an Expression

bee cake and pastry

Consider the following function:

def cake_availability(cake_status=True):
  print("Welcome to Bee Cake and Pastry!")
  if not cake_status:
    print("We are sorry, cake is SOLD OUT")
    return
  print("Special offer: 50% off!")

cake_availability()

When the function is invoked without any arguments:

cake_availability()

The function generates some output before the return statement is encountered:

OUTPUT:

By providing False as an argument:

cake_availability(False)

The function's behavior is modified, and the return statement causes the function to terminate just before the special offer are printed:

OUTPUT:

2. Return with an Expression

The second variant of the return statement involves an expression:

def function():
  return expression

Using this variant has two consequences:

  • It immediately terminates the function's execution, similar to the first variant.
  • The function evaluates the expression and returns its value as the result.

Consider the following example:

bee cake and pastry
def village_chicken():
  print("-Ayam Kampung (village chicken)")
  return 10

def broiler_chicken():
  print("-Ayam Pedaging (broiler chicken)")
  return 15

print("Welcome to Jamil Chicken Farm")

v = village_chicken()
b = broiler_chicken()

total_chicken = v+b

print("We offer various chickens for sale! Available chicken: ", total_chicken)

The output displayed will be:

OUTPUT:

The return statement, enriched with an expression, transports the value of the expression to the location where the function was invoked. The result can be assigned to a variable or ignored completely.

Although ignoring the result is permissible, keep in mind that the result is irretrievably lost. For instance:

def village_chicken():
  print("-Ayam Kampung (village chicken)")
  return 10

def broiler_chicken():
  print("-Ayam Pedaging (broiler chicken)")
  return 15

print("Welcome to Jamil Chicken Farm")

village_chicken()
broiler_chicken()

print("We offer various chickens for sale!")

The output will be:

OUTPUT:

While the function returns a value, it is ignored and not used further. It is important to remember that if a function is intended to provide a useful result, it should utilize the second variant of the return statement.

In summary, the return statement in Python allows functions to have results, which can be used or ignored based on the requirements of the program.

Understanding the Role of None as a Special Value

In Python, we encounter a special value called None, which holds a unique place within the language. While None is not a valid value in the traditional sense, it serves specific purposes and has distinct behaviors that are essential to understand.

The Nature of None

None is a peculiar value that does not represent any meaningful data. It is not considered a regular value and should not be included in any expressions. Attempting to perform operations involving None can result in runtime errors, as demonstrated in the example below:

print(None + 5)

This code snippet would generate a TypeError, indicating an unsupported operand type(s) for the addition: 'NoneType' and 'int'.

Safe Usages of None

There are two primary scenarios in which None can be safely utilized:

a. Assigning or Returning None

None can be assigned to a variable or returned as the result of a function. When a function does not explicitly return a value using a return expression, it is implicitly assumed that the function returns None. Consider the following code snippet:

value = None
if value is None:
   print("No data has been received.")

Here, None is assigned to the variable value, and it is subsequently compared with None to assess its internal state.

b. Diagnosing Function Results

None can be employed as a tool to diagnose the internal state of a variable by comparing it with None. By checking if a variable is None, we can identify situations where a function may unintentionally return None instead of a desired value. For instance:

def flood_alarm(water_level):
  if water_level > 100:
     return True

print(flood_alert(120))
print(flood_alert(50))

In the above function, it is evident that flood_alarm returns True when the argument is even. However, what does it return otherwise? Let’s see what the output of the code would be:

OUTPUT:

This outcome demonstrates the function returning None when the argument is odd.

None as an Indicator

Encountering None as the result of a function can serve as an indication of potential issues or subtle mistakes within the function's implementation. It is crucial to be aware of such occurrences to ensure the intended behavior of the code.

Lists in Function: Effects and Results

When working with functions in Python, it's essential to understand the effects and results that can be achieved with lists of function arguments and results. Let's explore two key questions in this regard.

Passing Lists as Function Arguments:

The first question is whether a list can be sent as an argument to a function. The answer is a resounding yes! Python allows any entity recognizable by the language to serve as a function argument. However, it is crucial to ensure that the function is designed to handle the specific type of entity being passed.

Consider the following example of a function that calculates the jumbo egg in a carton.

def jumbo_egg(egg_weight):
  total = 0

  for w in egg_weight:
    if w > 70:
      total += 1

  return total

x = jumbo_egg([60, 80, 88])
y = jumbo_egg([69])

If we invoke this function like x = jumbo_egg([60, 80, 88]), it will correctly return 2 as the result. However, it's important to note that invoking the function in a risky manner, such as jumbo_egg([69]), will lead to problems. Python will respond with a TypeError, stating that an integer object is not iterable.

Lists as Function Results:

The second question is whether a list can be a result of a function. Once again, the answer is yes! Python allows any entity recognizable by the language to serve as a function result.

Consider the following example of a function that generates a list with a particular pattern:

def student_marks(record):
  pass_list = []

  for i in record:
    if i > 70:
      pass_list.append(i)

  return pass_list

print(student_marks([90, 88, 70, 71, 60]))

Invoking student_marks([90, 88, 70, 71, 60]) will return the list [90, 88, 71] as the result.

These examples demonstrate the versatility of lists in both function arguments and results. Lists provide a flexible and dynamic way to handle collections of data within functions.

It's important to understand the characteristics and limitations of the entities passed to functions. By ensuring that functions are designed to handle the specific types of entities being used, we can create effective and safe functions. This understanding is vital for developing robust and reliable code in Python.

Conclusion

In this article, we explored the effects and results of functions in Python, with a focus on the return statement and the special value None. We discovered that the return statement allows functions to provide results, which can be utilized or ignored based on program requirements. We examined the two variants of the return statement, one without an expression and one with an expression, understanding how they affect function execution and result retrieval.

Furthermore, we delved into the nature of None, a unique value in Python that holds specific significance. We learned that None does not represent meaningful data and should not be used in expressions. However, it can be safely assigned to variables or returned as the result of a function. We also explored how None can be utilized for diagnosing function results and as an indicator of potential issues or mistakes in function implementation.

Lastly, we explored the usage of lists in function arguments and results. We confirmed that lists can be passed as arguments to functions, but it's crucial to ensure that the function is designed to handle the specific type of entity being passed. Additionally, we discovered that lists can be returned as function results, providing a flexible and dynamic way to handle collections of data within functions.

By understanding the effects and results of functions, leveraging the power of return statements and utilizing lists effectively, we can create robust and reliable code in Python. Functions become powerful tools for data manipulation and computation, enabling us to write more efficient and functional programs. So, embrace the capabilities of functions and take your programming proficiency to new heights!

End Of Article

End Of Article