Python Functions
In Python, a function is a block of code that can be reused multiple times in a program. Functions are defined using the def keyword, followed by the function name and a set of parentheses. Any input values, or arguments, are placed within the parentheses. The block of code that makes up the function is indented underneath the function definition.
For example:
def say_hello(name):
print("Hello, " + name + "!")
say_hello("John")
# Output: Hello, John!
Test Case
def print_args(*args):
for arg in args:
print(arg)
print_args("Hello", "world!", 1, [1,2,3])
# Output:
# Hello
# world!
# 1
# [1, 2, 3]
Functions can also return a value using the return keyword.
def add_numbers(a, b):
return a + b
result = add_numbers(1, 2)
print(result) #Output: 3
Test cases:
def add_numbers(a, b):
return a + b
# Test Case 1
# Check that the function returns the expected output for basic input
def test_add_numbers():
expected_output = 3
result = add_numbers(1, 2)
assert result == expected_output
# Test Case 2
# Check that the function returns the expected output for negative input
def test_add_numbers_negative():
expected_output = -3
result = add_numbers(-1, -2)
assert result == expected_output
Functions can also have default values for arguments, and can be called with keyword arguments, which allow the caller to specify the argument by name
def repeat_message(message, times=2):
for i in range(times):
print(message)
repeat_message("Hello", times=3)
# Output:
# Hello
# Hello
# Hello
Test case:
def repeat_message(message, times=2):
for i in range(times):
print(message)
# Test Case 1
# Check that the function prints the expected number of messages
def test_repeat_message():
expected_output = "Hello\nHello"
repeat_message("Hello")
# check that function output matches expected output
assert actual_output == expected_output
# Test Case 2
# Check that the function prints the expected number of messages when passing the times argument
def test_repeat_message_times_arg():
expected_output = "Hello\nHello\nHello"
repeat_message("Hello", times=3)
# check that function output matches expected output
assert actual_output == expected_output
Functions can also be called with a varying number of arguments using the * and ** syntaxes.
def print_args(*args):
for arg in args:
print(arg)
print_args("Hello", "world!", 1, [1,2,3])
# Output:
# Hello
# world!
# 1
# [1, 2, 3]
Test case:
def print_args(*args):
for arg in args:
print(arg)
# Test Case 1
# Check that the function prints all the arguments
def test_print_args():
expected_output = "Hello\nworld!\n1\n[1, 2, 3]"
print_args("Hello", "world!", 1, [1,2,3])
# check that function output matches expected output
assert actual_output == expected_output
# Test Case 2
# Check that the function prints no arguments when no arguments are passed
def test_print_args_none():
expected_output = ""
print_args()
# check that function output matches expected output
assert actual_output == expected_output