Function

Defining and calling functions

To define a function in Python, use the def statement, followed by a function name, parentheses (), and a colon :. The function body is indented, usually by 4 spaces. Functions can return values using the return statement. And to call a function, simply use the function’s name followed by parentheses ().

def greet():
    print("Hello, World!")

greet()

Arguments and Parameters

Functions can have input values, called arguments, which are passed to the function when it is called. Within the function, these input values are known as parameters. Parameters are defined within the parentheses () in the function definition, and arguments are passed to the function within the parentheses when calling the function.

# Defining a function with a parameter 'name'
def greet(name):
    print("Hello,", name)

# Calling the function with an argument 'Alice'
greet("Alice")

Lambda functions

Lambda functions, also known as anonymous functions, are small, single-expression functions in Python that you can define using the lambda keyword. They are useful for short, simple operations and can be defined in one line. Lambda functions are useful when working with functions like map(), filter() or sorted(), where a small function needs to be passed.

lambda arguments: expression

Remember: Use lambda functions for simple operations, and regular def functions for more complex tasks to keep your code readable.

# A lambda function to add two numbers:
add = lambda x, y: x + y
result1 = add(5, 3)
print(result1)

# A lambda function to find the square of a number:
square = lambda x: x**2
result2 = square(4)
print(result2)

# sorting a list of strings by length:
text_list = ["apple", "banana", "cherry", "kiwi"]
sorted_list = sorted(text_list, key=lambda x: len(x))
print(sorted_list)

Built-in functions

Python comes with numerous built-in functions that are readily available for use. These are just a few examples of the built-in functions available in Python that are commonly used. There are many other built-in functions that can save time and simplify code when working with data. Refer to the official Python documentation for the complete list: Python Built-in Functions

sorted()

sorted(iterable, *, key=None, reverse=False): Returns a new sorted list from the specified iterable.

my_list = [3, 2, 5, 1, 4]
sorted_list = sorted(my_list)
print(sorted_list)

map()

map(function, iterable): Applies a given function to all items in the input iterable, such as lists or tuples, and returns an iterable of the results.

numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
print(squares)

filter()

filter(function, iterable): Filters the elements from an iterable, passing only those elements for which the input function returns True.

numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)

zip()

zip(*iterables): Combines multiple iterables, like lists or tuples, into a single iterable, pairing elements at the same index in each input iterable.

names = ["Alice", "Bob", "Carol"]
ages = [30, 25, 28]
combined = list(zip(names, ages))
print(combined)

Exercise Function

!pip install rggrader
# @title #### Student Identity
student_id = "TESTRK123" # @param {type:"string"}
name = "Ricky" # @param {type:"string"}
# @title #### 00. Circle Area Function
from rggrader import submit
import math

rad = 5

# TODO: Define a function 'calculate_area' that takes a radius as a parameter and returns the area of a circle with that radius.
def calculate_circle_area(radius):
    # Put your code here:


    # ---- End of your code ----
    return 0

print(f"The area of the circle with radius {rad} is {calculate_circle_area(rad)}")

# Submit Method
assignment_id = "02-function"
question_id = "00_circle-area-function"
submit(student_id, name, assignment_id, str(calculate_circle_area(rad)), question_id)

# Expected Output for rad=5: 78.53981633974483
# @title #### 01. Fun with Lambda and Filter
from rggrader import submit

# Given a list of positive integers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# TODO: Use a lambda function and the 'filter' function to keep numbers less than 6.
# Result should be a list of numbers less than 6.
filtered_numbers = None

# Put your code here:


# ---- End of your code ----

print(f"The filtered numbers are {filtered_numbers}")

# Submit Method
assignment_id = "02-functions"
question_id = "01_fun-with-lambda-and-filter"
submit(student_id, name, assignment_id, str(filtered_numbers), question_id)

# Expected Output: [1, 2, 3, 4, 5]
# @title #### 02. Adventures with Map and Filter
from rggrader import submit

# Given a list of positive integers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# TODO: Use the 'map' function to double the numbers and the 'filter' function to keep numbers less than 15.
# Hint: You can use 'map' and 'filter' together.
modified_numbers = None

# Put your code here:


# ---- End of your code ----

print(f"The modified numbers are {modified_numbers}")

# Submit Method
assignment_id = "02-functions"
question_id = "02_adventures-with-map-and-filter"
submit(student_id, name, assignment_id, str(modified_numbers), question_id)

# Expected Output: [2, 4, 6, 8, 10, 12, 14]
Back to top