Lesson 1

Welcome to the lesson on recalling functions in Python. Functions are fundamental building blocks that allow for code modularity, reusability, and better organization. Understanding functions helps you write cleaner and more maintainable code.

The goal of this lesson is to refresh your memory on defining and calling functions effectively in Python.

In Python, a function is defined directly using the `def`

keyword. There is no need for a separate declaration step. This makes defining and using functions straightforward and efficient.

A function definition provides the function's actual body and specifies what the function does when it is called. Functions can receive any number of arguments separated by commas.

Consider these function definitions in our code snippet:

Python`1def add(a, b): 2 return a + b 3 4def greet(name): 5 print(f"Hello, {name}!") 6 7if __name__ == "__main__": 8 pass`

The `add`

function returns the sum of the two input parameters, while the `greet`

function prints a greeting message. The `pass`

statement in the `if __name__ == "__main__":`

block indicates an empty block of code that does nothing. It acts as a placeholder.

Once functions are defined, they can be called from the main body of the script or any other function.

Calling a function involves specifying the function name followed by arguments in parentheses. If a function does not have a return statement, it returns `None`

by default.

In our code snippet, we call the `add`

function from the main body:

Python`1def add(a, b): 2 return a + b 3 4def greet(name): 5 print(f"Hello, {name}!") 6 7if __name__ == "__main__": 8 sum_ints = add(2, 3) 9 sum_doubles = add(2.5, 3.5) 10 11 greet("Alice") # Hello, Alice! 12 13 print("Sum of ints:", sum_ints) # Sum of ints: 5 14 print("Sum of doubles:", sum_doubles) # Sum of doubles: 6.0`

Here, `add(2, 3)`

returns 5, and `add(2.5, 3.5)`

returns 6.0. The results are then printed using `print()`

. The `greet("Alice")`

function doesn't return anything useful, so we call it without assigning its result to a variable.

As a reminder, `if __name__ == "__main__":`

is a special block in Python that ensures certain code runs only when the script is executed directly, not when it's imported as a module in another script. It is considered a good practice to include this in your Python scripts.

If you do not know how many arguments will be passed into your function, you can add a `*`

before the parameter name in the function definition. This allows your function to accept an arbitrary number of arguments.

Here's an example:

Python`1def add_multiple(*args): 2 return sum(args) 3 4if __name__ == "__main__": 5 sum_all = add_multiple(1, 2, 3, 4) 6 print("Sum of all numbers:", sum_all) # Sum of all numbers: 10`

You can also send arguments with the `key=value`

syntax, allowing the order of the arguments to be irrelevant.

Here's an example:

Python`1def greet(name, greeting): 2 print(f"{greeting}, {name}!") 3 4if __name__ == "__main__": 5 greet(name="Bob", greeting="Hi") # Hi, Bob!`

In this example, `name="Bob", greeting="Hi"`

uses keyword arguments to specify which parameter each value corresponds to. In this case, the order doesn't matter: for example, `greet(greeting="Hi", name="Bob")`

is also valid.

Let's look at an example that involves working with lists. Suppose we want a function that calculates the average of a list of integers. We'll call this function `find_average`

. The function will take a list as input, iterate through the elements to find the sum, and then compute the average.

Here's how to implement `find_average`

:

Python`1def find_average(lst): 2 if not lst: 3 return 0 # avoid division by zero 4 return sum(lst) / len(lst) 5 6if __name__ == "__main__": 7 numbers = [1, 2, 3, 4, 5] 8 average = find_average(numbers) 9 10 print("The average is:", average) # The average is: 3.0`

Note that the `sum()`

and `len()`

functions are used to calculate the sum and size of the list, respectively.

In this example, the `find_average`

function calculates the average of the integers in the `numbers`

list and returns the result.

Next, we'll recall boolean functions by implementing a function to check if a number is prime. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. We'll call this function `is_prime`

.

Here's how to implement `is_prime`

:

Python`1import math 2 3def is_prime(num): 4 if num <= 1: 5 return False 6 for i in range(2, int(math.sqrt(num)) + 1): 7 if num % i == 0: 8 return False 9 return True 10 11if __name__ == "__main__": 12 pass`

**Explanation:**

- If the number is less than or equal to 1, it's not prime.
- The function checks for divisors up to the square root of
`num`

. - If a divisor is found,
`False`

is returned. - If no divisors are found,
`True`

is returned.

In the main body, you can call `is_prime`

like this:

Python`1import math 2 3def is_prime(num): 4 if num <= 1: 5 return False 6 for i in range(2, int(math.sqrt(num)) + 1): 7 if num % i == 0: 8 return False 9 return True 10 11if __name__ == "__main__": 12 number = 29 13 14 if is_prime(number): 15 print(f"{number} is a prime number.") # 29 is a prime number. 16 else: 17 print(f"{number} is not a prime number.")`

In this example, the `is_prime`

function checks if `number`

is prime and returns `True`

if it is, and `False`

otherwise. The result is printed using `print()`

.

In this lesson, we reviewed function definition and usage in Python. We saw how to define a function to specify its behavior and call these functions to perform tasks. We also covered how functions can accept an arbitrary number of arguments, use keyword arguments, and handle various tasks such as arithmetic operations, working with lists, or checking for prime numbers.

It's time to put what you've learned into practice. By working through practical exercises, you'll deepen your understanding and make these concepts second nature.

Let's move on to the practice session, where you'll write and call your functions, and ensure you've mastered the basics of Python functions!