Introduction to Sets
Syntax:
Example:
A set is an unordered collection of unique elements. Sets are mutable, but their elements must be immutable (e.g., strings, numbers, tuples). Sets do not allow duplicate values.
Syntax:
my_set = {element1, element2, element3, ...}Example:
fruits = {"apple", "banana", "cherry"}
print(fruits) # Output: {'apple', 'banana', 'cherry'}Set Operations
Examples:
Sets are useful for mathematical operations like union, intersection, difference, and symmetric difference.
union(): Returns a set containing all unique elements from both sets.intersection(): Returns a set containing only the common elements.difference(): Returns a set containing elements that are only in the first set.symmetric_difference(): Returns a set containing elements in either set but not both.Examples:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1.union(set2)) # Output: {1, 2, 3, 4, 5, 6}
print(set1.intersection(set2)) # Output: {3, 4}
print(set1.difference(set2)) # Output: {1, 2}
print(set1.symmetric_difference(set2)) # Output: {1, 2, 5, 6}Modifying Sets
Examples:
Sets can be modified by adding or removing elements:
add(element): Adds an element to the set.remove(element): Removes an element from the set; raises KeyError if not found.discard(element): Removes an element from the set; does nothing if not found.clear(): Removes all elements from the set.pop(): Removes and returns a random element from the set.Examples:
fruits.add("orange")
print(fruits) # Output: {'apple', 'banana', 'cherry', 'orange'}
fruits.remove("banana")
print(fruits) # Output: {'apple', 'cherry', 'orange'}
fruits.discard("banana") # No error if "banana" is not in the set
print(fruits) # Output: {'apple', 'cherry', 'orange'}
fruits.clear()
print(fruits) # Output: set()Frozensets
Example:
A frozenset is an immutable version of a set. It cannot be modified after it is created.
Example:
frozen_set = frozenset([1, 2, 3, 4])
print(frozen_set) # Output: frozenset({1, 2, 3, 4})
# Attempting to modify a frozenset will raise an AttributeError
# frozen_set.add(5) # Raises AttributeError
👍2
Practice Exercises for Day 7
Exercise 1: Dictionary Manipulation
Exercise 2: Word Frequency
Exercise 3: Set Operations
Exercise 4: Unique Elements Finder
Exercise 5: Nested Dictionary
Exercise 1: Dictionary Manipulation
Create a dictionary with keys as names and values as marks. Add new entries, update marks, and delete a student entry.
Exercise 2: Word Frequency
Write a Python program to count the frequency of each word in a given sentence using a dictionary.
Exercise 3: Set Operations
Given two lists, create sets from them and perform union, intersection, difference, and symmetric difference operations.
Exercise 4: Unique Elements Finder
Write a Python program to find unique elements in a list using a set.
Exercise 5: Nested Dictionary
Create a nested dictionary to represent students' data, including their names, ages, and subjects. Write a program to print each student's details.
Homework for Day 7
Contact Book Program:
Set-Based Vowel Counter:
Dictionary Comprehensions:
Contact Book Program:
Write a Python program to create a contact book using a dictionary. The user should be able to add, delete, update, and search contacts.
Set-Based Vowel Counter:
Write a Python program to count the number of unique vowels in a given string using a set.
Dictionary Comprehensions:
Write a Python program to create a dictionary from a list of numbers where the keys are the numbers, and the values
What is a Function?
Syntax:
Example:
A function is a block of organized, reusable code that performs a single action or returns a value. Functions allow you to break down complex problems into smaller, manageable tasks.
Syntax:
def function_name(parameters):
# Function body
# Perform some action
return result
Example:
def greet():
print("Hello, World!")
greet() # Output: Hello, World!
Defining and Calling Functions
Defining a Function:
Calling a Function:
Example:
Defining a Function:
Use the def keyword followed by the function name and parentheses (). You can pass parameters inside the parentheses.
Calling a Function:
Simply use the function name followed by parentheses ().
Example:
def add(a, b):
return a + b
result = add(3, 5)
print(result) # Output: 8
Function Parameters and Arguments
- Parameters are variables defined in the function declaration.
- Arguments are the values passed to the function when it is called.
Types of Function Parameters:
1. Positional Arguments: Arguments passed to a function in a correct positional order.
2. Keyword Arguments: Arguments passed using the parameter name, making the order irrelevant.
3. Default Parameters: Parameters that have default values if no argument is provided during the function call.
4. Variable-Length Arguments: Allows passing a variable number of arguments (
Examples:
- Parameters are variables defined in the function declaration.
- Arguments are the values passed to the function when it is called.
Types of Function Parameters:
1. Positional Arguments: Arguments passed to a function in a correct positional order.
2. Keyword Arguments: Arguments passed using the parameter name, making the order irrelevant.
3. Default Parameters: Parameters that have default values if no argument is provided during the function call.
4. Variable-Length Arguments: Allows passing a variable number of arguments (
*args for non-keyword, **kwargs for keyword arguments).Examples:
def greet(name, message="Hello"):
print(f"{message}, {name}!")
greet("Alice") # Output: Hello, Alice!
greet("Bob", "Good Morning") # Output: Good Morning, Bob!
def display(*args):
print(args)
display(1, 2, 3) # Output: (1, 2, 3)
def show_details(**kwargs):
print(kwargs)
show_details(name="Alice", age=25) # Output: {'name': 'Alice', 'age': 25}
Return Statement
Example:
The return statement is used to exit a function and send back a value to the caller. If no return statement is used, the function returns None.
Example:
def multiply(x, y):
return x * y
result = multiply(4, 5)
print(result) # Output: 20
Scope and Lifetime of Variables
Local Scope: Variables declared inside a function, accessible only within that function.
Global Scope: Variables declared outside any function, accessible from anywhere in the program.
Example:
The scope of a variable determines the part of the program where the variable is accessible. Python has two main types of scope:
Local Scope: Variables declared inside a function, accessible only within that function.
Global Scope: Variables declared outside any function, accessible from anywhere in the program.
Example:
x = 10 # Global variable
def show():
y = 5 # Local variable
print(y)
show() # Output: 5
print(x) # Output: 10
# print(y) # Error: y is not defined
Recursion in Functions
Example: Factorial Calculation
A function that calls itself is known as a recursive function. Recursion is a common mathematical and programming concept that helps solve problems by breaking them down into simpler, smaller problems.
Example: Factorial Calculation
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
Lambda Functions
Syntax:
Example:
A lambda function is a small anonymous function defined using the lambda keyword. It can have any number of arguments but only one expression.
Syntax:
lambda arguments: expression
Example:
square = lambda x: x ** 2
print(square(4)) # Output: 16
add = lambda a, b: a + b
print(add(3, 5)) # Output: 8
Built-in Functions and
Python provides several built-in functions for various operations, including
Examples:
map(), filter(), and reduce()Python provides several built-in functions for various operations, including
len(), max(), min(), sum(), and more. Some useful built-in functions for working with lists and sequences:map(function, iterable): Applies a function to all items in an iterable.filter(function, iterable): Filters items in an iterable based on a condition.reduce(function, iterable): Reduces an iterable to a single value (requires functools module).Examples:
# Using map()
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x ** 2, numbers))
print(squares) # Output: [1, 4, 9, 16]
# Using filter()
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # Output: [2, 4]
# Using reduce()
from functools import reduce
product = reduce(lambda x, y: x * y, numbers)
print(product) # Output: 24
Function Annotations
Function annotations provide a way of attaching metadata to function arguments and return values. Annotations are optional and are stored in the function's __annotations__ attribute.
def add(a: int, b: int) -> int:
return a + b
print(add(3, 4)) # Output: 7
print(add.__annotations__) # Output: {'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
👍2
Practice Exercises for Day 8
Exercise 1: Basic Calculator
Exercise 2: Palindrome Checker
Exercise 3: Fibonacci Sequence Generator
Exercise 4: Find the Maximum of Three Numbers
Exercise 5: Character Frequency Counter
Exercise 1: Basic Calculator
Write a function calculator() that takes three arguments (two numbers and an operator) and returns the result of the operation.
Exercise 2: Palindrome Checker
Write a Python function that checks if a given string is a palindrome (reads the same backward as forward).
Exercise 3: Fibonacci Sequence Generator
Write a recursive function to generate the Fibonacci sequence up to n terms.
Exercise 4: Find the Maximum of Three Numbers
Write a Python function that takes three numbers and returns the maximum of the three.
Exercise 5: Character Frequency Counter
Write a Python function that takes a string as input and returns a dictionary with the frequency of each character.
Homework for Day 8
Factorial Using Iteration:
Lambda and map():
Prime Number Checker:
Flatten a List:
Higher-Order Functions:
Factorial Using Iteration:
Write a Python program to find the factorial of a number using an iterative function instead of recursion.
Lambda and map():
Write a Python program to use map() with a lambda function to convert a list of temperatures from Celsius to Fahrenheit.
Prime Number Checker:
Write a Python function to check if a given number is a prime number.
Flatten a List:
Write a Python function to flatten a nested list using recursion.
Higher-Order Functions:
Write a Python function that takes another function as an argument and applies it to every element in a list.
Summary
Today, we covered the core concepts of functions in Python, including:
Defining, calling, and using functions for code organization and reusability.
Different types of parameters (
The importance of the
Understanding recursion, lambda functions, and built-in functions like
Function annotations for attaching metadata to functions.
Today, we covered the core concepts of functions in Python, including:
Defining, calling, and using functions for code organization and reusability.
Different types of parameters (
positional, keyword, default, *args, **kwargs) and how to use them.The importance of the
return statement and variable scope.Understanding recursion, lambda functions, and built-in functions like
map(), filter(), and reduce().Function annotations for attaching metadata to functions.
👍2
What is a Module?
Example of a module (
Importing a Module
Example:
Example:
A module in Python is simply a file containing Python definitions and statements. A module can define functions, classes, and variables. It can also include runnable code.
By organizing your code into modules, you can keep related code together and reuse it across multiple programs.
Example of a module (
greetings.py):# greetings.py
def hello(name):
print(f"Hello, {name}!")
def goodbye(name):
print(f"Goodbye, {name}!")
Importing a Module
To use a module in another Python program, you need to import it using the import keyword.
Example:
import greetings
greetings.hello("Alice") # Output: Hello, Alice!
greetings.goodbye("Bob") # Output: Goodbye, Bob!
You can also import specific functions or variables from a module using from.
Example:
from greetings import hello
hello("Alice") # Output: Hello, Alice!
❤1
Standard Library Modules
Here are some common modules from the standard library:
Example: Using the
Example: Using the
Python comes with a large standard library of modules that you can use without needing to install them. The standard library includes modules for various tasks such as working with files, handling dates and times, performing mathematical operations, and much more.
Here are some common modules from the standard library:
math: Provides mathematical functions like sin(), cos(), sqrt(), etc.datetime: Provides functions for working with dates and times.random: Contains functions to generate random numbers and selections.os: Provides a way of using operating system-dependent functionality.Example: Using the
math moduleimport math
result = math.sqrt(16)
print(result) # Output: 4.0
Example: Using the
datetime modulefrom datetime import datetime
current_time = datetime.now()
print(current_time) # Output: 2024-09-12 10:23:00 (example output)