PYTHON notes by devaraj | PDF | Python (Programming Language) | Boolean Data Type
100% found this document useful (1 vote)
38 views

PYTHON notes by devaraj

The document is a comprehensive guide to Python programming, covering topics such as installation, basic syntax, data types, control flow, functions, data structures, object-oriented programming, modules, and best practices. It includes practical examples and explanations for each topic, making it suitable for beginners. The content is structured in a way that facilitates learning and understanding of Python programming concepts.

Uploaded by

quickclicksad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
38 views

PYTHON notes by devaraj

The document is a comprehensive guide to Python programming, covering topics such as installation, basic syntax, data types, control flow, functions, data structures, object-oriented programming, modules, and best practices. It includes practical examples and explanations for each topic, making it suitable for beginners. The content is structured in a way that facilitates learning and understanding of Python programming concepts.

Uploaded by

quickclicksad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

DEVARAJ ASANGI

MCA

2025-Jan- Edition
INDEX

1. Introduction to Python:
➢ History and evolution
➢ Installing Python and setting up the environment
➢ Your first Python program
2. Basic Syntax and Data Types:
➢ Variables and data types
➢ Operators
➢ Input and output
3. Control Flow:
➢ Conditional statements (if-else)
➢ Loops (for, while)
4. Functions:
➢ Defining and calling functions
➢ Parameters and return values
5. Data Structures:
➢ Lists, tuples, dictionaries, and sets
➢ Common operations and use cases
6. Object-Oriented Programming (OOP):
➢ Classes and objects
➢ Methods and inheritance
7. Modules and Libraries:
➢ Importing and using standard libraries
➢ Introduction to popular libraries (e.g., NumPy, Pandas, Matplotlib)
8. Advanced Topics:
➢ File handling
➢ Exception handling
➢ Decorators and generators
9. Practical Applications:
➢ Writing scripts for automation
➢ Building a simple web scraper
➢ Creating a basic GUI application
10. Best Practices:
➢ Code readability and PEP 8
➢ Debugging and testing
➢ Version control with Git
1. Introduction to Python

What type of language is Python?

Python is an interpreted, object-oriented, high-level programming language.

History and Evolution

Python was created by Guido van Rossum and first released in 1991. It was designed to emphasize
code readability and simplicity. Over the years, Python has evolved through major versions:

Python 1.x: Initial release focused on basic functionality.

Python 2.x: Introduced significant improvements but eventually deprecated.

Python 3.x: Current version with modern features and ongoing support.

Python's widespread adoption is due to its versatility and the active development of its ecosystem.

Installing Python and Setting Up the Environment

To start coding in Python, follow these steps:

1. Download Python: Visit the official Python website and download the latest version
compatible with your operating system.

2. Install Python: Follow the installation instructions for your platform. Ensure you check the
box to add Python to your system's PATH during installation.

3. Set Up an IDE: Use an Integrated Development Environment (IDE) like PyCharm or VSCode,
or start with the default IDLE that comes with Python.

4. Verify Installation:

o Open a terminal or command prompt.

o Type python --version or python3 --version to check the installed version.

Your First Python Program

Write and run your first Python program:

1. Open your IDE or text editor.

2. Create a new file named hello.py.

3. Add the following code:

print("Hello, World!")

4. Save the file and run it:

o In the terminal, navigate to the file's directory and type python hello.py.

Congratulations! You've written your first Python program.


2. Basic Syntax and Data Types
Variables and Data Types

Variables in Python are used to store data values. Python is dynamically typed, meaning you don't
need to declare the type of a variable explicitly.

Example:

# Variable declaration

x = 10 # Integer

y = 3.14 # Float

name = "Alice" # String

is_active = True # Boolean

print(x, y, name, is_active)

Common Data Types:

1. int: Integer values (e.g., 5, -10).


2. float: Decimal values (e.g., 3.14, -0.5).
3. str: Text data (e.g., "Hello").
4. bool: Boolean values (True or False).
5. list: Ordered collection (e.g., [1, 2, 3]).
6. tuple: Immutable ordered collection (e.g., (1, 2, 3)).
7. dict: Key-value pairs (e.g., {"name": "Alice", "age": 25}).
8. set: Unordered unique elements (e.g., {1, 2, 3}).

Operators
Python provides a variety of operators to perform operations on variables:

1. Arithmetic Operators: +, -, *, /, %, **, //

a = 10

b=3

print(a + b) # Addition

print(a ** b) # Exponentiation

2. Comparison Operators: ==, !=, <, >, <=, >=

print(a > b) # True

print(a == b) # False

3. Logical Operators: and, or, not

print(a > 5 and b < 5) # True


print(not (a > b)) # False

4. Assignment Operators: =, +=, -=, *=, /=, %=

x=5

x += 3 # x = x + 3

print(x) # 8

Input and Output

Python allows user input and provides flexible output formatting.

Example:

# Input

name = input("Enter your name: ")

print("Hello, " + name + "!")

# Output formatting

age = 25

print(f"{name} is {age} years old.")


3. Control Flow
Conditional Statements (if-else)

Conditional statements allow your program to execute certain blocks of code based on specific
conditions.

Syntax:

if condition:

# code to execute if condition is true

elif another_condition:

# code to execute if another_condition is true

else:

# code to execute if none of the above conditions are true

Example:

age = int(input("Enter your age: "))

if age < 18:

print("You are a minor.")

elif age == 18:

print("You just became an adult!")

else:

print("You are an adult.")

Loops (for, while)


Loops are used to repeat a block of code multiple times.

1. For Loop:

A for loop iterates over a sequence (like a list, tuple, or range).

Syntax:

for variable in sequence:

# code to execute for each item in sequence

Example:
for i in range(5):

print("Iteration:", i)

2. While Loop:
A while loop repeats as long as a condition is true.

Syntax:

while condition:
# code to execute while condition is true

Example:

count = 0

while count < 5:

print("Count is:", count)

count += 1

Breaking Out of Loops

• break: Exits the loop immediately.

• continue: Skips the rest of the current iteration and moves to the next.

Example:

for i in range(10):

if i == 5:

break # Stops the loop when i is 5

if i % 2 == 0:

continue # Skips even numbers

print(i)
4. Functions:
Functions are a fundamental concept in programming, allowing you to group a set of statements
together and give them a name. You can then call the function by its name to execute the block of
code.

1. Defining and Calling Functions

To define a function, you use the def keyword (in Python), followed by the function name and
parentheses. If the function has parameters (inputs), they are listed inside the parentheses.

Here’s an example of defining and calling a function:

python

# Defining a function

def greet(name):

print(f"Hello, {name}!")

# Calling the function

greet("Alice")

This will output:

Hello, Alice!

2. Parameters and Return Values

A parameter is a variable used in the function definition to receive values when the function is
called. Return values allow a function to send back data to the caller.

Example with parameters and return values:

python

# Defining a function with parameters and a return value

def add_numbers(a, b):

return a + b

# Calling the function and storing the result

result = add_numbers(3, 5)

# Printing the result

print(result)

This will output:

8
In this example:

• a and b are parameters.

• The function returns the sum of a and b, which is then printed out.

Summary:

• Defining a function involves using the def keyword, a function name, and optional
parameters.

• Calling a function executes the code inside it.

• Functions can accept parameters and can return values using the return keyword.
5. Data Structures:

In Python, there are several built-in data structures that are used to store collections of data. These
include lists, tuples, dictionaries, and sets. Each has different characteristics and use cases.

1. Lists

A list is an ordered, mutable (changeable) collection of items. Lists can hold items of different data
types.

Example:

python

# Defining a list

my_list = [1, 2, 3, "apple", 4.5]

# Accessing elements

print(my_list[0]) # Outputs: 1

# Modifying elements

my_list[1] = "banana"

# Adding elements

my_list.append("orange")

# Removing elements

my_list.remove("apple")

Common operations:

• append() – Adds an item to the end of the list.

• remove() – Removes the first occurrence of an item.

• pop() – Removes and returns an item at the specified index.

• len() – Returns the number of items in the list.

• List slicing – Access a subset of elements (e.g., my_list[1:3]).

Use cases:

• Storing ordered collections.


• Easy to modify (e.g., add, remove, or change items).

2. Tuples

A tuple is an ordered, immutable collection of items. Once defined, the values in a tuple cannot be
changed.

Example:

python

# Defining a tuple

my_tuple = (1, 2, 3, "apple", 4.5)

# Accessing elements

print(my_tuple[0]) # Outputs: 1

Common operations:

• Tuples are immutable, so you can't modify elements once created.

• You can slice tuples and use them in loops, similar to lists.

Use cases:

• When you need an ordered collection that should not be modified.

• Storing fixed collections of data.

3. Dictionaries

A dictionary (often referred to as a dict) is an unordered collection of key-value pairs. Each key must
be unique, and values can be of any data type.

Example:

python

# Defining a dictionary

my_dict = {"name": "Alice", "age": 25, "city": "New York"}

# Accessing elements by key

print(my_dict["name"]) # Outputs: Alice

# Modifying values

my_dict["age"] = 26

# Adding new key-value pair

my_dict["job"] = "Engineer"
Common operations:

• Access elements by key: my_dict["key"].

• Add/modify key-value pairs.

• Use del to remove a key-value pair.

• keys(), values(), and items() to get lists of keys, values, or key-value pairs.

Use cases:

• When you need to associate a unique key with a value (e.g., storing data like usernames and
passwords).

4. Sets

A set is an unordered collection of unique items. Sets do not allow duplicate elements.

Example:

python

# Defining a set

my_set = {1, 2, 3, 4, 5}

# Adding elements

my_set.add(6)

# Removing elements

my_set.remove(3)

# Checking membership

print(2 in my_set) # Outputs: True

Common operations:

• add() – Adds an element to the set.

• remove() – Removes an element.

• union(), intersection(), and difference() – Perform set operations.

• Sets automatically eliminate duplicates.


Use cases:

• When you need a collection of unique elements.

• Performing mathematical set operations like union, intersection, and difference.

Summary of Common Operations:

Data Operations Use Cases


Structure

List append(), remove(), pop(), len() Ordered, changeable collections (e.g., to-do
lists)

Tuple index(), count() Ordered, unchangeable collections (e.g.,


coordinates)

Dictionary keys(), values(), items(), get() Key-value pairs (e.g., storing user data)

Set add(), remove(), union(), Unique items, set operations (e.g., removing
intersection() duplicates)

Each data structure serves a different purpose depending on whether you need mutability,
uniqueness, or key-based access.
6. Object-Oriented Programming (OOP):

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects,"


which are instances of classes. Classes are templates for creating objects and can contain both data
(attributes) and functions (methods) that operate on the data.

1. Classes and Objects

• Class: A blueprint for creating objects. It defines attributes (data) and methods (functions).

• Object: An instance of a class. It represents a specific object created from a class template.

Example of Defining a Class and Creating Objects:

python

# Defining a class

class Car:

# Constructor to initialize the object (attributes)

def __init__(self, make, model, year):

self.make = make # Attribute: make

self.model = model # Attribute: model

self.year = year # Attribute: year

# Method: A function inside a class

def display_info(self):

print(f"{self.year} {self.make} {self.model}")

# Creating objects (instances) of the Car class

car1 = Car("Toyota", "Corolla", 2021)

car2 = Car("Honda", "Civic", 2022)

# Calling a method on the objects

car1.display_info() # Outputs: 2021 Toyota Corolla

car2.display_info() # Outputs: 2022 Honda Civic

Key Points:
• The __init__ method is the constructor, which initializes the object when it's created.

• self is a reference to the current object (similar to this in other programming languages).

2. Methods and Inheritance

Methods

Methods are functions that belong to a class and are used to perform actions on an object’s
attributes. They are defined inside the class.

Example of defining and using methods:

python

class Dog:

def __init__(self, name, age):

self.name = name

self.age = age

def bark(self):

print(f"{self.name} says woof!")

# Creating an object and calling a method

dog1 = Dog("Buddy", 3)

dog1.bark() # Outputs: Buddy says woof!

Inheritance

Inheritance allows one class (called a child class or subclass) to inherit attributes and methods from
another class (called a parent class or superclass). This enables code reuse and the creation of a
hierarchical class structure.

Example of Inheritance:

python

# Parent class (Superclass)

class Animal:

def __init__(self, name):

self.name = name
def speak(self):

print(f"{self.name} makes a sound.")

# Child class (Subclass) inheriting from Animal

class Dog(Animal):

def speak(self):

print(f"{self.name} barks.")

# Creating an object of the Dog class (which inherits from Animal)

dog = Dog("Rex")

dog.speak() # Outputs: Rex barks.

Key Points:

• Inheritance allows the child class to override methods from the parent class or add new
methods.

• The child class can call the parent class methods using super() if needed.

Example of Inheritance with super():

python

class Dog(Animal):

def __init__(self, name, breed):

# Using the parent class constructor

super().__init__(name)

self.breed = breed

def speak(self):

print(f"{self.name} barks, and is a {self.breed}.")

# Creating an object of Dog class

dog = Dog("Max", "Labrador")

dog.speak() # Outputs: Max barks, and is a Labrador.


Summary:

• Classes are blueprints for creating objects and define methods and attributes.

• Objects are instances of classes.

• Methods are functions that operate on the attributes of the class.

• Inheritance allows a class to inherit attributes and methods from another class, enabling
code reuse and hierarchical relationships.
7. Modules and Libraries in Python

In Python, modules and libraries are essential for organizing and reusing code. A module is a file
containing Python code (e.g., functions, variables, classes), while a library is a collection of modules
that provide additional functionality. Python comes with a large number of standard libraries that can
be imported and used for various tasks, from mathematical operations to web development.

1. Importing and Using Standard Libraries

To use a library or module in Python, you need to import it first. There are several ways to import
modules:

1. Import the entire module:

python

import math # Importing the math module

print(math.sqrt(16)) # Outputs: 4.0

2. Import specific functions or classes from a module:

python

from math import sqrt # Importing only the sqrt function

print(sqrt(16)) # Outputs: 4.0

3. Rename the module using as:

python

import math as m # Renaming math module to 'm'

print(m.sqrt(16)) # Outputs: 4.0

4. Import all functions and classes (not recommended for large projects as it can clutter the
namespace):

python

from math import * # Imports all functions from math module

print(sqrt(16)) # Outputs: 4.0


Some common standard libraries in Python:

• math: Provides mathematical functions (e.g., sqrt(), sin(), cos()).

• random: Used for generating random numbers (e.g., randint(), choice()).

• datetime: Used for working with dates and times.

• os: Provides a way to interact with the operating system (e.g., file manipulation, directories).

• sys: Provides access to system-specific parameters and functions (e.g., command-line


arguments).

2. Introduction to Popular Libraries

NumPy (Numerical Python)

NumPy is a powerful library used for numerical computing, especially for handling large arrays and
matrices, along with mathematical functions to operate on these arrays.

• Installation: pip install numpy

• Common Operations with NumPy:

python

import numpy as np

# Create a NumPy array

arr = np.array([1, 2, 3, 4])

# Array operations

print(arr + 2) # Outputs: [3 4 5 6]

print(np.sqrt(arr)) # Outputs: [1. 1.41421356 1.73205081 2. ]

• Use cases:

o Efficient array and matrix operations.

o Linear algebra, random number generation, Fourier transforms.


Pandas

Pandas is a powerful library used for data manipulation and analysis, particularly for working with
structured data in the form of DataFrames and Series.

• Installation: pip install pandas

• Common Operations with Pandas:

python

import pandas as pd

# Creating a DataFrame

data = {"Name": ["Alice", "Bob", "Charlie"], "Age": [24, 27, 22]}

df = pd.DataFrame(data)

# Accessing DataFrame columns

print(df["Name"]) # Outputs: Alice, Bob, Charlie

# Summary statistics

print(df.describe()) # Outputs summary of numerical columns

# Filtering data

print(df[df["Age"] > 23]) # Outputs rows where age > 23

• Use cases:

o Data cleaning and manipulation.

o Working with time series data, reading/writing CSV, Excel files.

o Aggregating and grouping data.

Matplotlib

Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python.

• Installation: pip install matplotlib

• Common Operations with Matplotlib:


python

import matplotlib.pyplot as plt

# Simple line plot

x = [1, 2, 3, 4]

y = [10, 20, 25, 30]

plt.plot(x, y)

# Adding labels and title

plt.xlabel("X-axis")

plt.ylabel("Y-axis")

plt.title("Simple Line Plot")

# Displaying the plot

plt.show()

• Use cases:

o Plotting data (line, bar, scatter plots, histograms, etc.).

o Visualizing mathematical functions.

o Creating custom plots for data analysis and reporting.

Summary of Key Libraries:

Library Description Example Usage

Numerical computing library, provides support for Handling large datasets,


NumPy
large, multi-dimensional arrays and matrices. mathematical computations.

Provides data structures like Series and DataFrame Data cleaning, transformation,
Pandas
for data manipulation and analysis. and analysis.

Visualization library for creating static, animated, and Plotting graphs, charts, and data
Matplotlib
interactive plots. visualization.

Conclusion:
• Modules and libraries allow you to extend Python's functionality with ready-made code for
common tasks.

• Standard libraries provide essential tools that help you with everything from basic math to
working with files.

• Popular libraries like NumPy, Pandas, and Matplotlib are indispensable for tasks like data
manipulation, scientific computing, and data visualization.
8. Advanced Topics:
Advanced Python Topics

In Python, there are several advanced concepts that allow you to write more efficient, maintainable,
and scalable code. These include file handling, exception handling, decorators, and generators.
Let’s dive into each of them.

1. File Handling

File handling refers to the process of reading from and writing to files in Python. This allows your
program to persist data beyond its execution, enabling you to work with text, binary, and CSV files.

Opening a File

Python provides several modes for opening files:

• 'r': Read (default mode).

• 'w': Write (creates a new file or truncates an existing one).

• 'a': Append (writes data to the end of the file).

• 'b': Binary mode (for non-text files).

• 'x': Exclusive creation (creates a new file, but raises an error if the file exists).

Example: Reading from a File

python

# Opening a file for reading

with open("example.txt", "r") as file:

content = file.read()

print(content)

• The with statement is used for automatic resource management, ensuring the file is closed
after the block of code is executed.

Example: Writing to a File

python

# Opening a file for writing

with open("example.txt", "w") as file:

file.write("Hello, World!\n")

file.write("This is a test.")
Common File Handling Operations:

• file.read(): Reads the entire file content.

• file.readline(): Reads one line from the file.

• file.readlines(): Reads all lines and returns them as a list.

• file.write(): Writes data to the file.

• file.writelines(): Writes a list of lines to the file.

2. Exception Handling

Exception handling allows you to gracefully handle runtime errors in your program, preventing it
from crashing and allowing you to respond to errors in a controlled manner.

Basic Syntax

python

try:

# Code that may raise an exception

num = 10 / 0

except ZeroDivisionError as e:

# Handling the exception

print(f"Error: {e}")

finally:

# Code that will run no matter what

print("This will always be executed.")

Explanation:

• try: The block of code that may raise an exception.

• except: Defines the block that runs if a specific exception occurs.

• finally: The block that always runs, regardless of whether an exception occurred or not.
Useful for cleanup tasks like closing files.

Example: Handling Multiple Exceptions

python

try:

# Code that may raise exceptions

num1 = int(input("Enter a number: "))


num2 = int(input("Enter another number: "))

result = num1 / num2

except ValueError:

print("Invalid input, please enter a number.")

except ZeroDivisionError:

print("You cannot divide by zero.")

except Exception as e:

print(f"An unexpected error occurred: {e}")

Raising Exceptions

You can raise your own exceptions using the raise keyword:

python

def check_age(age):

if age < 18:

raise ValueError("Age must be 18 or older.")

return age

try:

check_age(15)

except ValueError as e:

print(e) # Outputs: Age must be 18 or older.

3. Decorators

A decorator is a function that allows you to modify the behavior of another function without
changing its code. Decorators are often used for logging, access control, caching, and other cross-
cutting concerns.

Basic Syntax

python

def decorator_function(original_function):

def wrapper_function():

print("Wrapper executed this before {}".format(original_function.__name__))

return original_function()
return wrapper_function

@decorator_function

def display():

print("Display function executed.")

# Calling the decorated function

display()

Output:

arduino

Wrapper executed this before display

Display function executed.

Explanation:

• decorator_function: This is the decorator that modifies the behavior of display().

• @decorator_function: This syntax is shorthand for display = decorator_function(display).

Example: Decorator with Arguments

If the function being decorated accepts arguments, you can modify the decorator to handle them:

python

def greet_decorator(func):

def wrapper(name):

print(f"Hello {name}!")

return func(name)

return wrapper

@greet_decorator

def greet(name):

print(f"How are you, {name}?")

greet("Alice")
Output:

sql

Hello Alice!

How are you, Alice?

4. Generators

A generator is a function that produces a sequence of results using the yield keyword. Unlike normal
functions that return a single value, a generator "yields" multiple values, one at a time. This makes
them memory-efficient, especially for large datasets.

Basic Syntax:

python

def my_generator():

yield 1

yield 2

yield 3

# Using the generator

gen = my_generator()

print(next(gen)) # Outputs: 1

print(next(gen)) # Outputs: 2

print(next(gen)) # Outputs: 3

Explanation:

• The yield keyword suspends the function’s state, returning a value, and allows the function
to be resumed from where it left off.

Example: Using a Generator for Large Data Sets

Generators are useful when dealing with large datasets because they generate values on the fly,
rather than storing them all in memory.

python
def count_up_to(n):

count = 1

while count <= n:

yield count

count += 1

counter = count_up_to(5)

for num in counter:

print(num)

Output:

Benefits of Generators:

• Memory-efficient: Unlike lists, which store all values in memory, generators produce values
one at a time and do not store them.

• Lazy evaluation: Values are computed only when needed, making them ideal for large
datasets or infinite sequences.

Summary of Advanced Topics

Concept Description

Reading from and writing to files using open(), read(), write(), and other
File Handling
functions.

Exception
Catching and managing errors using try, except, and finally blocks.
Handling

Functions that modify the behavior of other functions, often used for logging,
Decorators
authentication, etc.
Concept Description

Functions that yield a sequence of values, producing them one at a time in a


Generators
memory-efficient way.

Conclusion

Mastering advanced topics such as file handling, exception handling, decorators, and generators is
crucial for writing clean, efficient, and scalable Python code. These concepts empower you to
manage resources, handle errors gracefully, and optimize performance, especially when working
with large datasets or complex functionalities.
9. Practical Applications
In this section, we'll explore practical applications of Python for solving real-world problems. These
include writing scripts for automation, building a simple web scraper, and creating a basic GUI
application. These skills are widely used in tasks like automating repetitive processes, collecting data
from websites, and building desktop applications.

1. Writing Scripts for Automation

One of the most powerful uses of Python is for automation—scripting to perform tasks that would
normally require manual effort. Python can be used to automate tasks like file handling, web
interactions, sending emails, and more.

Example: Automating File Organization

Suppose you want to automatically organize files into folders based on their file type. This script will
move files into folders named after their extensions.

python

import os

import shutil

# Path where files are located

source_folder = "/path/to/your/folder"

# Get list of all files in the source folder

files = os.listdir(source_folder)

# Iterate over files

for file in files:

# Get the file extension

file_extension = file.split('.')[-1]

folder_name = os.path.join(source_folder, file_extension)

# Create folder if it doesn't exist

if not os.path.exists(folder_name):

os.makedirs(folder_name)
# Move file to the respective folder

shutil.move(os.path.join(source_folder, file), os.path.join(folder_name, file))

print("Files have been organized.")

What this does:

• Lists files in the specified folder.

• Creates subdirectories for each file type (e.g., .txt, .jpg).

• Moves the files into the appropriate subdirectory.

2. Building a Simple Web Scraper

A web scraper is a script that extracts data from web pages. Python libraries like requests and
BeautifulSoup make web scraping easy.

Example: Scraping Titles from a Website

Let's build a simple web scraper that extracts the titles of articles from a blog.

python

import requests

from bs4 import BeautifulSoup

# URL of the website to scrape

url = "https://example-blog.com"

# Send a GET request to fetch the page content

response = requests.get(url)

# Parse the HTML content with BeautifulSoup

soup = BeautifulSoup(response.text, "html.parser")

# Find all article titles (assuming they are in <h2> tags)

titles = soup.find_all("h2")

# Print the titles

for title in titles:

print(title.text)
Explanation:

• requests.get(url): Fetches the webpage content.

• BeautifulSoup(response.text, "html.parser"): Parses the HTML content using BeautifulSoup.

• soup.find_all("h2"): Extracts all <h2> tags, which we assume are the titles of the articles.

Libraries for Web Scraping:

• requests: Makes HTTP requests to fetch the content of a webpage.

• BeautifulSoup: Parses HTML and XML documents and allows for easy extraction of data.

3. Creating a Basic GUI Application

Python can also be used to create graphical user interfaces (GUIs) using libraries like Tkinter. Let's
build a simple calculator application.

Example: Simple Calculator with Tkinter

python

import tkinter as tk

# Function to perform arithmetic operations

def on_click(button_text):

current_text = entry.get()

if button_text == "=":

try:

result = eval(current_text)

entry.delete(0, tk.END)

entry.insert(tk.END, str(result))

except Exception as e:

entry.delete(0, tk.END)

entry.insert(tk.END, "Error")

elif button_text == "C":

entry.delete(0, tk.END)

else:

entry.insert(tk.END, button_text)

# Create the main window

window = tk.Tk()
window.title("Simple Calculator")

# Create an entry widget to display the current calculation

entry = tk.Entry(window, width=20, font=("Arial", 24))

entry.grid(row=0, column=0, columnspan=4)

# Define buttons

buttons = [

("7", 1, 0), ("8", 1, 1), ("9", 1, 2), ("/", 1, 3),

("4", 2, 0), ("5", 2, 1), ("6", 2, 2), ("*", 2, 3),

("1", 3, 0), ("2", 3, 1), ("3", 3, 2), ("-", 3, 3),

("0", 4, 0), (".", 4, 1), ("=", 4, 2), ("+", 4, 3),

("C", 5, 0)

# Create and place buttons

for (text, row, col) in buttons:

button = tk.Button(window, text=text, font=("Arial", 18), width=5, height=2, command=lambda


t=text: on_click(t))

button.grid(row=row, column=col)

# Run the main event loop

window.mainloop()

Explanation:

• The tkinter library is used to create a graphical interface.

• We define buttons for the digits, operations, and special functions like clear (C) and equals
(=).

• When the user clicks a button, the corresponding value is entered into the entry widget (the
display area).

• The eval() function evaluates the arithmetic expression when the equals button is clicked.

How it works:

• The calculator GUI updates the entry widget with the current input, and the result is
displayed when the equals button is pressed.

• The C button clears the input field.


Conclusion

Python’s versatility shines when applied to real-world tasks like automation, web scraping, and
building graphical applications:

• Automating repetitive tasks can save a significant amount of time. The example provided
demonstrates how to organize files based on their extensions.

• Web scraping enables you to collect data from websites for analysis or aggregation. The
simple scraper pulls article titles from a blog.

• Building a GUI application like the calculator shows how Python can be used to develop
user-friendly applications.

Mastering these practical applications opens the door to solving a wide range of problems efficiently
and creatively.
10. Best Practices

In this section, we’ll cover important best practices for writing clean, maintainable, and efficient
Python code. These practices include adhering to PEP 8 for code style, implementing proper
debugging and testing techniques, and using version control with Git to manage code changes.

1. Code Readability and PEP 8

PEP 8 (Python Enhancement Proposal 8) is the style guide for Python code. Following PEP 8 ensures
that your code is clean, readable, and consistent with the Python community’s conventions. It
enhances collaboration and makes your code easier to maintain.

Key Points of PEP 8:

• Indentation: Use 4 spaces per indentation level.

o Example:

python

def my_function():

if condition:

print("True")

else:

print("False")

• Line Length: Limit all lines to a maximum of 79 characters (72 for docstrings).

o Example:

python

# Good practice: Keep lines short for readability.

def long_function_name(parameter_one, parameter_two):

result = parameter_one * parameter_two

return result

• Blank Lines: Use blank lines to separate functions, classes, and blocks of code inside
functions.

o Example:

python
def function_one():

pass

def function_two():

pass

• Naming Conventions:

o Function and variable names should be written in snake_case (e.g., my_variable).

o Class names should be written in CamelCase (e.g., MyClass).

o Constants should be written in UPPERCASE (e.g., PI = 3.14).

• Imports: Imports should be on separate lines and follow this order:

1. Standard library imports

2. Related third-party imports

3. Local application or library imports

python

import os

import sys

import numpy as np

• Docstrings: Use docstrings to describe your functions, classes, and modules.

o Example:

python

def greet(name):

"""

Greets the person by name.

Arguments:

name (str): The name of the person to greet.

"""

print(f"Hello, {name}!")

For more details, you can refer to the full PEP 8 guide here.
2. Debugging and Testing

Debugging

Debugging is the process of identifying and fixing issues or bugs in your code. There are several
techniques to debug Python code effectively.

• Using print statements: Adding print() statements helps trace the flow of execution and
examine variable values at different stages.

python

def add(a, b):

print(f"a: {a}, b: {b}")

return a + b

• Using Python's built-in debugger (pdb): The Python debugger (pdb) allows you to pause the
execution of your program and inspect variables, step through code, and evaluate
expressions.

python

import pdb

def faulty_code():

a = 10

b=0

pdb.set_trace() # Pauses execution here

return a / b

faulty_code()

Once the code reaches the pdb.set_trace() line, you can enter commands like n (next), s (step), or p
(print) to inspect the execution.

Testing

Testing ensures that your code works as expected and helps prevent future bugs. There are several
testing techniques in Python.

• Unit Testing: Python’s unittest module allows you to test individual units of code (functions,
methods) for correctness.

python

import unittest

def add(a, b):

return a + b
class TestMathOperations(unittest.TestCase):

def test_add(self):

self.assertEqual(add(1, 2), 3)

self.assertEqual(add(-1, 1), 0)

if __name__ == "__main__":

unittest.main()

o assertEqual() checks whether the result of add() matches the expected value.

o To run the tests, execute the script.

• Test Coverage: Ensure that your tests cover all possible paths and scenarios in your code.

o Tools like coverage.py can help track the test coverage.

• Mocking: When testing code that interacts with external systems (e.g., APIs, databases), you
can use mocking to simulate these interactions without actually invoking them.

3. Version Control with Git

Version control helps track changes to your codebase over time, allowing you to collaborate with
others, revert to previous versions, and manage releases. Git is the most popular version control
system, and platforms like GitHub, GitLab, and Bitbucket are widely used for hosting code
repositories.

Key Concepts:

• Commit: A snapshot of your project at a certain point in time. Each commit contains a
message that describes the changes made.

bash

git commit -m "Fixed bug in the user login logic"

• Branch: A separate line of development. This allows you to work on new features or fixes
without affecting the main codebase.

bash

git checkout -b new-feature

• Merge: Combines changes from different branches into one. After a feature is complete, you
can merge it back into the main branch.

bash
git merge new-feature

• Pull Requests (PRs): On platforms like GitHub, PRs are used to propose changes and discuss
them before merging them into the main codebase.

• Push and Pull: Git is used to synchronize your local code with the remote repository.

o Push: Upload your changes to a remote repository.

bash

git push origin main

o Pull: Fetch and merge changes from a remote repository to your local machine.

bash

git pull origin main

Git Workflow Example:

1. Clone a repository:

bash

git clone https://github.com/user/repo.git

2. Create a new branch for a feature:

bash

git checkout -b feature-xyz

3. Make changes and commit them:

bash

git add .

git commit -m "Added feature XYZ"

4. Push changes to the remote repository:

bash

git push origin feature-xyz

5. Create a pull request on GitHub to merge your changes into the main branch.

Best Practices for Git:

• Commit early and often: Make small, meaningful commits rather than large, infrequent
ones.

• Write clear commit messages: Describe what and why you are changing.

o Example: Fix: Corrected the logic in the user login function


• Use branches for features, bug fixes, or experiments, and merge them when ready.

• Keep your main branch clean: Avoid working directly on main—use feature branches and
merge them when they are complete.

Summary of Best Practices

Practice Description

PEP 8 Follow Python's official style guide for readability and consistency.

Debugging Use techniques like print statements, pdb, and log files for debugging.

Write unit tests and ensure test coverage using tools like unittest and
Testing
coverage.py.

Version Control Use Git for version control: commit frequently, use branches, and create pull
with Git requests for code review.

Conclusion

By following best practices such as adhering to PEP 8 for clean code, employing effective debugging
and testing techniques, and managing your code with Git, you’ll ensure that your Python code is
maintainable, efficient, and ready for collaboration. These best practices will not only improve the
quality of your code but also enhance your development workflow and productivity.

THANKYOU

You might also like