Free Python Course | Programming Tutorials
599 subscribers
9 photos
2 files
6 links
Join Noob to Pro in Python in 100 Days! πŸš€ Learn Python with daily lessons, practical examples, free code samples, exercises, and homework. Ideal for beginners and those looking to advance their skills. Start your journey to becoming a Python pro! 🐍
Download Telegram
Recursion in Functions
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
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 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

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:

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 (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?
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
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 module
import math

result = math.sqrt(16)
print(result) # Output: 4.0

Example: Using the datetime module
from datetime import datetime

current_time = datetime.now()
print(current_time) # Output: 2024-09-12 10:23:00 (example output)
Creating Your Own Modules
You can easily create your own modules. All you need to do is save your Python code in a .py file. Later, you can import and use this module in other programs.


Example:
1. Create a file math_tools.py:
def add(a, b):
return a + b

def subtract(a, b):
return a - b

2. In another Python file, import and use it:
import math_tools

print(math_tools.add(3, 5)) # Output: 8
print(math_tools.subtract(10, 4)) # Output: 6
πŸ‘1
Exploring the import Statement
Importing with Aliases: You can give an alias to a module or function while importing it to simplify the code or avoid naming conflicts.


Example:
import math as m

print(m.sqrt(25)) # Output: 5.0

Importing All Names from a Module: You can use the * symbol to import everything from a module

Example:
from math import *

print(sqrt(9)) # Output: 3.0

However, importing everything this way is discouraged as it can lead to confusion if you have multiple imports with the same function names.
Python Packages
A package is a collection of related modules. A package is just a directory that contains multiple Python files (modules) and an __init__.py file. The __init__.py file makes the directory a Python package.


Package Structure Example:
math_package/
__init__.py
basic_operations.py
advanced_operations.py

__init__.py: This file can be empty or contain initialization code for the package.

Modules (basic_operations.py, advanced_operations.py): The Python files inside the package contain your functions or classes.


Creating and Using a Package
1. Directory Structure:
my_package/
__init__.py
utilities.py

2. utilities.py:
def greet(name):
return f"Hello, {name}!"

3. Main Python file:
from my_package import utilities

print(utilities.greet("Alice")) # Output: Hello, Alice!
πŸ‘1
Installing External Packages with pip
The Python ecosystem is rich with third-party libraries that you can install using pip, Python’s package installer. You can install, update, and remove external packages from your system using pip.

To install a package, use the command:
pip install package_name


Example:
pip install requests


Once installed, you can import and use the package:
import requests

response = requests.get("https://api.github.com")
print(response.status_code) # Output: 200


You can find packages on the Python Package Index (PyPI) at https://pypi.org.
The dir() and help() Functions
dir(): This function lists all the names (functions, variables, etc.) defined in a module.
help(): This function provides documentation for a module, function, class, etc.

Example:
import math

print(dir(math)) # Lists all functions and constants in the math module
help(math.sqrt) # Provides documentation for the sqrt function
Practice Exercises for Day 9

Exercise 1: Create a Simple Module

Create a module called temperature.py that contains two functions: celsius_to_fahrenheit() and fahrenheit_to_celsius(). Import this module and use it in another program to convert temperatures.

Exercise 2: Using Standard Library Modules
Write a Python program that calculates the area of a circle using the math module.

Exercise 3: Directory Operations with the os Module
Write a Python script that uses the os module to list all files in the current directory and create a new directory called "TestFolder".

Exercise 4: Custom Package
Create a package called math_operations with two modules: basic.py and advanced.py. In basic.py, create functions for basic arithmetic operations (add, subtract, multiply, divide), and in advanced.py, create functions for operations like exponentiation and square root. Write a script that uses this package.

Exercise 5: Exploring random Module
Write a Python program to generate a random password of 8 characters using the random module.
πŸ‘1
Summary

In Day 9, we explored the following topics:
Modules: Files containing Python code that can be imported and reused.
Standard Library Modules: Common built-in modules like math, datetime, os, and random.
Packages: Directories containing multiple related modules, which allow for better organization of your code.
pip: Python’s package installer for managing third-party libraries.
dir() and help(): Useful functions for exploring modules and getting documentation.

Modules and packages are essential to writing maintainable Python code and help you tap into Python’s vast ecosystem of libraries and tools. With these skills, you’ll be able to write modular and reusable code that scales well as your projects grow
πŸ‘2
Introduction to File Handling
Python provides built-in functions to work with files. The most common operations include:
Opening a file: open()
Reading from a file:
read(), readline(), readlines()
Writing to a file:
write(), writelines()
Closing a file:
close()

Syntax:
file = open("filename", "mode")

The mode defines how the file will be opened:
'r': Read (default mode, raises an error if the file does not exist)
'w': Write (creates a new file if it does not exist, overwrites existing content)
'a': Append (creates a new file if it does not exist, appends to existing content)
'x': Create (creates a new file, raises an error if the file exists)
'b': Binary mode (e.g., 'rb' for reading binary files)
't': Text mode (default mode, used for reading/writing text files)
πŸ‘2
Opening and Closing Files
Opening a File

To open a file, use the open() function.

Example:
file = open("example.txt", "r")

This will open the file example.txt in read mode ('r').

Closing a File
It’s good practice to close a file after you are done with it using the close() method. This frees up system resources.
file.close()

Alternatively, you can use the with statement to automatically close the file after the block of code is executed.

Example:
with open("example.txt", "r") as file:
content = file.read()
print(content) # File is automatically closed after the block
πŸ‘2
Reading from a File
Python provides several methods to read the contents of a file.
read() Method
Reads the entire content of a file as a single string.

Example:
with open("example.txt", "r") as file:
content = file.read()
print(content) # Prints the entire file content


readline() Method
Reads one line at a time from the file.

Example:
with open("example.txt", "r") as file:
line = file.readline()
print(line) # Prints the first line of the file


readlines() Method
Reads all lines of a file and returns them as a list of strings.

Example:
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines) # Prints all lines in a list
πŸ‘2❀1
Writing to a File
To write content to a file, you can use the write() or writelines() methods. Opening a file in write ('w') mode will create the file if it doesn’t exist or overwrite it if it does.

write() Method
The write() method writes a string to the file.
Example:
with open("output.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is a Python program.\n")


writelines() Method
The writelines() method takes a list of strings and writes them to the file.
Example:
lines = ["First line\n", "Second line\n", "Third line\n"]

with open("output.txt", "w") as file:
file.writelines(lines)
πŸ‘3❀1