def greet():
print("Hello, World!")
greet()
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 ()
.
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'
"Alice") greet(
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:
= lambda x, y: x + y
add = add(5, 3)
result1 print(result1)
# A lambda function to find the square of a number:
= lambda x: x**2
square = square(4)
result2 print(result2)
# sorting a list of strings by length:
= ["apple", "banana", "cherry", "kiwi"]
text_list = sorted(text_list, key=lambda x: len(x))
sorted_list 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.
= [3, 2, 5, 1, 4]
my_list = sorted(my_list)
sorted_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.
= [1, 2, 3, 4, 5]
numbers = list(map(lambda x: x**2, numbers))
squares print(squares)
filter()
filter(function, iterable)
: Filters the elements from an iterable, passing only those elements for which the input function returns True
.
= [1, 2, 3, 4, 5]
numbers = list(filter(lambda x: x % 2 == 0, numbers))
even_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.
= ["Alice", "Bob", "Carol"]
names = [30, 25, 28]
ages = list(zip(names, ages))
combined print(combined)
Exercise Function
!pip install rggrader
# @title #### Student Identity
= "TESTRK123" # @param {type:"string"}
student_id = "Ricky" # @param {type:"string"} name
# @title #### 00. Circle Area Function
from rggrader import submit
import math
= 5
rad
# 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
= "02-function"
assignment_id = "00_circle-area-function"
question_id str(calculate_circle_area(rad)), question_id)
submit(student_id, name, assignment_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
= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers
# 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.
= None
filtered_numbers
# Put your code here:
# ---- End of your code ----
print(f"The filtered numbers are {filtered_numbers}")
# Submit Method
= "02-functions"
assignment_id = "01_fun-with-lambda-and-filter"
question_id str(filtered_numbers), question_id)
submit(student_id, name, assignment_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
= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers
# 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.
= None
modified_numbers
# Put your code here:
# ---- End of your code ----
print(f"The modified numbers are {modified_numbers}")
# Submit Method
= "02-functions"
assignment_id = "02_adventures-with-map-and-filter"
question_id str(modified_numbers), question_id)
submit(student_id, name, assignment_id,
# Expected Output: [2, 4, 6, 8, 10, 12, 14]