Python Learning

Here we post everything that we learn in python while doing this course

1. Python Fundamentals (≈10 Hours)

Environment Setup

Welcome to the first step of your Python journey! In this section, we'll cover everything you need to get started: installing Python, choosing the right IDE, and running your very first script. This foundation will ensure you have a smooth and efficient environment to support your learning.

Check out this detailed blog post: Real Python’s Guide to Installing Pythonarrow-up-right

chevron-rightEnvironment Setuphashtag

1. Installing Python

Python is open-source and free to use. Here’s how to get it on your machine:

  • Download the Installer: Visit python.orgarrow-up-right and download the installer for your operating system. For most users, the latest stable version is the best choice.

  • Run the Installer: During installation, make sure to check the box that says "Add Python to PATH." This small step allows you to run Python from any command prompt or terminal window without additional configuration.

  • Verify Your Installation: Open your terminal or command prompt and type:

    python --version

    You should see the Python version number displayed, confirming the successful installation.

2. Choosing an IDE

An Integrated Development Environment (IDE) simplifies coding by providing features like syntax highlighting, debugging tools, and code suggestions. Here are a few popular options:

  • Visual Studio Code (VS Code): A versatile and lightweight editor, VS Code is highly recommended for beginners. Its extensive marketplace of extensions, including Python-specific plugins, makes it a powerful tool for development.

  • PyCharm: PyCharm is a dedicated Python IDE that offers a rich set of features tailored to Python development. While the Community Edition is free, it provides robust tools for coding, testing, and debugging.

  • Other Options: Alternatives like Atom, Sublime Text, or even Jupyter Notebook (great for data analysis) can also be considered, depending on your project needs.

Choose the one that best fits your style and workflow. If you’re unsure, starting with VS Code is a safe bet due to its balance of simplicity and functionality.

3. Running Your First Python Script

Now that Python is installed and your IDE is set up, it’s time to write and run a simple script.

  • Create a New File: Open your IDE and create a new file named hello.py.

  • Write Your Code: Type the following code:

    print("Hello, Python!")
  • Run the Script: There are a couple of ways to execute your script:

    • Using the Terminal: Navigate to the directory where your script is saved and run:

      python hello.py
    • From the IDE: Most IDEs provide a “Run” button or similar functionality that allows you to execute the script directly from the interface.

When you run your script, you should see the output “Hello, Python!” in your terminal or the IDE’s console.


Python Basics: Syntax & Data Types

Understanding Python’s basic syntax and data types is the foundation of writing efficient code. In this section, we will cover variables, numbers, strings, booleans, and operators.


1. Variables & Assignment

A variable stores data in memory and can be assigned using =.

  • Python is dynamically typed, meaning you don’t need to specify the type explicitly.

  • Variable names should be meaningful and follow the snake_case convention (my_variable).

Practice Questions

  1. Declare three variables: an integer, a floating-point number, and a string. Print their values.

  2. Swap the values of two variables without using a third variable.

  3. What will be the output of the following?

    (Predict the output before running the code!)


2. Data Types

Python has built-in types for handling different kinds of data:

Type
Example
Description

int

10

Whole numbers

float

3.14

Decimal numbers

str

"Hello"

Text enclosed in quotes

bool

True, False

Logical values

list

[1, 2, 3]

Ordered collection (mutable)

tuple

(1, 2, 3)

Ordered collection (immutable)

dict

{"key": "value"}

Key-value pairs

set

{1, 2, 3}

Unordered unique elements

Use the type() function to check the data type:

Practice Questions

  1. What is the difference between a list and a tuple? Create one of each.

  2. Convert the string "123" to an integer and add 10 to it.

  3. What will be the output of bool(""), bool(0), and bool([])? Why?


3. Operators in Python

Python supports several operators:

A. Arithmetic Operators

Operator
Description
Example

+

Addition

5 + 3 = 8

-

Subtraction

10 - 2 = 8

*

Multiplication

4 * 2 = 8

/

Division

10 / 2 = 5.0

//

Floor Division

10 // 3 = 3

%

Modulus

10 % 3 = 1

**

Exponentiation

2 ** 3 = 8

B. Comparison Operators

Operator
Description
Example

==

Equal to

5 == 5 → True

!=

Not equal to

5 != 3 → True

>

Greater than

7 > 5 → True

<

Less than

3 < 5 → True

>=

Greater than or equal to

5 >= 5 → True

<=

Less than or equal to

4 <= 6 → True

C. Logical Operators

Operator
Description
Example

and

Returns True if both conditions are true

(5 > 3 and 10 > 5) → True

or

Returns True if at least one condition is true

(5 > 3 or 10 < 5) → True

not

Reverses the boolean value

not(5 > 3) → False

Practice Questions

  1. What is the difference between / and // operators in Python?

  2. Predict the output of the following:

  3. Write a program that takes two numbers as input and prints whether the first is greater than, less than, or equal to the second.


4. String Operations

Strings (str) are sequences of characters enclosed in quotes.

String Concatenation & Formatting

Practice Questions

  1. Given a string "Python Programming", write a program to:

    • Convert it to lowercase.

    • Find the index of the letter "P".

    • Extract "Programming" from the string.

  2. What is the difference between single quotes (') and double quotes (") in Python strings?

  3. What will be the output of the following?

Next Steps: Practice these concepts by solving the questions above before moving on to loops and control structures!


Python Control Structures: Conditional Statements & Loops

Control structures allow us to control the flow of execution in a program using conditional statements and loops. These are essential for decision-making and repetitive tasks.


1. Conditional Statements (if-elif-else)

Python uses if, elif (else if), and else to make decisions based on conditions.

Syntax:

  • The if block executes if the condition is True.

  • The elif block executes if the previous conditions are False, but its condition is True.

  • The else block executes only if all previous conditions are False.

Practice Questions:

  1. Write a Python program to check if a number is even or odd.

  2. Given three numbers, write a program to find the largest among them.

  3. Predict the output:


2. Loops in Python

Loops allow us to execute a block of code multiple times.

A. The for Loop

A for loop iterates over a sequence (list, tuple, string, etc.).

Looping Over a List:


B. The while Loop

A while loop runs as long as a condition remains True.


C. Loop Control Statements

Python provides statements to control loop execution:

Statement
Description

break

Exits the loop immediately

continue

Skips the current iteration and moves to the next

pass

Acts as a placeholder (does nothing)

Example: Using break and continue


Practice Questions:

  1. Write a Python program to print numbers from 1 to 10 using both for and while loops.

  2. Write a program that prints only even numbers from 1 to 20.

  3. Predict the output:


Next Steps: Move on to Functions & Data Structures after practicing these concepts!

2. Functions, Modules, and Data Structures (≈8 Hours)

Functions, modules, and data structures are the building blocks of Python programming. This section covers:

  1. Functions: Writing reusable code with parameters and return values.

  2. Modules & Packages: Organizing and reusing code efficiently.

  3. Core Data Structures: Lists, tuples, dictionaries, and sets.


Functions in Python

Functions allow us to write reusable code, making programs more modular and efficient.

1. Defining a Function

A function is defined using the def keyword.

2. Function Parameters & Arguments

Functions can take parameters to accept input values.

Types of Arguments:

Type
Example

Positional Arguments

greet("Alice")

Keyword Arguments

greet(name="Alice")

Default Arguments

def greet(name="Guest")

Variable-Length Arguments

*args for multiple positional args, **kwargs for multiple keyword args

3. Return Values in Functions

A function can return values using return.


Practice Questions

  1. Write a function that takes two numbers as input and returns their sum.

  2. Modify the above function to support variable-length arguments (*args).

  3. Predict the output of the following:


Modules & Packages: Organizing and Reusing Code Efficiently

In Python, modules and packages help in organizing code, improving reusability, and maintaining clean project structures.

1. Modules in Python

A module is a Python file (.py) that contains functions, classes, or variables, which can be imported into other programs.

1.1 Creating and Importing Modules

  1. Create a module (math_utils.py):

  2. Import and use the module (main.py):

  3. Importing specific functions:


2. Built-in Python Modules

Python comes with many built-in modules. Some common ones include:

Module
Purpose

math

Mathematical functions

random

Generate random numbers

datetime

Work with dates and times

os

Interact with the operating system

Example: Using the math module


3. Python Packages

A package is a collection of modules, organized using a directory with an __init__.py file.

3.1 Creating a Package

  1. Create a folder named mypackage/

  2. Inside mypackage/, create __init__.py (This makes it a package)

  3. Add modules: Example, mypackage/utils.py

  4. Import from the package:


Practice Questions

  1. Create a module calculator.py with functions for addition, subtraction, and multiplication. Import it into another script and use the functions.

  2. Use the random module to generate a random number between 1 and 100.

  3. What will be the output of the following?


Core Data Structures: Lists, Tuples, Dictionaries, and Sets

Python provides built-in data structures that help in storing and manipulating collections of data efficiently.


1. Lists (Ordered, Mutable, Allows Duplicates)

A list is an ordered collection that can hold different data types and is mutable (modifiable).

1.1 Creating and Accessing Lists

1.2 List Methods

1.3 List Comprehension

Practice Questions

  1. Create a list of numbers and find the sum of all elements.

  2. Write a Python program to remove duplicates from a list.


2. Tuples (Ordered, Immutable, Allows Duplicates)

Tuples are similar to lists but immutable (cannot be modified).

2.1 Creating and Accessing Tuples

2.2 Tuple Unpacking

Practice Questions

  1. Convert a list to a tuple and try modifying it.

  2. Write a program to swap two values using tuple unpacking.


3. Dictionaries (Key-Value Pairs, Unordered, Mutable)

A dictionary stores data in key-value pairs, making lookups efficient.

3.1 Creating and Accessing Dictionaries

3.2 Dictionary Methods

Practice Questions

  1. Create a dictionary of students with their marks and find the student with the highest marks.

  2. Write a Python script to merge two dictionaries.


4. Sets (Unordered, Unique Elements, Mutable)

A set is an unordered collection that does not allow duplicates.

4.1 Creating and Using Sets

4.2 Set Operations

Practice Questions

  1. Write a Python program to remove duplicate values from a list using a set.

  2. Given two sets, find their common elements and differences.


Error Handling in Python: Introduction to try/except Blocks

Errors (exceptions) can cause a program to crash if not handled properly. Python provides try/except blocks to handle exceptions gracefully.


1. What is an Exception?

An exception is an error that occurs during execution. Some common ones:

Exception
Description

ZeroDivisionError

Division by zero

TypeError

Operation on incompatible types

ValueError

Invalid value for a function

IndexError

List index out of range

KeyError

Accessing a non-existent dictionary key

Example of an unhandled exception:


2. Handling Errors with try/except

2.1 Basic try/except Usage

2.2 Using else and finally

  • else runs if no exception occurs.

  • finally runs always, whether an exception occurs or not.


3. Raising Custom Exceptions

Use raise to trigger custom exceptions:


Practice Questions

  1. Write a function that takes a list and an index as input. Use try/except to handle IndexError if the index is out of range.

  2. Modify a program to handle KeyError when accessing a dictionary key that doesn’t exist.

  3. Predict the output:


Object-Oriented Programming (≈6 Hours)

1. Defining a Class and Creating Objects


2. Inheritance (Reusing properties and methods from a parent class)


3. Method Overriding (Redefining a method in a child class)


4. Encapsulation (Using private variables with _ or __)


5. Polymorphism (Using the same method name for different implementations)


6. Abstract Classes (Using ABC for defining abstract methods)

7. Magic Methods (__str__, __len__, etc.)

Magic methods (also called dunder methods) allow objects to define behavior for built-in operations like printing, addition, and length calculations.

Example: __str__ and __len__


8. Multiple Inheritance

Multiple inheritance allows a class to inherit from more than one parent class.

Example: Inheriting from Two Classes


9. Composition

Composition is when a class contains an instance of another class rather than inheriting from it.

Example: Using Composition Instead of Inheritance


Practice Questions

  1. Create a Person class with name and age attributes, and a method to display them.

  2. Implement an Employee class that inherits from Person and adds a salary attribute.

  3. Create a Shape class with a method area(), then implement Rectangle and Circle classes with their own area() calculations.


4. Building a “Hello World” API with Flask (≈8 Hours)

Simple static API

Steps to Run the API

  1. Install Flask (if not already installed):

  2. Save the following code as app.py.

  3. Run the script using:

  4. Open a browser or use Postman to test:

    • http://127.0.0.1:5000/ → Home Route

    • http://127.0.0.1:5000/data → Static JSON Data

Static API Code (app.py)

Output Examples

1. Visiting / Route

2. Visiting /data Route

This is a basic static API returning hardcoded JSON responses.


Flask API with MongoDB (Dynamic Data)

1. Install Required Libraries

2. Setup MongoDB

Ensure MongoDB is running locally or use a cloud database (MongoDB Atlas).

  • Local Connection URI: mongodb://localhost:27017/

  • Cloud Connection URI (Atlas Example): mongodb+srv://<username>:<password>@cluster.mongodb.net/<database>?retryWrites=true&w=majority

3. API Code (app.py)

4. Test API Endpoints

Start the API:

Visit:

  • http://127.0.0.1:5000/users → Fetches dynamic data from MongoDB.

5. Example Output


Database Integration: MongoDB CRUD Operations (≈6 Hours)

1. Install Required Libraries

2. API Code (app.py)

3. Testing the API

Start the API:

Create a User (POST)

Response:

Get All Users (GET)

Response Example:

Update a User (PUT)

Response:

Delete a User (DELETE)

Response:

6. Advanced Python Topics (≈8 Hours)

1. Decorators & Context Managers (Enhancing functions and managing resources)

1.1 Decorators (Modifying Function Behavior Without Changing Code)

Output:

1.2 Context Managers (with Statement for Resource Management)

  • Ensures the file is closed automatically after execution.

Practice Questions

  1. Create a decorator that logs the execution time of a function.

  2. Implement a context manager for handling database connections.


2. Iterators & Generators (Efficient looping and lazy evaluation)

2.1 Iterators (Custom Iteration Using __iter__ and __next__)

2.2 Generators (Memory-Efficient Iterators Using yield)

  • Unlike lists, generators do not store all values in memory.

Practice Questions

  1. Create an iterator that returns even numbers up to a limit.

  2. Write a generator function to yield Fibonacci numbers.


3. Testing & Debugging (Ensuring code correctness and finding errors)

3.1 Unit Testing with unittest

3.2 Debugging with pdb (Python Debugger)

Practice Questions

  1. Write unit tests for a function that checks if a string is a palindrome.

  2. Use Python's pdb module to debug a function that calculates factorial.


Machine Learning with Python (≈30–40 Hours)

This section introduces Machine Learning (ML) with Python, covering essential libraries, data preprocessing, model training, and evaluation.

1. Setting Up the ML Environment (≈2 Hours)

  • Install key libraries:

  • Importing ML essentials:

2. Data Preprocessing & Exploration (≈6 Hours)

  • Loading Data:

  • Handling Missing Values:

  • Feature Scaling:

Practice Questions

  1. Load a dataset and check for missing values.

  2. Normalize numerical features using MinMaxScaler.

3. Supervised Learning: Regression & Classification (≈10 Hours)

3.1 Linear Regression (Predicting Continuous Values)

3.2 Logistic Regression (Binary Classification)

Practice Questions

  1. Train a linear regression model to predict house prices.

  2. Build a classifier to predict if an email is spam or not.

4. Unsupervised Learning: Clustering & Dimensionality Reduction (≈8 Hours)

4.1 K-Means Clustering (Grouping Similar Data)

4.2 Principal Component Analysis (PCA) for Dimensionality Reduction

Practice Questions

  1. Apply K-Means to group customers based on purchasing behavior.

  2. Use PCA to reduce the dimensions of a dataset with 10+ features.

5. Model Evaluation & Hyperparameter Tuning (≈6 Hours)

  • Splitting Data:

  • Evaluating with Metrics:

  • Hyperparameter Tuning using GridSearchCV:

Practice Questions

  1. Evaluate a trained model using R² score or F1-score.

  2. Use GridSearchCV to optimize hyperparameters for an SVM model.

6. Deep Learning with TensorFlow & Keras (Optional) (≈8 Hours)

Practice Questions

  1. Train a neural network on the MNIST dataset.

  2. Implement a CNN for image classification.


Next Steps:

Want to work on real-world ML projects or explore NLP & Computer Vision?

Last updated