Python Notes ?
Python Notes ?
com
Python For Beginner
● What is Python?
Python is a high-level, interpreted programming language known for its
simplicity and readability. It is widely used in web development, data
analysis, machine learning, automation, and more.
● Why Learn Python?
○ Beginner-friendly syntax
○ Extensive libraries and frameworks
○ Strong community support
○ Versatile for various applications
On Windows
● Download Python
○ Visit python.org and download the Windows installer.
○ Choose the appropriate version (32-bit or 64-bit) based on your
system.
● Install Python
○ Run the installer.
○ Check the box "Add Python to PATH" to make Python accessible
from the Command Prompt.
○ Choose Customize Installation for optional features like pip, IDLE,
and development tools.
○ Complete the installation process.
● Verify Installation
visit: www.thelearnnova.com
○ Open Command Prompt.
Run:
python --version
pip --version
On Linux
● Install Python
For Debian/Ubuntu:
sudo apt install python3 python3-pip -y
Verify Installation
python3 --version
pip3 --version
2. Choose an Editor
Recommended Editors for Both Linux and Windows
visit: www.thelearnnova.com
○ Install the Python Extension for debugging, syntax highlighting, and
more.
● PyCharm
○ Download from jetbrains.com/pycharm.
○ Offers a free Community Edition.
● Jupyter Notebook
Launch:
jupyter notebook
pip --version
On Linux
visit: www.thelearnnova.com
pip3 --version
Deactivate with:
deactivate
On Linux
Deactivate with:
deactivate
visit: www.thelearnnova.com
Use pip to install Python libraries.
Example Commands
Install libraries:
pip install numpy pandas matplotlib
Upgrade pip:
python -m pip install --upgrade pip # Windows
6. Additional Tips
● Linux Users
○ Use a package manager like apt or yum to install Python
dependencies.
● Windows Users
○ Use PowerShell or Command Prompt for Python commands.
○ Use Windows Subsystem for Linux (WSL) for a Linux-like
development environment.
visit: www.thelearnnova.com
Basic Syntax
Hello World
print("Hello, World!")
Python Comments
Single-line Comments
Comments in Python begin with a # symbol, and Python will ignore everything
following the # on that line:
# This is a comment
print("Hello, World!")
Inline Comments
Comments can also be placed at the end of a line, and Python will ignore the rest of the
line:
print("Hello, World!") # This is a comment
Multiline Comments
visit: www.thelearnnova.com
# This is a comment
# written in
print("Hello, World!")
"""
This is a comment
written in
"""
print("Hello, World!")
visit: www.thelearnnova.com
1. Operators
Arithmetic Operators
These operators perform mathematical operations like addition, subtraction, etc.
● + : Addition
● - : Subtraction
● * : Multiplication
● / : Division
● % : Modulus (remainder of division)
● // : Floor division (returns the integer part of the division)
● ** : Exponentiation (raising to a power)
Example:
a = 10
b=5
print(a + b) # Output: 15
print(a - b) # Output: 5
Comparison Operators
These operators compare two values and return True or False.
● == : Equal to
● != : Not equal to
● > : Greater than
● < : Less than
● >= : Greater than or equal to
● <= : Less than or equal to
visit: www.thelearnnova.com
Logical Operators
These operators are used to combine conditional statements.
In Python, variables are used to store data. You can think of a variable as a box
where you store something (like a number or a name). Data types tell Python what
kind of data you're storing.
x=5 # Integer
y = 3.14 # Float
name = "Alice" # String
is_active = True # Boolean
3. Lists:
A list is like a collection of items. You can store multiple items in a list, and each
item can be accessed by its position (index). Lists are very flexible and allow you
to change, add, or remove items.
visit: www.thelearnnova.com
Output: ['apple', 'banana', 'cherry', 'orange']
Lists are one of the most important data structures in Python. You can perform
various operations on them.
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4]) # Output: [2, 3, 4]
numbers = [5, 2, 9, 1]
numbers.sort() # Sorting the list in ascending order
print(numbers) # Output: [1, 2, 5, 9]
4. Tuples:
A tuple is similar to a list but with one important difference: it is immutable. This
means that once you create a tuple, you cannot change, add, or remove elements
visit: www.thelearnnova.com
from it. Tuples are useful when you want to store a collection of values that should
not be modified, like the coordinates of a point or days of the week.
Creating a Tuple
Tuples are defined using parentheses (), and they can contain elements of different
data types (e.g., integers, strings, booleans).
# Creating a tuple
my_tuple = (1, 2, 3, "apple", True)
print(my_tuple) # Output: (1, 2, 3, 'apple', True)
Tuple Immutability
Since tuples are immutable, you cannot change their values after creation. Trying
to do so will raise an error.
To create a tuple with just one element, you need to add a trailing comma.
✅
❌
single_tuple = (5,) # Correct
not_a_tuple = (5) # This is just an integer
print(type(single_tuple)) # Output: <class 'tuple'>
print(type(not_a_tuple)) # Output: <class 'int'>
visit: www.thelearnnova.com
5. Dictionaries:
6. Conditional Statements:
Conditional statements let you check if something is true or false and then take
different actions based on that. It's like asking a question: "Is this true?" If yes, do
one thing; if no, do something else.
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
7. Loops:
● For Loop: You use a for loop when you know how many times you want to
repeat something.
for i in range(5):
print(i) # Output: 0, 1, 2, 3, 4
visit: www.thelearnnova.com
● While Loop: You use a while loop when you want to repeat something until
a certain condition is met.
count = 0
while count < 5:
print(count)
count += 1 # Output: 0, 1, 2, 3, 4
8. Functions:
A function is a block of code that does something. You can define your own
functions to organize your code and reuse it. Functions help make your code
cleaner and more efficient.
def greet(name):
return "Hello, " + name
def square(x):
return x * x
print(square(4)) # Output: 1
In Python, you can create your own types using classes. A class is like a blueprint
for creating objects. An object is an instance of a class. Classes allow you to group
related data and functions together.
visit: www.thelearnnova.com
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name} and I am {self.age} years old."
Python comes with a lot of built-in libraries (also called modules) that help you do
common tasks. You can import these libraries into your code to use their
functionality.
import math
print(math.sqrt(16)) # Output: 4.0
def fib(n):
a, b = 0, 1
while a < n:
a, b = b, a + b
print()
visit: www.thelearnnova.com
fib(1000)
Output:
def fib(n):
a, b = 0, 1
sequence = []
while a < n:
sequence.append(a)
a, b = b, a + b
return sequence
max_price = 1000
retracement_levels = fib(max_price)
Output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]
visit: www.thelearnnova.com
When to Buy & Sell?
📌 Buy: When the price retraces to 61.8%, 50%, or 38.2% and bounces up.
📌 Sell: When the price rises to 38.2%, 50%, or 61.8% and struggles to go
higher.
38.2%
● 50%
● 61.8%
● 78.6%
These levels are calculated by dividing each number in the Fibonacci sequence by
the number two places ahead of it. For example:
Strings are used to handle text data. You can perform several operations on strings.
greeting = "Hello"
name = "Alice"
visit: www.thelearnnova.com
message = greeting + ", " + name
print(message) # Output: Hello, Alice
● String Methods:
name = "Alice"
age = 25
message = f"My name is {name} and I am {age} years old."
print(message) # Output: My name is Alice and I am 25 years old.
Exceptions are errors that occur during program execution. Python provides a way
to handle these errors gracefully using try, except.
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
● Else and Finally: You can also add else and finally blocks.
try:
x = 10 / 2
visit: www.thelearnnova.com
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful!")
finally:
print("This will always run.")
Lambda functions are small anonymous functions defined using the lambda
keyword.
# Regular function
def add(x, y):
return x + y
# Lambda function
add_lambda = lambda x, y: x + y
print(add_lambda(2, 3)) # Output: 5
Lambda functions are often used in places where you need a simple function for a
short period, like in map(), filter(), or sorted().
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16]
visit: www.thelearnnova.com
numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4]
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product) # Output: 24
Sometimes, you may need to read from or write to files. Python allows you to
easily open, read, and write files.
● Writing to a file:
visit: www.thelearnnova.com
● Reading Large Files: Instead of reading the entire file into memory, you
can read it line by line.
What is Regex?
Regular Expressions (Regex) are patterns used to search for specific text in a
string. It helps find, validate, and modify text efficiently.
🔹 Example:
● Searching for a phone number in a document
● Checking if an email address is valid
● Replacing spaces with underscores in a sentence
Python provides a built-in module called re for working with regular expressions.
visit: www.thelearnnova.com
import re # Import the regex module
import re
if match:
print("Found 'Python' in the text!")
✅ Explanation:
● re.search(pattern, text) → Searches for "Python" in the text.
● If found, it prints "Found 'Python' in the text!".
import re
if match:
print("Found number:", match.group()) # Output: 42
✅ Explanation:
visit: www.thelearnnova.com
● \d+ → Matches one or more digits (e.g., 42).
● match.group() → Returns the found number.
email = "[email protected]"
pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
if re.match(pattern, email):
print("Valid email!")
else:
print("Invalid email!")
✅ Explanation:
● ^ → Start of the string
● [a-zA-Z0-9_.+-]+ → Letters, numbers, and some special characters
● @ → Must contain @
● [a-zA-Z0-9-]+ → Domain name (e.g., example)
● \.[a-zA-Z0-9-.]+$ → Ends with .com, .org, etc.
if date:
print("Found date:", date.group()) # Output: 15/08/2025
visit: www.thelearnnova.com
✅ Explanation:
● \d{2}/\d{2}/\d{4} → Finds a date in dd/mm/yyyy format.
if re.match(pattern, phone_number):
print("Valid phone number!")
else:
print("Invalid phone number!")
✅ Explanation:
● \(\d{3}\) → Matches (123).
● \d{3}-\d{4} → Matches 456-7890.
✅ Explanation:
● \s → Matches spaces.
● re.sub(pattern, replacement, text) → Replaces spaces with underscores.
visit: www.thelearnnova.com
Extracting a Website URL from Text
import re
if url:
print("Found URL:", url.group()) # Output: https://www.example.com
✅ Explanation:
● https?:// → Matches http:// or https://.
● [a-zA-Z0-9./]+ → Matches the rest of the URL.
✅ Explanation:
● re.split() → Splits text based on commas and spaces.
visit: www.thelearnnova.com
import re
✅ Explanation:
● \d+ → Finds all numbers in the text.
● re.findall() → Returns a list of all matches.
import re
✅ Explanation:
● \b → Matches word boundaries (start of a word).
● [Aa] → Matches uppercase or lowercase "A".
● \w+ → Matches the rest of the word.
visit: www.thelearnnova.com
● At least 8 characters
● At least one uppercase letter
● At least one lowercase letter
● At least one number
● At least one special character
import re
password = "Secure@123"
pattern =
r"^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"
if re.match(pattern, password):
print("Strong password!")
else:
print("Weak password! Try adding uppercase, lowercase, numbers, and special
characters.")
✅ Explanation:
● (?=.*[A-Z]) → At least one uppercase letter
● (?=.*[a-z]) → At least one lowercase letter
● (?=.*\d) → At least one digit
● (?=.*[@$!%*?&]) → At least one special character
● {8,} → At least 8 characters long
import re
visit: www.thelearnnova.com
print("Words:", words)
# Output: ['Python', 'is', 'fun', 'Let', 's', 'learn', 'regex', 'together']
✅ Explanation:
● \b → Word boundary (start and end of a word)
● \w+ → One or more word characters (letters, numbers, underscore)
import re
✅ Explanation:
● Looks for text with @ and a valid domain.
visit: www.thelearnnova.com
# Output: ['#Python', '#Regex', '#Coding']
✅ Explanation:
● #\w+ → Finds words starting with #.
✅ Explanation:
● \b[A-Z][a-z]*\b → Finds words that start with a capital letter.
import re
print(cleaned_text)
# Output: "Python is awesome!"
visit: www.thelearnnova.com
✅ Explanation:
● \s+ → Matches one or more spaces.
✅ Explanation:
● \d+ → Finds all numbers.
✅ Explanation:
● \b[Tt]\w+ → Finds words that start with "T" or "t".
visit: www.thelearnnova.com
Checking if a String Contains Only Letters and Numbers
import re
text = "Python123"
if re.fullmatch(r"[A-Za-z0-9]+", text):
print("Valid input (letters and numbers only)")
else:
print("Invalid input!")
✅ Explanation:
● re.fullmatch() → Checks if the entire string matches the pattern.
● [A-Za-z0-9]+ → Allows only letters and numbers.
Python has a built-in module datetime to work with dates and times.
visit: www.thelearnnova.com
# Format date and time
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted) # Output: 2025-01-25 14:30:45
Modules are Python files containing code that you can import and use in your
programs. Packages are collections of modules.
● Importing a Module:
import math
print(math.sqrt(16)) # Output: 4.0
def greet(name):
return f"Hello, {name}!"
import mymodule
print(mymodule.greet("Alice")) # Output: Hello, Alice!
visit: www.thelearnnova.com
OOP is a way of writing programs where we create objects that represent
real-world things.
Think of a car:
class Car:
# Class attribute (shared by all cars)
wheels = 4
# Method (action)
def display_info(self):
print(f"{self.brand} {self.model} has {self.wheels} wheels.")
visit: www.thelearnnova.com
ii ) Object: A Real Example of a Class
# Calling a method
my_car.display_info()
Output:
Methods are functions inside a class that define what an object can do.
visit: www.thelearnnova.com
Example: A Dog That Can Bark
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print(f"{self.name} says Woof!")
Output:
Inheritance allows one class (child class) to reuse the attributes and methods of
another class (parent class).
class Animal:
def speak(self):
print("Animal speaks")
visit: www.thelearnnova.com
def speak(self):
print("Dog barks")
dog = Dog()
dog.speak() # Calls Dog's speak method
Output:
Dog barks
✔ The Dog class gets its behavior from the Animal class.
Encapsulation hides internal data and allows access only through specific methods.
In this example, we'll create a Car class that has a private attribute for speed, and
we'll use methods to control the speed of the car.
class Car:
if increment > 0:
self.__speed += increment
visit: www.thelearnnova.com
def brake(self, decrement):
self.__speed -= decrement
def get_speed(self):
return self.__speed
def get_brand(self):
return self.__brand
Explanation:
visit: www.thelearnnova.com
○ get_brand(self): This method allows you to access the brand of the
car.
my_car = Car("Toyota", 50) # Create a Car object with brand "Toyota" and speed
50
print(my_car.get_speed()) # Output: 50
print(my_car.get_speed()) # Output: 80
print(my_car.get_speed()) # Output: 60
Output:
50
80
60
Key Points:
● Private Data (__speed, __brand): The speed and brand are private,
meaning they can't be changed directly from outside the class. This ensures
that the internal state of the car is protected.
● Methods for Controlled Access:
visit: www.thelearnnova.com
○ accelerate() and brake() methods control how the speed changes,
ensuring that the speed doesn't go below zero and that it only
increases when requested.
○ get_speed() and get_brand() provide a way to safely access the car's
data.
● The internal data (like the car's speed and brand) is hidden inside the
object and can only be accessed or modified through methods like
accelerate, brake, and get_speed.
● This ensures that the car’s state is always valid (e.g., speed cannot go below
zero), and any changes to the car’s data are controlled and safe.
Polymorphism allows different classes to have methods with the same name but
different behaviors.
class Dog:
def speak(self):
print("Woof")
visit: www.thelearnnova.com
Output:
Meow
Woof
✔ Both Cat and Dog have a speak() method, but they behave differently.
class Dog(Animal):
def speak(self):
print("Woof")
dog = Dog()
dog.speak()
Output:
Woof
✔ The Animal class only defines speak(), but doesn’t implement it.
✔ The Dog class must define speak().
visit: www.thelearnnova.com
Summary of OOP Concepts in Python
def decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
visit: www.thelearnnova.com
@decorator
def say_hello():
print("Hello!")
say_hello()
Output:
Output
Before function call
Hello!
After function call
visit: www.thelearnnova.com
● Reusability: Add the same behavior (e.g., logging, authentication) to
multiple functions without repeating code.
● Clean Code: Keep the original function's logic separate from additional
functionality.
● Flexibility: Apply or remove behaviors easily by adding or removing
decorators.
Iterator:
● An iterator is like a tool that helps you go through items in a collection (like
a list or a tuple) one by one.
● It keeps track of where it is in the collection.
● You can create an iterator from a collection using the iter() function.
● To get the next item, you use the next() function. When there are no more
items, next() will stop the iteration and raise a StopIteration error.
Example:
numbers = [1, 2, 3]
iterator = iter(numbers)
print(next(iterator)) # Output: 1
Generator:
Example:
visit: www.thelearnnova.com
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
counter = count_up_to(3)
for num in counter:
print(num) # Output: 1, 2, 3
Key Differences:
● Memory Efficient: Generators don’t store all the values at once. They
generate each value only when needed.
● Great for Large Datasets: They’re useful when working with large
amounts of data or infinite sequences because they don’t take up a lot of
memory.
List and dictionary comprehensions are powerful tools for creating and
transforming data structures in a concise way.
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
visit: www.thelearnnova.com
print(squares) # Output: [1, 4, 9, 16, 25]
24. Enumerate:
enumerate() is a built-in function that allows you to loop over an iterable and get
both the index and the value.
25. Zip:
zip() is a built-in function that combines multiple iterables (like lists or tuples) into
a single iterable of tuples.
visit: www.thelearnnova.com
scores = [85, 90, 95]
combined = zip(names, scores)
print(list(combined)) # Output: [('Alice', 85), ('Bob', 90), ('Charlie', 95)]
Sets are unordered collections of unique elements. You can perform mathematical
operations like union, intersection, and difference on sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
print(union_set) # Output: {1, 2, 3, 4, 5}
● Difference: Finds elements in the first set that are not in the second.
Sometimes, you need to pause your program for a specific amount of time. You can
do this using time.sleep().
visit: www.thelearnnova.com
import time
print("Starting...")
time.sleep(2) # Waits for 2 seconds
print("2 seconds later...")
Context managers are used to set up and tear down resources automatically. The
with statement is commonly used for managing files, database connections, and
more.
29. Multi-threading:
Python allows you to run multiple threads (tasks) concurrently. This is useful for
I/O-bound tasks.
import threading
def print_numbers():
for i in range(5):
print(i)
visit: www.thelearnnova.com
# Start the threads
thread1.start()
thread2.start()
i. Web Scraping
● Scenario: Downloading multiple files from the internet at the same time.
● Why Multi-threading: File downloads are typically I/O-bound tasks.
Running multiple threads allows you to download files concurrently,
reducing the total time required.
● Example: Downloading multiple files from different servers or URLs
concurrently.
visit: www.thelearnnova.com
● Scenario: Processing large datasets or performing computationally
expensive tasks (e.g., image processing, video encoding).
● Why Multi-threading: If the task involves multiple independent operations
(e.g., processing different chunks of data), threads can be used to handle
these tasks concurrently, speeding up the process.
● Example: Processing multiple images or videos at the same time using
separate threads.
v. Real-time Applications
visit: www.thelearnnova.com
● Scenario: Running background tasks while the main application continues
to run.
● Why Multi-threading: Some tasks, like periodic data syncing, logging, or
monitoring, can be handled in the background while the main application
remains responsive.
● Example: A chat application that runs background tasks (like checking for
new messages) in a separate thread while the user interacts with the UI.
visit: www.thelearnnova.com
● Why Multi-threading: Each user query can be processed in a separate
thread, allowing the assistant to handle multiple conversations at the same
time without blocking.
● Example: A chatbot that responds to user queries concurrently in a
multi-threaded environment.
What is a Decorator?
Decorators can also accept arguments (like regular functions do). This makes
them even more powerful and flexible because you can customize their behavior
based on the values you pass to them.
visit: www.thelearnnova.com
Imagine you have a function that says "Hello", but you want it to say "Hello"
multiple times. Instead of writing the same code over and over, you can use a
decorator to repeat it for you.
You can create decorators that accept arguments to make them more flexible.
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
# Output:
# Hello, Alice!
# Hello, Alice!
# Hello, Alice!
1. repeat(n): This is the main decorator. It takes an argument n (the number of
times you want the function to repeat).
2. decorator(func): This function takes the original function greet and wraps it
with additional behavior.
3. wrapper(*args, **kwargs): This is the function that actually does the
repeating. It runs the original function greet n times.
visit: www.thelearnnova.com
4. @repeat(3): This is the decorator syntax. It means "decorate the greet
function with the repeat decorator, repeating it 3 times."
Output:
Hello, Alice!
Hello, Alice!
Hello, Alice!
Using decorators with arguments gives you flexibility. You can customize how the
decorator behaves by passing different values. For example, you can make the
decorator repeat the function 5 times, 10 times, or just once, depending on what
you need.
import json
Output:
json
visit: www.thelearnnova.com
Convert JSON to Python objects:
Output:
import csv
['name', 'age']
['Alice', '25']
['Bob', '30']
visit: www.thelearnnova.com
import csv
name,age
Alice,25
Bob,30
Pandas is a powerful library for working with large datasets in a table-like structure
called DataFrame.
import pandas as pd
# Create a DataFrame
data = {"name": ["Alice", "Bob", "Charlie"], "age": [25, 30, 35]}
df = pd.DataFrame(data)
visit: www.thelearnnova.com
Output:
markdown
name age
0 Alice 25
1 Bob 30
2 Charlie 35
0 Alice
1 Bob
2 Charlie
Name: name, dtype: object
name age
2 Charlie 35
SQLite is a simple, file-based database. Python's sqlite3 module lets you interact
with SQLite databases.
import sqlite3
# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER
PRIMARY KEY, name TEXT, age INTEGER)''')
visit: www.thelearnnova.com
# Query data from the table
cursor.execute('''SELECT * FROM users''')
print(cursor.fetchall()) # Output: [(1, 'Alice', 25)]
Output:
The requests library makes it easy to send HTTP requests (like GET, POST) and
work with the responses.
When you want to interact with an API, you send an HTTP request (like GET,
POST) to a server, and it responds with data.
GET Request:
A GET request is used to fetch data from a server. It's like asking a server, "Please
send me this information."
Code Explanation:
import requests
visit: www.thelearnnova.com
This line imports the requests library, which makes it easy to send HTTP requests.
response = requests.get("https://api.github.com")
Here, we're sending a GET request to the GitHub API. The URL
"https://api.github.com" is the address of the GitHub API that provides information
about the current status of GitHub.
print(response.status_code)
After sending the GET request, the server responds. The status_code tells us
whether the request was successful. A 200 status code means "OK" (the request
was successful).
Output:
200
print(response.json())
The .json() method converts the response from the server into a Python dictionary.
The data returned by the server is usually in JSON format, which is a way of
structuring data that is easy to read and write for both humans and machines.
Output:
json
{
"current_user_url": "https://api.github.com/user",
"current_user_authorizations_html_url":
"https://github.com/settings/connections/applications{/client_id}",
...
}
visit: www.thelearnnova.com
This is the data returned by the GitHub API. It contains links and information
about the current user, such as the URL to access the current user's details.
POST Request:
A POST request is used to send data to a server. It's like saying, "Here's some
data, please save it or process it."
Code Explanation:
data = {"name": "Alice", "age": 25}
Here, we create a dictionary data that contains the information we want to send to
the server. In this case, it's a simple dictionary with a person's name and age.
print(response.status_code)
After the POST request is made, the server responds again. The status_code tells us
if the request was successful. A 201 status code means "Created," which typically
indicates that the data was successfully created or saved.
Output:
201
Summary:
visit: www.thelearnnova.com
● GET request: Used to fetch data from a server. The server sends back
information, and you can read it.
● POST request: Used to send data to a server. The server processes the data
and responds.
The requests library simplifies the process of interacting with APIs in Python. You
can use it to both fetch and send data to web services, which is an essential part of
working with modern web applications.
i) What is BeautifulSoup?
BeautifulSoup is a Python library that makes it easy to extract data from HTML
and XML documents. It's especially useful for web scraping, where you want to
retrieve data from websites.
Web scraping involves fetching the HTML content of a webpage and then parsing
it to extract useful information. BeautifulSoup helps you navigate and search
through the HTML structure in a readable way.
● from bs4 import BeautifulSoup: This imports the BeautifulSoup class from
the bs4 module, which is the library used for parsing HTML.
● import requests: This imports the requests module, which is used to send
HTTP requests to fetch the content of a webpage.
response = requests.get("https://example.com")
visit: www.thelearnnova.com
soup = BeautifulSoup(response.text, 'html.parser')
● soup.find_all('a'): This searches the HTML content for all <a> tags, which
are used to define hyperlinks.
● link.get('href'): For each <a> tag found, this retrieves the value of the href
attribute, which contains the URL of the link.
● print(link.get('href')): This prints each URL (or link) found on the page.
Output:
https://www.example.com/page1
https://www.example.com/page2
visit: www.thelearnnova.com
● HTML Tags: HTML pages are structured with tags like <a>, <div>, <p>,
etc. These tags define the content and structure of the page.
● requests Module: This is used to fetch content from the web.
● BeautifulSoup: This is used to parse the fetched HTML content and extract
useful information from it.
● Navigating HTML: Using methods like find_all() allows you to search for
specific tags and attributes in the HTML.
Summary:
37. Multiprocessing
Example:
visit: www.thelearnnova.com
process.start()
The asyncio module allows you to write code that can perform tasks while waiting
for something else to finish (like reading a file or making a network request). This
makes your program more efficient because it can do other work instead of
waiting.
Example:
import asyncio
# Asynchronous function that sleeps for 1 second and then prints a message
async def greet():
await asyncio.sleep(1)
print("Hello, Async!")
visit: www.thelearnnova.com
● asyncio.run(greet()) runs the asynchronous function.
Custom exceptions allow you to create your own error types that are specific to
your program. This helps make error handling more meaningful and easier to
manage.
Example:
YAML is a simple format for storing data, often used for configuration files. You
can use the PyYAML library to read and write YAML files in Python.
Example:
visit: www.thelearnnova.com
import yaml
Type hinting in Python helps make your code easier to understand by showing
what types of values variables and function arguments should have. It can also help
catch errors when using tools like mypy.
Example:
visit: www.thelearnnova.com
43. ConfigParser
The configparser module is used to work with .ini configuration files, which store
settings for your program. You can read, write, and modify these files using this
module.
Example:
import configparser
The argparse module helps you create command-line tools that accept arguments
from the user. This is useful for building programs that can be run from the
terminal with different options.
visit: www.thelearnnova.com
The argparse module helps you create programs that can accept input directly from
the terminal (or command line). This is useful when you want your program to be
flexible and run with different options.
Example:
import argparse
Explanation:
How to Use:
When you run the program, you can provide your name like this:
visit: www.thelearnnova.com
python your_program.py --name John
Hello, John!
In this example, --name is the argument, and John is the value that the program
uses to print the greeting.
F-strings, introduced in Python 3.6, are a way to embed expressions inside string
literals, making string formatting simpler and more readable. They allow you to
directly insert variables or expressions inside a string without needing to
concatenate or use formatting methods like .format() or %.
Basic Syntax:
The syntax for an f-string is to prefix the string with the letter f or F and use curly
braces {} to insert variables or expressions directly inside the string.
name = "Alice"
visit: www.thelearnnova.com
age = 25
Output:
Here, name and age are variables, and inside the f-string, we can directly reference
them. We can also perform calculations inside the curly braces, such as age + 5.
You can include any valid Python expression inside the curly braces.
width = 5
height = 10
Output:
F-strings also allow you to format numbers, dates, or other data types directly
inside the string.
pi = 3.14159
visit: www.thelearnnova.com
# Format pi to 2 decimal places
Output:
In this case, :.2f is a formatting specifier that rounds the number to two decimal
places.
Advantages of F-strings:
F-strings are an essential feature for anyone learning Python, as they make string
manipulation more intuitive and efficient.
visit: www.thelearnnova.com
Our students have gone on to work at renowned companies,
innovative startups, and leading unicorns.
Crack Project
Job
Top
MNC’s
Updates
Courses Blogs
E - Books
www.thelearnnova.com Follow us -