Chapter 8: Functions in Python With free Notes

Introduction

Functions are the building blocks of any Python program. They allow you to organize your code into reusable pieces, making it more modular and easier to read. In this chapter, we’ll explore how to define and call functions, handle function arguments, and work with return values. We’ll also dive into the world of lambda functions, which are useful for writing concise, anonymous functions. By the end of this chapter, you’ll be equipped to write efficient and clean code using functions.

Functions in Python


Defining and Calling Functions

A function is a block of reusable code that performs a specific task. Defining a function allows you to group statements together and execute them whenever needed.

Defining a Function

  • To define a function, use the def keyword followed by the function name and parentheses:
  • Here, greet is a simple function that prints a message.
def greet():
    print("Hello, world!")

Calling a Function

To execute the code inside a function, you need to call it by its name followed by parentheses:

greet() # Output: Hello, world!

Function Arguments

Functions often need input values to perform their tasks. These input values are called arguments or parameters.

See also  Data Types in Python
image-55 Chapter 8: Functions in Python With free Notes
Functions in Python

Positional Arguments

Positional arguments are the most common type of arguments. The order in which you pass them matters:

def greet(name):
    print(f"Hello, {name}!")

greet("Alice")  # Output: Hello, Alice!

Keyword Arguments

You can also pass arguments using the keyword format, which makes the function calls clearer:

def greet(name, age):
    print(f"Hello, {name}! You are {age} years old.")

greet(name="Alice", age=30)  # Output: Hello, Alice! You are 30 years old.

Default Arguments

Default arguments allow you to specify default values for parameters:

def greet(name, age=18):
    print(f"Hello, {name}! You are {age} years old.")

greet("Alice")  # Output: Hello, Alice! You are 18 years old.

Return Values

A function can send a result back to the caller using the return statement. This allows the function to output a value that can be used elsewhere in the code.

def add(a, b):
    return a + b

result = add(5, 3)
print(result)  # Output: 8

Lambda Functions

Lambda functions are small, anonymous functions defined using the lambda keyword. They can have any number of arguments but only one expression.

Creating a Lambda Function

  • A typical lambda function looks like this:
  • Here, lambda x: x ** 2 defines a function that takes one argument x and returns x squared.
square = lambda x: x ** 2
print(square(5))  # Output: 25

Using Lambda with Built-in Functions

Lambda functions are often used with built-in functions like map(), filter(), and reduce().

  • Map: Apply a function to all items in an iterable.
  numbers = [1, 2, 3, 4, 5]
  squares = list(map(lambda x: x ** 2, numbers))
  print(squares)  # Output: [1, 4, 9, 16, 25]
  • Filter: Filter items in an iterable based on a condition.
  even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
  print(even_numbers)  # Output: [2, 4]
  • Reduce: Apply a function cumulatively to the items of an iterable.
  from functools import reduce
  sum_numbers = reduce(lambda x, y: x + y, numbers)
  print(sum_numbers)  # Output: 15

Practice Day – Applying What You’ve Learned

Good Coding Questions

Basic Function Practice:

  • Write a function is_even() that takes an integer and returns True if the number is even, and False otherwise.
  • Create a function factorial() that takes a number and returns its factorial using a loop.
See also  Python Command-Line Arguments: A Comprehensive Guide

Function Arguments:

  • Define a function greet_user() that takes a user’s first name and last name and prints a greeting message. Use keyword arguments to call the function.
  • Write a function calculate_area() that calculates the area of a circle given its radius. Use a default argument for the value of Ï€ (pi).

Working with Return Values:

  • Write a function find_max() that takes a list of numbers and returns the maximum value.
  • Create a function reverse_string() that takes a string and returns the string in reverse order.

Lambda Functions:

  • Use a lambda function to create a list of squares of numbers from 1 to 10 using map().
  • Write a lambda function to filter out words from a list that are shorter than 5 characters using filter().

Advanced Lambda Usage:

  • Use reduce() with a lambda function to find the product of all elements in a list.
  • Combine map() and filter() to create a list of squares of even numbers from 1 to 20.

Complete Python Course :- Click here


1 comment

Post Comment