PYTHON notes by devaraj
PYTHON notes by devaraj
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
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 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.
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:
print("Hello, World!")
o In the terminal, navigate to the file's directory and type python hello.py.
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
Operators
Python provides a variety of operators to perform operations on variables:
a = 10
b=3
print(a + b) # Addition
print(a ** b) # Exponentiation
print(a == b) # False
x=5
x += 3 # x = x + 3
print(x) # 8
Example:
# Input
# Output formatting
age = 25
Conditional statements allow your program to execute certain blocks of code based on specific
conditions.
Syntax:
if condition:
elif another_condition:
else:
Example:
else:
1. For Loop:
Syntax:
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
count += 1
• continue: Skips the rest of the current iteration and moves to the next.
Example:
for i in range(10):
if i == 5:
if i % 2 == 0:
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.
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.
python
# Defining a function
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Hello, Alice!
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.
python
return a + b
result = add_numbers(3, 5)
print(result)
8
In this example:
• 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.
• 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
# 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:
Use cases:
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
# Accessing elements
print(my_tuple[0]) # Outputs: 1
Common operations:
• You can slice tuples and use them in loops, similar to lists.
Use cases:
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
# Modifying values
my_dict["age"] = 26
my_dict["job"] = "Engineer"
Common operations:
• 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
Common operations:
List append(), remove(), pop(), len() Ordered, changeable collections (e.g., to-do
lists)
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):
• 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.
python
# Defining a class
class Car:
def display_info(self):
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).
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.
python
class Dog:
self.name = name
self.age = age
def bark(self):
dog1 = Dog("Buddy", 3)
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
class Animal:
self.name = name
def speak(self):
class Dog(Animal):
def speak(self):
print(f"{self.name} barks.")
dog = Dog("Rex")
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.
python
class Dog(Animal):
super().__init__(name)
self.breed = breed
def speak(self):
• Classes are blueprints for creating objects and define methods and attributes.
• 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.
To use a library or module in Python, you need to import it first. There are several ways to import
modules:
python
python
python
4. Import all functions and classes (not recommended for large projects as it can clutter the
namespace):
python
• os: Provides a way to interact with the operating system (e.g., file manipulation, directories).
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.
python
import numpy as np
# Array operations
print(arr + 2) # Outputs: [3 4 5 6]
• Use cases:
Pandas is a powerful library used for data manipulation and analysis, particularly for working with
structured data in the form of DataFrames and Series.
python
import pandas as pd
# Creating a DataFrame
df = pd.DataFrame(data)
# Summary statistics
# Filtering data
• Use cases:
Matplotlib
Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python.
x = [1, 2, 3, 4]
plt.plot(x, y)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
• Use cases:
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
• 'x': Exclusive creation (creates a new file, but raises an error if the file exists).
python
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.
python
file.write("Hello, World!\n")
file.write("This is a test.")
Common File Handling Operations:
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:
num = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
finally:
Explanation:
• finally: The block that always runs, regardless of whether an exception occurred or not.
Useful for cleanup tasks like closing files.
python
try:
except ValueError:
except ZeroDivisionError:
except Exception as e:
Raising Exceptions
You can raise your own exceptions using the raise keyword:
python
def check_age(age):
return age
try:
check_age(15)
except ValueError as e:
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():
return original_function()
return wrapper_function
@decorator_function
def display():
display()
Output:
arduino
Explanation:
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):
greet("Alice")
Output:
sql
Hello 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
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.
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
yield count
count += 1
counter = count_up_to(5)
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.
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
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.
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.
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
source_folder = "/path/to/your/folder"
files = os.listdir(source_folder)
file_extension = file.split('.')[-1]
if not os.path.exists(folder_name):
os.makedirs(folder_name)
# Move file to the respective folder
A web scraper is a script that extracts data from web pages. Python libraries like requests and
BeautifulSoup make web scraping easy.
Let's build a simple web scraper that extracts the titles of articles from a blog.
python
import requests
url = "https://example-blog.com"
response = requests.get(url)
titles = soup.find_all("h2")
print(title.text)
Explanation:
• soup.find_all("h2"): Extracts all <h2> tags, which we assume are the titles of the articles.
• BeautifulSoup: Parses HTML and XML documents and allows for easy extraction of data.
Python can also be used to create graphical user interfaces (GUIs) using libraries like Tkinter. Let's
build a simple calculator application.
python
import tkinter as tk
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")
entry.delete(0, tk.END)
else:
entry.insert(tk.END, button_text)
window = tk.Tk()
window.title("Simple Calculator")
# Define buttons
buttons = [
("C", 5, 0)
button.grid(row=row, column=col)
window.mainloop()
Explanation:
• 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.
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.
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.
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
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:
python
import os
import sys
import numpy as np
o Example:
python
def greet(name):
"""
Arguments:
"""
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
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
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
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.
• Test Coverage: Ensure that your tests cover all possible paths and scenarios in your code.
• 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.
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
• Branch: A separate line of development. This allows you to work on new features or fixes
without affecting the main codebase.
bash
• 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.
bash
o Pull: Fetch and merge changes from a remote repository to your local machine.
bash
1. Clone a repository:
bash
bash
bash
git add .
bash
5. Create a pull request on GitHub to merge your changes into the main branch.
• Commit early and often: Make small, meaningful commits rather than large, infrequent
ones.
• Write clear commit messages: Describe what and why you are changing.
• Keep your main branch clean: Avoid working directly on main—use feature branches and
merge them when they are complete.
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