0% found this document useful (0 votes)
406 views

Mastering Python Free E-Book by Cosmicode

The document is an e-book titled 'Mastering Python' published by CosmiCode, designed to provide comprehensive knowledge and practical insights into Python programming for students and aspiring developers. It covers a wide range of topics from basic concepts to advanced programming techniques, including functions, data structures, and libraries for AI and ML, along with practical exercises and interview questions. The e-book aims to bridge the gap between theoretical knowledge and practical application in the tech industry.

Uploaded by

ghulamebilal408
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
406 views

Mastering Python Free E-Book by Cosmicode

The document is an e-book titled 'Mastering Python' published by CosmiCode, designed to provide comprehensive knowledge and practical insights into Python programming for students and aspiring developers. It covers a wide range of topics from basic concepts to advanced programming techniques, including functions, data structures, and libraries for AI and ML, along with practical exercises and interview questions. The e-book aims to bridge the gap between theoretical knowledge and practical application in the tech industry.

Uploaded by

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

COSMICODE

PRESENTS
E-BOOK

A PORTAL TO EXCELLENCE

Python

Detailed Comprehensive Practical Essential


COMPREHENSIVE KNOWLEDGE FOR STUDENTS TO THRIVE IN TECH

COSMICODE LEARNING SERIES


Mastering Python: CosmiCode Learning Series

Mastering Python
Comprehensive Learning for Future Developers

1st Edition
Published by CosmiCode
Date of Publication: 9/1/2025
Book ID: 002-ASCII-786

About CosmiCode E-Book

This book is designed by CosmiCode's team of experts to provide in-depth knowledge and
practical insights into Python programming. Whether you're a student, a tech enthusiast, or an
aspiring developer, this resource will guide you step-by-step toward mastering the language.

Contact Us

For feedback, inquiries, or to report an error, please reach out:


[email protected]
� www.cosmicode.tech

Special Note
This book is crafted with utmost care to ensure clarity and accuracy. If you find any errors,
please contact us at [email protected] so we can improve future editions.

pg. 1
Mastering Python: CosmiCode Learning Series

Table of Contents
1. Introduction to Python
o Overview of Python and its significance
o Why Python is widely adopted
o Key features of Python: Simplicity, readability, and versatility
o History and evolution of Python
o Setting up Python: IDEs, interpreters, and installation
2. Basic Concepts
o Variables and data types
o Input and output in Python
o Python operators
o Control structures: if-else, loops (for, while), and logical operators
3. Functions and Modules
o Function declarations and scope
o Arguments, keyword arguments, and default values
o Importing and using modules
o Creating custom modules
4. Data Structures
o Lists, tuples, sets, and dictionaries
o Operations on data structures
o Nested data structures
o Comprehensions and generators
5. Object-Oriented Programming (OOP) in Python
o Classes and objects
o Constructors and destructors
o Inheritance, polymorphism, and encapsulation
o Magic (dunder) methods and operator overloading
6. File Handling
o Working with files (reading, writing, appending)
o File modes and exceptions
o Handling CSV, JSON, and XML files
7. Python Libraries for AI and ML
o Overview of libraries: NumPy, Pandas, Matplotlib, TensorFlow, Scikit-learn, and
PyTorch
o How Python is shaping AI and ML development
o Real-world applications of Python in AI/ML
8. Advanced Python
o Error handling and exceptions
o Decorators and generators
o Multithreading and multiprocessing
o Python packages and virtual environments
9. Practical Exercises
o Exercise 1: Building a simple calculator
o Exercise 2: Data analysis using Pandas
o Exercise 3: Visualizing data with Matplotlib

pg. 2
Mastering Python: CosmiCode Learning Series

o Exercise 4: A simple AI/ML project


o Exercise 5: Working with APIs
10. Interview Questions
o 50 MCQs on Python basics, OOP, and advanced concepts
11. Certification Offer
o Online test for Python mastery
o Instructions on how to earn your certificate

pg. 3
Mastering Python: CosmiCode Learning Series

Introduction to CosmiCode E-Books


Welcome to the CosmiCode eBook Series, an initiative dedicated to empowering tech students,
professionals, and enthusiasts with high-quality learning resources. At CosmiCode, our mission
is to bridge the gap between theoretical knowledge and practical application, enabling learners to
confidently navigate the ever-evolving landscape of the tech industry.

Our eBooks are more than just educational resources; they are a stepping stone for anyone who
aspires to make a mark in the world of technology. With topics ranging from programming
languages and software tools to cutting-edge fields like artificial intelligence and machine
learning, the CosmiCode eBook series is designed to cater to learners of all levels—whether
you’re a beginner, intermediate, or advanced practitioner.

About the Python eBook

This Python eBook focuses on Python Programming, a language that has revolutionized modern
software development. From its origins as a simple scripting tool to its widespread applications
in web development, data science, artificial intelligence, and automation, Python remains a
versatile and essential language in the tech world. With a blend of theoretical explanations and
practical examples, this book will take you from the basics of Python to its advanced concepts,
all while maintaining clarity and accessibility.

Quality and Accuracy

Every CosmiCode eBook is crafted by a team of experts with years of experience in their
respective fields. Each topic is carefully researched, written, and reviewed multiple times to
ensure accuracy, clarity, and relevance. While we strive to provide error-free content, we
understand that occasional mistakes may happen. If you find any errors, inconsistencies, or areas
for improvement, we encourage you to report them to CosmiCode at [email protected].
Your feedback helps us maintain the quality and reliability of our resources.

pg. 4
Mastering Python: CosmiCode Learning Series

Introduction to Python
History and Evolution of Python

Python is a versatile, high-level programming language created by Guido van Rossum in 1991.
Its design philosophy emphasizes simplicity and readability, making it an ideal choice for both
beginners and seasoned developers. The name "Python" was inspired by the comedy series
Monty Python's Flying Circus, reflecting the language's focus on being fun and accessible.

Python was designed to address limitations in earlier languages by providing a clear and easy-to-
learn syntax. Over the years, it has evolved into one of the most popular programming languages
worldwide, powering applications in web development, data analysis, artificial intelligence, and
more.

The first major version, Python 1.0, was released in 1991 and included features like exception
handling and functions. Python 2.0, introduced in 2000, added list comprehensions and garbage
collection. In 2008, Python 3.0 addressed inconsistencies in the language and introduced
significant improvements, though it broke backward compatibility with Python 2.

Python continues to evolve with regular updates, offering improved performance, features, and
libraries. Its active community and open-source nature ensure that Python remains at the
forefront of modern programming.

Why Learn Python?

Python is one of the most widely used programming languages today due to its simplicity and
versatility. Here’s why learning Python is essential:

1. Ease of Learning: Python's syntax is designed to be intuitive and beginner-friendly, making it a


perfect first language for aspiring programmers.
2. Versatility: Python can be used for a wide variety of applications, including web development,
data science, artificial intelligence, and more.
3. Extensive Libraries and Frameworks: Libraries like NumPy, Pandas, TensorFlow, and
frameworks like Django and Flask simplify complex tasks.
4. Community Support: Python has a vast and active global community, ensuring abundant
resources, tutorials, and forums for learning and troubleshooting.
5. Demand in the Industry: Python's use in emerging fields like data analytics and machine
learning has made it one of the most sought-after skills in the job market.

Key Features of Python

Python stands out due to its rich feature set and adaptability to various domains:

 Simplicity: Python’s syntax is straightforward and mirrors natural language, allowing developers
to focus on problem-solving rather than syntax.

pg. 5
Mastering Python: CosmiCode Learning Series

 Cross-Platform Compatibility: Python code runs seamlessly across platforms like Windows,
macOS, and Linux with minimal changes.
 Extensive Standard Library: Python comes with a robust standard library that includes modules
for handling files, databases, web development, and more.
 Dynamic Typing: Python eliminates the need for explicit type declarations, making it highly
flexible.
 Support for Multiple Paradigms: Python supports object-oriented, procedural, and functional
programming styles, allowing developers to choose the best approach for their project.
 Scalability: Python is used to develop small scripts as well as large-scale applications,
demonstrating its ability to scale efficiently.

Getting Started with Python

To start working with Python, you’ll need the following tools:

1. Python Interpreter: Download and install Python from the official website, python.org.
2. Integrated Development Environment (IDE): Use IDEs like PyCharm, Visual Studio Code, or
Jupyter Notebook for an optimized coding experience.
3. Text Editors: Lightweight editors such as Sublime Text, Atom, or Notepad++ can also be used
for writing Python code.

Once you have your tools installed, you can begin writing your first Python program.

pg. 6
Mastering Python: CosmiCode Learning Series

Chapter 1: Basic Concepts


Python is a versatile and powerful programming language that provides simplicity in syntax
while offering robust capabilities. In this chapter, we will explore the foundational building
blocks of Python, including variables, data types, input/output mechanisms, operators, and
control structures. These concepts form the backbone of Python programming, enabling
developers to create logical and interactive programs.

Variables and Data Types

A variable in Python is a named location in memory used to store data. Unlike many other
programming languages, Python does not require specifying the type of variable beforehand. The
type of data is automatically inferred when a value is assigned.

What are Variables?

 A variable is like a container for storing data values.


 Python uses dynamic typing, meaning the type of the variable is determined when a value is
assigned.
 Variables can hold different types of data, such as numbers, text, and more.

Common Data Types in Python

Python supports several built-in data types that are used to define the nature of the data stored in
variables. The main types include:

Data Type Description Example

 int Integer values. x = 10

 float Decimal values. y = 5.75

 str String of characters. name = "CosmiCode"

 bool Boolean values (True or False). status = False

 list Ordered collection of items. items = [1, 2, 3]

 dict Key-value pairs. data = {"a": 1}

pg. 7
Mastering Python: CosmiCode Learning Series

Example:

x = 10 # Integer
pi = 3.14 # Floating-Point
name = "Python" # String
is_active = True # Boolean

Input and Output in Python

Python makes it easy to interact with users through input and output.

Getting User Input

 Python uses the input() function to capture user input.


 By default, the input is stored as a string, which can be converted to other types if needed.

Displaying Output

 The print() function is used to display messages or results on the screen.


 It can output text, variables, or even formatted strings.

Example:

name = input("Enter your name: ") # Taking input


print("Hello, " + name + "!") # Displaying output

Python Operators

Operators are special symbols that perform operations on variables and values. Python provides a
variety of operators to handle arithmetic, comparisons, logical evaluations, and more.

Types of Operators

1. Arithmetic Operators: Perform basic mathematical operations like addition (+), subtraction (-),
multiplication (*), and division (/).
2. Comparison Operators: Compare two values and return True or False, e.g., >, <, ==, !=.
3. Logical Operators: Combine multiple conditions using and, or, and not.

Example:

a = 10
b = 20
print(a + b) # Arithmetic
print(a > b) # Comparison
print(a < b and b > 15) # Logical

pg. 8
Mastering Python: CosmiCode Learning Series

Control Structures

Conditional Statements: if-else

Use if, elif, and else to execute code based on conditions.

Example:

age = 18
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 and while

1. For Loop: Used to iterate over a sequence (like a list, string, or range).

Example:

for i in range(5): # Iterates from 0 to 4


print(i)

2. While Loop: Repeats as long as a condition is True.

Example:

count = 0
while count < 5:
print(count)
count += 1

Logical Operators in Control Structures

Combine conditions in control structures using logical operators (and, or, not):

Example:

age = 20
if age > 18 and age < 25:
print("You are in your early 20s.")

Summary

pg. 9
Mastering Python: CosmiCode Learning Series

In this chapter, we covered the basic building blocks of Python, including variables, data types,
input/output operations, operators, and control structures. These concepts lay the groundwork for
more advanced topics, allowing you to build programs that interact with users, make decisions,
and perform repetitive tasks efficiently. Mastering these basics is the first step in becoming
proficient in Python programming.

pg. 10
Mastering Python: CosmiCode Learning Series

Chapter 2: Functions and Modules


Function Declarations and Scope

A function in Python is a block of code that only runs when it is called. It can accept input via
parameters and may return output. Functions allow you to reuse code, reducing redundancy and
improving clarity.

What is a Function?

• A function is a reusable piece of code that can perform a specific task. • Functions can accept
parameters (input values) and return a result (output). • Functions help break down large
programs into smaller, manageable pieces of code.

Declaring a Function

In Python, functions are declared using the def keyword followed by the function name and
parameters (if any). Here's a simple example:

def greet(name):
print(f"Hello, {name}!")

In this example:

 greet is the function name.


 name is the parameter, which is expected to be passed when the function is called.

Calling a Function

To call the function and execute the code within it, simply use the function name followed by the
arguments in parentheses:

greet("Alice") # Output: Hello, Alice!

Function Scope

Scope refers to the area of a program where a variable can be accessed. Python has different
scopes for variables, which can be local or global.

 Local Scope: Variables defined inside a function are local to that function.
 Global Scope: Variables defined outside of any function are global and accessible to all functions
in the program.

pg. 11
Mastering Python: CosmiCode Learning Series

x = 10 # Global variable

def test_scope():
y=5 # Local variable
print(x) # Accessing global variable

test_scope() # Output: 10
# print(y) # Error: NameError: name 'y' is not defined

Arguments, Keyword Arguments, and Default Values

In Python, functions can accept various types of arguments:

1. Positional Arguments: These are the arguments that must be passed in the same order as the
parameters in the function definition.
2. Keyword Arguments: These are arguments that are passed by explicitly stating the parameter
name.
3. Default Arguments: These are arguments that have default values assigned, and they don't need
to be passed by the caller if not required.

Example with Positional and Keyword Arguments


def display_info(name, age):
print(f"Name: {name}, Age: {age}")

# Positional arguments
display_info("John", 25)

# Keyword arguments
display_info(age=30, name="Alice")

Example with Default Arguments


def greet(name="Guest"):
print(f"Hello, {name}!")

greet("Bob") # Output: Hello, Bob!


greet() # Output: Hello, Guest!

Importing and Using Modules

Modules in Python are files containing Python code that can be reused in other programs. By
using modules, you can organize your code into separate files, making it more modular and
easier to maintain.

Importing Built-in Modules

Python provides several built-in modules like math, random, etc. To use a module, simply import it:

pg. 12
Mastering Python: CosmiCode Learning Series

import math

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

Creating and Using Custom Modules

You can also create your own modules by saving Python code in a .py file. Once saved, you can
import and use them in other Python files.

 mymodule.py (Custom Module):

def add(a, b):


return a + b

def subtract(a, b):


return a - b

 main.py (Main Program):

import mymodule

result = mymodule.add(3, 5)
print(result) # Output: 8

Practical Example: Functions and Modules in Action

Let’s combine functions and modules in a practical scenario. Imagine you’re building a basic
arithmetic calculator with separate functions for each operation.

 arithmetic.py (Module):

def add(a, b):


return a + b

def subtract(a, b):


return a - b

def multiply(a, b):


return a * b

def divide(a, b):


if b == 0:
return "Cannot divide by zero"
return a / b

pg. 13
Mastering Python: CosmiCode Learning Series

 calculator.py (Main Program):

import arithmetic

x, y = 10, 5

print("Addition:", arithmetic.add(x, y))


print("Subtraction:", arithmetic.subtract(x, y))
print("Multiplication:", arithmetic.multiply(x, y))
print("Division:", arithmetic.divide(x, y))

This example demonstrates how to create functions for different operations and organize them
into a module, making your code cleaner and more reusable.

Summary

In this chapter, we explored functions and modules in Python. Functions allow you to organize
code into reusable blocks, while modules help structure your code into separate files. By using
functions and modules, you can create more maintainable and efficient Python programs.
Understanding these concepts is crucial for writing well-structured Python code that can scale
and be easily managed.

pg. 14
Mastering Python: CosmiCode Learning Series

Chapter 3: Data Structures


In Python, data structures are essential for organizing, storing, and managing data in a way that
allows for efficient access and modification. Data structures are designed to store collections of
data and can be implemented in various forms depending on the specific needs of your program.
In this chapter, we will cover the foundational data structures available in Python: lists, tuples,
sets, and dictionaries. You will also learn about the operations and use cases for each data
structure, and how to work with them effectively.

Lists, Tuples, Sets, and Dictionaries

Python provides several built-in data structures that help organize data in different ways. Let’s
discuss each one in more detail.

Lists

A list in Python is an ordered collection of items that can be modified. Lists can hold a variety of
data types, such as integers, strings, and other objects, and are the most versatile data structure in
Python. Lists are defined using square brackets [] and the items within the list are separated by
commas.

Key Characteristics:

 Ordered: The order of items in a list is maintained.


 Mutable: Items in a list can be changed after it is created.
 Heterogeneous: A list can contain items of different data types.

Use Case: Lists are useful when you need to store a collection of items in a specific order and
want the flexibility to modify those items later.

Example:

my_list = [1, 2, 3, 4, 5]
my_list.append(6) # Adds an item to the list

Tuples

A tuple is similar to a list, but unlike lists, tuples are immutable. This means once a tuple is
created, its elements cannot be modified. Tuples are defined using parentheses ().

Key Characteristics:

 Ordered: The order of elements is preserved.


 Immutable: Once a tuple is created, its values cannot be altered.
 Heterogeneous: A tuple can store multiple types of data.

pg. 15
Mastering Python: CosmiCode Learning Series

Use Case: Tuples are useful when you need to store data that should not change. They can be
used to store fixed data like coordinates or settings.

Example:

my_tuple = (1, 2, 3, 4, 5)
# my_tuple[2] = 10 # This will result in a TypeError because tuples are immutable

Sets

A set is an unordered collection of unique items. The main difference between sets and lists is
that sets do not maintain order and do not allow duplicates. Sets are defined using curly braces {}.

Key Characteristics:

 Unordered: The items in a set are not stored in any particular order.
 Mutable: Items can be added or removed from a set.
 Unique: Sets do not allow duplicate values.

Use Case: Sets are useful when you want to store unique items and don't care about the order of
those items. They are commonly used for operations such as union, intersection, and difference
between two sets.

Example:

my_set = {1, 2, 3, 4, 5}
my_set.add(6) # Adds an element to the set

Dictionaries

A dictionary is a collection of key-value pairs. Each item in a dictionary has a unique key that is
mapped to a specific value. Dictionaries are defined using curly braces {}, with each key-value
pair separated by a colon.

Key Characteristics:

 Unordered: The key-value pairs are not stored in any particular order (though recent versions of
Python maintain insertion order).
 Mutable: Keys and values can be added, modified, or removed after creation.
 Key-Value Pairs: Each item is stored as a pair of keys and corresponding values, where the key
is unique.

Use Case: Dictionaries are ideal when you need to store and retrieve data by a specific identifier
(key), like storing information about a person using their name as the key.

pg. 16
Mastering Python: CosmiCode Learning Series

Example:

my_dict = {"name": "Alice", "age": 25}


my_dict["age"] = 26 # Modifying the value associated with the key "age"

Operations on Data Structures

Each data structure supports various operations that help modify or retrieve information from the
structure. Let's look at common operations for each data structure.

List Operations

 Appending Items: my_list.append(item) - Adds an item to the end of the list.


 Removing Items: my_list.remove(item) - Removes the first occurrence of an item.
 Slicing: my_list[start:end] - Retrieves a sublist from index start to end.
 Length: len(my_list) - Returns the number of items in the list.

Tuple Operations

 Concatenation: my_tuple + another_tuple - Combines two tuples.


 Repetition: my_tuple * n - Repeats the tuple n times.
 Length: len(my_tuple) - Returns the number of elements in the tuple.

Set Operations

 Union: set1 | set2 - Combines all elements from both sets.


 Intersection: set1 & set2 - Returns elements common to both sets.
 Difference: set1 - set2 - Returns elements present in set1 but not in set2.

Dictionary Operations

 Accessing Values: my_dict[key] - Retrieves the value associated with a specific key.
 Modifying Values: my_dict[key] = new_value - Updates the value for a given key.
 Adding Key-Value Pairs: my_dict[new_key] = value - Adds a new key-value pair.
 Deleting Items: del my_dict[key] - Removes the item with the given key.

Nested Data Structures

Python allows you to combine different data structures. This is called nesting, and it lets you
create more complex data models.

Example of Nested List:


nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(nested_list[1][2]) # Output: 6 (Accessing the 3rd item of the second list)

pg. 17
Mastering Python: CosmiCode Learning Series

Example of Nested Dictionary:


nested_dict = {"person1": {"name": "Alice", "age": 25}, "person2": {"name": "Bob", "age": 30}}
print(nested_dict["person1"]["name"]) # Output: Alice

Comprehensions and Generators

Comprehensions provide a concise way to create lists, sets, or dictionaries in Python, especially
when you want to filter or transform data in one line.

List Comprehension:
squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Set Comprehension:
unique_squares = {x**2 for x in range(10)}
print(unique_squares) # Output: {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}

Dictionary Comprehension:
square_dict = {x: x**2 for x in range(5)}
print(square_dict) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Generator Expressions:

Generators allow for more memory-efficient iteration over sequences.

gen = (x**2 for x in range(10))


for num in gen:
print(num)

Summary

In this chapter, we explored the key data structures in Python—lists, tuples, sets, and dictionaries.
Each of these structures has its unique characteristics and applications, depending on the nature
of your data and the operations you need to perform. Understanding when and how to use these
structures is critical for writing efficient and clean Python code. Additionally, we discussed how
to use comprehensions and generators for more concise and efficient code when working with
collections of data. Mastering these data structures is a key step towards becoming proficient in
Python programming.

pg. 18
Mastering Python: CosmiCode Learning Series

Chapter 4: Object-Oriented Programming


(OOP) in Python
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of
"objects," which are instances of classes. Python is an object-oriented language, and OOP is a
powerful tool that helps in organizing and structuring code efficiently. This chapter will cover
key OOP concepts such as classes, objects, inheritance, polymorphism, and more. We will also
introduce file handling as part of real-world Python applications.

Classes and Objects

In Python, classes are blueprints for creating objects. An object is an instance of a class,
representing a real-world entity.

Class Definition:

A class in Python is defined using the class keyword followed by the class name and a colon. The
body of the class contains its attributes (data) and methods (functions).

Creating a Class:
class Person:
# Constructor method
def __init__(self, name, age):
self.name = name
self.age = age

# Method to display info


def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")

In the example above, we defined a Person class with a constructor method (__init__) to initialize
attributes, and a greet() method to display information about the person.

Creating an Object:
person1 = Person("Alice", 30)
person1.greet() # Output: Hello, my name is Alice and I am 30 years old.

Here, person1 is an object created from the Person class, and we call the greet() method to print the
person's details.

Constructors and Destructors

 Constructor (__init__): The constructor is a special method in Python that is called when
an object is created. It initializes the object's state (attributes).
 Destructor (__del__): The destructor is a special method called when an object is
destroyed. It is used for cleanup operations.

pg. 19
Mastering Python: CosmiCode Learning Series

Example:
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
print(f"Car {self.make} {self.model} is created.")

def __del__(self):
print(f"Car {self.make} {self.model} is being destroyed.")

# Creating and destroying an object


car1 = Car("Toyota", "Corolla")
del car1 # The destructor will be called

In this example, when the Car object is created, the __init__ constructor is called to initialize the
attributes, and when the object is deleted, the __del__ destructor is invoked.

Inheritance, Polymorphism, and Encapsulation

Inheritance

Inheritance allows one class (child class) to inherit the attributes and methods from another class
(parent class). This promotes code reuse and allows for hierarchical relationships between
classes.

Example:
class Animal:
def speak(self):
print("Animal speaks")

class Dog(Animal):
def speak(self):
print("Woof! Woof!")

# Creating an object of the Dog class


dog = Dog()
dog.speak() # Output: Woof! Woof!

In this example, Dog is a subclass of Animal, and it overrides the speak() method.

Polymorphism

Polymorphism refers to the ability of different classes to provide different implementations of


the same method. This allows the same method to behave differently based on the object that is
calling it.

pg. 20
Mastering Python: CosmiCode Learning Series

Encapsulation

Encapsulation is the concept of hiding the internal state of an object and only exposing necessary
functionality. This is achieved by using private variables and methods (denoted by a leading
underscore _ or __).

Example of Encapsulation:
class BankAccount:
def __init__(self, balance=0):
self.__balance = balance # Private attribute

def deposit(self, amount):


if amount > 0:
self.__balance += amount

def get_balance(self):
return self.__balance

# Creating a BankAccount object


account = BankAccount()
account.deposit(100)
print(account.get_balance()) # Output: 100

In this example, __balance is a private attribute, and it can only be accessed through the deposit()
and get_balance() methods, ensuring controlled access to the balance.

Magic (Dunder) Methods and Operator Overloading

Magic methods (or dunder methods) are special methods that allow you to define the behavior of
your objects for built-in Python operations like addition, string representation, and comparisons.

Common Magic Methods:

 __init__(self): Constructor
 __str__(self): String representation of the object
 __add__(self, other): Addition operator

Example of Magic Methods:


class Point:
def __init__(self, x, y):
self.x = x
self.y = y

def __str__(self):
return f"Point({self.x}, {self.y})"

def __add__(self, other):


return Point(self.x + other.x, self.y + other.y)

# Creating Point objects


p1 = Point(2, 3)

pg. 21
Mastering Python: CosmiCode Learning Series

p2 = Point(5, 7)

# Adding two points


p3 = p1 + p2
print(p3) # Output: Point(7, 10)

In this example, the __str__ method provides a custom string representation of the object, and the
__add__ method allows for operator overloading of the + operator.

Operator Overloading

Operator overloading allows us to redefine how operators (like +, -, *, //, etc.) behave when
used with objects of a custom class. By overloading these operators, we can make our class
instances behave like built-in data types in terms of operations.

Overloading Arithmetic Operators

Python provides various magic methods to overload arithmetic operators.

 Addition (+): __add__


 Subtraction (-): __sub__
 Multiplication (*): __mul__
 Division (/): __truediv__
 Floor Division (//): __floordiv__
 Modulus (%): __mod__
 Exponentiation (**): __pow__

Example:
class ComplexNumber:
def __init__(self, real, imag):
self.real = real
self.imag = imag

def __add__(self, other):


return ComplexNumber(self.real + other.real, self.imag + other.imag)

def __str__(self):
return f"{self.real} + {self.imag}i"

c1 = ComplexNumber(1, 2)
c2 = ComplexNumber(3, 4)
c3 = c1 + c2 # Using the + operator for ComplexNumber
print(c3) # Output: 4 + 6i

In this example, we've overloaded the + operator for the ComplexNumber class. When we add two
ComplexNumber objects, the __add__ method is invoked to add their real and imaginary parts.

Summary

pg. 22
Mastering Python: CosmiCode Learning Series

In this chapter, we explored key concepts of Object-Oriented Programming in Python, including


defining classes and objects, using constructors and destructors, understanding inheritance,
polymorphism, and encapsulation, and leveraging magic methods for operator overloading.
Mastery of OOP will enhance your ability to build scalable, maintainable, and robust
applications in Python.

pg. 23
Mastering Python: CosmiCode Learning Series

Chapter 5: File Handling in Python


File handling is an essential concept in programming, allowing us to interact with files for
reading, writing, and processing data. Python provides built-in functions to work with different
file formats and supports various file operations. In this chapter, we'll explore how to manage
files, handle exceptions, and work with specific file formats like CSV, JSON, and XML.

1. Working with Files (Reading, Writing, Appending)

Python provides several built-in functions to open, read, write, and manipulate files. The most
common functions used for file handling are open(), read(), write(), and close().

Opening a File

To work with a file, we first need to open it using the open() function. The open() function takes
two parameters:

 File name: The name of the file you want to open.


 Mode: The mode in which the file will be opened (read, write, append, etc.).

The general syntax is:

file = open("filename.txt", "r") # Open in read mode

File Modes

File modes determine the purpose of opening a file. Some common modes are:

 r: Read (default mode). Opens the file for reading.


 w: Write. Opens the file for writing (creates a new file or truncates an existing file).
 a: Append. Opens the file for writing, but appends to the end of the file instead of overwriting.
 b: Binary mode. Used for non-text files (e.g., images).
 rb, wb, ab: Binary modes for reading, writing, and appending.

Reading from a File

Once the file is opened, we can read its contents using various methods:

 read(): Reads the entire file as a string.


 readline(): Reads one line at a time.
 readlines(): Reads all lines into a list.

pg. 24
Mastering Python: CosmiCode Learning Series

Example:

# Reading a file

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


content = file.read() # Read the entire file
print(content)

Writing to a File

To write data to a file, use the write() method. If the file does not exist, it will be created.

# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, World!")

Appending to a File

Appending allows us to add data to the end of the file without overwriting its contents.

# Appending to a file
with open("example.txt", "a") as file:
file.write("\nAppended text!")

Closing the File

Once the file operations are complete, it's important to close the file using file.close() to free up
system resources.

file.close()

However, the with open() context manager automatically handles closing the file once the block of
code is executed.

2. File Modes and Exceptions

When working with files, errors may occur due to issues like missing files, incorrect file
permissions, or attempting to read from a file that doesn’t exist. To handle these errors gracefully,
Python provides exception handling mechanisms.

Common File Handling Exceptions

 FileNotFoundError: Raised when attempting to open a file that does not exist.
 PermissionError: Raised when there are insufficient permissions to access the file.
 IOError: Raised when an input/output operation fails.

pg. 25
Mastering Python: CosmiCode Learning Series

Using Try-Except Blocks

To prevent your program from crashing, use try-except blocks to handle exceptions.

Example:

try:
with open("example.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("File not found. Please check the file path.")
except PermissionError:
print("You do not have permission to read the file.")
except Exception as e:
print(f"An unexpected error occurred: {e}")

3. Handling CSV, JSON, and XML Files

Python provides various modules to work with different file formats such as CSV, JSON, and
XML. Each of these formats is commonly used to store structured data, and Python’s standard
library provides tools to make their handling easy and efficient.

CSV (Comma-Separated Values)

CSV files store data in a tabular format where values are separated by commas. Python’s csv
module provides tools for reading and writing CSV files.

Reading CSV Files


import csv

# Reading a CSV file


with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row) # Each row is a list

Writing CSV Files


import csv

# Writing to a CSV file


data = [["Name", "Age"], ["Alice", 30], ["Bob", 25]]
with open("output.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)

pg. 26
Mastering Python: CosmiCode Learning Series

JSON (JavaScript Object Notation)

JSON is a popular format for storing and exchanging data, especially in web applications. The
json module in Python allows easy parsing and serialization of JSON data.

Reading JSON Files


import json

# Reading a JSON file


with open("data.json", "r") as file:
data = json.load(file)
print(data) # Returns the content as a Python dictionary

Writing JSON Files


import json

# Writing to a JSON file


data = {"name": "Alice", "age": 30}
with open("output.json", "w") as file:
json.dump(data, file)

XML (eXtensible Markup Language)

XML is a markup language that is commonly used for data exchange. Python’s
xml.etree.ElementTree module is used to parse and create XML files.

Reading XML Files


import xml.etree.ElementTree as ET

# Parsing an XML file


tree = ET.parse("data.xml")
root = tree.getroot()

# Iterating over the XML elements


for child in root:
print(child.tag, child.attrib)

Writing XML Files


import xml.etree.ElementTree as ET

# Creating an XML structure


data = ET.Element("data")
item1 = ET.SubElement(data, "item")
item1.text = "Item 1"

tree = ET.ElementTree(data)
tree.write("output.xml")

pg. 27
Mastering Python: CosmiCode Learning Series

Summary

In this chapter, we learned how to work with files in Python, including opening, reading, writing,
and appending files. We also explored file modes and exceptions to handle errors effectively.
Additionally, we covered how to work with various file formats such as CSV, JSON, and XML.
Understanding file handling is fundamental for interacting with data and creating efficient
programs that read from and write to files.

pg. 28
Mastering Python: CosmiCode Learning Series

Chapter 7: Python Libraries for AI and ML


Python is one of the most widely used programming languages for Artificial Intelligence (AI)
and Machine Learning (ML) due to its simplicity, versatility, and the powerful libraries it offers.
These libraries provide specialized functions and tools to handle the complex data operations,
model building, and computation needed for AI and ML tasks.

Overview of Libraries:

1. NumPy (Numerical Python)

 Purpose: NumPy is a fundamental package for scientific computing. It provides support


for large, multi-dimensional arrays and matrices, along with a collection of mathematical
functions to operate on these arrays.
 Real-World Usage: Used for fast computation in ML algorithms, matrix manipulation,
and data preprocessing.

Code Example:

import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr + 2) # [3 4 5 6]

2. Pandas

 Purpose: Pandas is designed for data manipulation and analysis. It provides two primary
data structures: Series (1D) and DataFrame (2D) which are ideal for handling and analyzing
structured data like tables.
 Real-World Usage: Preprocessing data, cleaning datasets, handling missing data, and
feature engineering in ML tasks.

Code Example:

import pandas as pd
data = {'Name': ['John', 'Anna', 'Peter'], 'Age': [28, 22, 35]}
df = pd.DataFrame(data)
print(df.head()) # Displays first 5 rows of the dataframe

pg. 29
Mastering Python: CosmiCode Learning Series

3. Matplotlib

 Purpose: Matplotlib is a plotting library for creating static, animated, and interactive
visualizations in Python. It is primarily used for data visualization to interpret the data
and results of models.
 Real-World Usage: Visualizing datasets, plotting training and validation curves, and
model evaluation.

Code Example:

import matplotlib.pyplot as plt


x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y)
plt.title('Sample Plot')
plt.show()

4. TensorFlow

 Purpose: TensorFlow is a powerful open-source framework developed by Google for


machine learning and deep learning. It allows users to design and train deep neural
networks, and deploy them on various platforms.
 Real-World Usage: Building and training neural networks, natural language processing
(NLP), image classification, and computer vision.

Code Example:

import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Dense(32, activation='relu', input_shape=(8,)),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

5. Scikit-learn

 Purpose: Scikit-learn is a simple and efficient tool for data mining and data analysis. It
supports a wide range of supervised and unsupervised learning algorithms, along with
tools for model evaluation and selection.
 Real-World Usage: Classification, regression, clustering, model selection, and data
preprocessing.

pg. 30
Mastering Python: CosmiCode Learning Series

Code Example:

from sklearn.datasets import load_iris


from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2)
model = LogisticRegression()
model.fit(X_train, y_train)
print(model.score(X_test, y_test)) # Accuracy of the model

6. PyTorch

 Purpose: PyTorch is a deep learning framework developed by Facebook. It provides a


flexible, dynamic computational graph for building and training deep learning models.
 Real-World Usage: Used for deep learning, reinforcement learning, and research-
oriented projects due to its dynamic graph feature, which makes debugging easier.

Code Example:

import torch
import torch.nn as nn
model = nn.Sequential(
nn.Linear(5, 10),
nn.ReLU(),
nn.Linear(10, 3)
)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

How Python is Shaping AI and ML Development

Python has solidified its position as a dominant programming language in Artificial Intelligence
(AI) and Machine Learning (ML) development due to several critical advantages:

1. Simple and Readable Syntax

Python's easy-to-understand syntax reduces the complexity of coding for AI and ML. Developers
can focus on solving intricate AI/ML problems without worrying about syntax intricacies, which
boosts productivity and collaboration.

2. Rich Ecosystem of Libraries

Python boasts a vast ecosystem of libraries tailored for AI and ML. Popular libraries include
TensorFlow and PyTorch for deep learning, Scikit-learn for traditional machine learning, NumPy
for numerical computing, and Pandas for data manipulation. These tools allow developers to
build models without reinventing the wheel.

pg. 31
Mastering Python: CosmiCode Learning Series

3. Community and Support

Python has one of the largest and most active developer communities. Continuous contributions
from developers worldwide ensure that libraries remain up-to-date, bugs are fixed promptly, and
support is readily available for learners and professionals alike.

4. Integration with Other Tools

Python seamlessly integrates with other tools essential for AI/ML pipelines, such as SQL for
databases, Matplotlib for data visualization, and big data tools like Hadoop and Spark. This
makes Python highly versatile for handling data, training models, and deploying solutions.

5. Open-Source

Both Python and its libraries are open-source, making them accessible to developers and
organizations worldwide. This encourages collaboration and innovation in the AI/ML space
while reducing costs.

Real-World Applications of Python in AI/ML

Python plays a pivotal role in diverse industries and use cases, offering transformative solutions
across domains:

1. Natural Language Processing (NLP)

Python libraries like NLTK, spaCy, and TextBlob power tasks like text analysis, sentiment
analysis, language translation, and the development of intelligent chatbots.

2. Computer Vision

Python frameworks such as OpenCV, TensorFlow, and PyTorch enable image classification,
object detection, facial recognition, and video analytics, transforming fields like security and
entertainment.

3. Healthcare

AI and ML models built with Python are revolutionizing healthcare through predictive
diagnostics, personalized medicine, and drug discovery. For example, Python is used in early
disease detection, patient monitoring, and medical imaging.

4. Finance

Python is extensively used in algorithmic trading, fraud detection, and financial forecasting. Its
data manipulation and machine learning capabilities make it ideal for handling complex financial
datasets and building predictive models.

pg. 32
Mastering Python: CosmiCode Learning Series

5. Autonomous Vehicles

Python enables the development of self-driving car technology by facilitating tasks such as
image processing, object detection, and path planning. Deep learning frameworks like
TensorFlow and PyTorch are instrumental in these advancements.

6. Speech Recognition

Python libraries such as SpeechRecognition and PyAudio are used to develop systems that can
transcribe speech into text, generate voice responses, and enable voice commands in virtual
assistants.

7. Robotics

Python is employed in robotics to control robots, process sensor data, and implement automation.
Tasks like pathfinding, object manipulation, and real-time decision-making rely heavily on
Python.

Python’s simplicity, powerful libraries, and strong community make it the backbone of AI and
ML development, empowering developers to create innovative solutions that address real-world
challenges.

Conclusion

Python’s extensive library ecosystem, ease of use, and integration capabilities make it the ideal
choice for AI and ML development. With libraries such as NumPy, Pandas, TensorFlow, Scikit-
learn, and PyTorch, Python has empowered developers and researchers to push the boundaries of
AI and ML in various industries, from healthcare and finance to robotics and self-driving cars.
Whether it's for prototyping models, preprocessing data, or building complex deep learning
systems, Python continues to be the backbone of modern AI/ML development.

pg. 33
Mastering Python: CosmiCode Learning Series

Chapter 8: Advanced Python


1. Error Handling and Exceptions

Introduction

Errors can disrupt the normal flow of a program. Python provides a robust error-handling
mechanism to ensure programs handle exceptions gracefully instead of abruptly stopping
execution.

Types of Errors

 Syntax Errors: Mistakes in the syntax, detected before execution (e.g., missing colons or
incorrect indentation).
 Exceptions: Runtime errors that occur when the program is running (e.g., ValueError,
FileNotFoundError, ZeroDivisionError).

Handling Exceptions

Python uses the try-except block to handle exceptions. Additional clauses like else and finally make
the error-handling process more structured.

 try: Executes the code that may raise an exception.


 except: Handles specific exceptions when they occur.
 else: Runs only if no exception is raised in the try block.
 finally: Executes regardless of whether an exception occurs (e.g., to close files or clean up
resources).

Practical Applications

1. File Handling: Handle missing or inaccessible files gracefully.


2. User Input Validation: Ensure only valid input is processed.
3. Database Operations: Manage connection failures or query errors.

Example
try:
file = open("data.txt", "r")
print(file.read())
except FileNotFoundError:
print("The file does not exist.")
finally:
print("Error handling complete.")

2. Decorators and Generators

pg. 34
Mastering Python: CosmiCode Learning Series

Decorators

Decorators are powerful tools that modify or enhance the behavior of functions or methods
dynamically without altering their structure.

 Key Use Cases:


o Logging function calls.
o Authenticating users.
o Measuring execution time of functions.
 How It Works:
A decorator takes a function, wraps it in another function (the wrapper), and returns the
modified function.

Example
def logger(func):
def wrapper():
print("Function is about to run.")
func()
print("Function has finished running.")
return wrapper

@logger
def greet():
print("Hello, World!")

greet()

Generators

Generators are functions that yield values one at a time, making them memory-efficient for
processing large datasets.

 Advantages:
o Generate data on demand.
o Save memory by avoiding storing large datasets in memory.
 Applications:
o Reading large files line-by-line.
o Streaming data for machine learning or data analysis.

Example
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b

for number in fibonacci(5):


print(number)

pg. 35
Mastering Python: CosmiCode Learning Series

3. Multithreading and Multiprocessing

Multithreading

Multithreading allows a program to perform multiple tasks simultaneously. It is ideal for I/O-
bound tasks, like reading files or making API calls.

 Use Cases:
o Fetching data from multiple APIs.
o Reading multiple files concurrently.
 Advantages:
o Enhances application responsiveness.
o Saves time on I/O operations.

Example
import threading

def print_numbers():
for i in range(5):
print(i)

thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()

Multiprocessing

Multiprocessing involves running tasks in separate processes, utilizing multiple CPU cores. It is
ideal for CPU-bound tasks, like heavy computations or simulations.

 Use Cases:
o Training machine learning models.
o Performing large matrix computations.
 Advantages:
o Speeds up computation by using all available cores.
o Avoids Python’s Global Interpreter Lock (GIL).

Example
import multiprocessing

def square(n):
print(f"Square of {n}: {n * n}")

if __name__ == "__main__":
process = multiprocessing.Process(target=square, args=(4,))
process.start()
process.join()

4. Python Packages and Virtual Environments

pg. 36
Mastering Python: CosmiCode Learning Series

Python Packages

A Python package is a collection of modules. Python’s vast ecosystem of libraries allows


developers to build advanced applications quickly. Commonly used packages include:

 NumPy: Numerical computations.


 Pandas: Data manipulation.
 Matplotlib: Data visualization.
 Requests: HTTP requests handling.

Creating and Using Packages

Packages are created by organizing Python modules in directories with an __init__.py file. They
can be installed using pip, Python’s package manager.

Virtual Environments

Virtual environments isolate dependencies for different projects. This avoids version conflicts
when working on multiple projects.

Creating a Virtual Environment:

python -m venv env_name

Activating a Virtual Environment:

On Windows:

env_name\Scripts\activate

On macOS/Linux:

source env_name/bin/activate

Installing Packages in a Virtual Environment:

pip install package_name

Summary

This chapter introduced key advanced Python concepts essential for writing efficient and
professional programs. Error handling ensures programs run reliably by managing exceptions
gracefully, while decorators enhance the functionality of functions dynamically, and generators
optimize memory usage by generating data on demand. Multithreading and multiprocessing
enable efficient concurrent and parallel processing, making programs faster and more responsive.
Python packages offer a rich ecosystem of tools for scalable development, while virtual

pg. 37
Mastering Python: CosmiCode Learning Series

environments help manage dependencies effectively across projects. Mastering these advanced
concepts equips developers with the skills to build resilient, scalable, and maintainable Python
applications.

pg. 38
Mastering Python: CosmiCode Learning Series

Practical Exercises
To truly master Python programming, it's important to apply your knowledge in real-world
programming scenarios. Below are practical exercises ranging from beginner-level tasks to more
advanced projects, designed to reinforce the concepts covered in this book.

Exercise 1: Building a Simple Calculator

 Objective: Create a Python program that performs basic arithmetic operations such as addition,
subtraction, multiplication, and division.
 Steps:
1. Write a program that prompts the user to input two numbers.
2. Ask the user to select an operation (+, -, *, /).
3. Perform the chosen operation and display the result.
4. Handle errors like division by zero.

def calculator():
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
operator = input("Enter an operator (+, -, *, /): ")

if operator == "+":
print("Result:", num1 + num2)
elif operator == "-":
print("Result:", num1 - num2)
elif operator == "*":
print("Result:", num1 * num2)
elif operator == "/":
if num2 != 0:
print("Result:", num1 / num2)
else:
print("Error: Division by zero is not allowed.")
else:
print("Invalid operator.")
except ValueError:
print("Invalid input. Please enter numbers only.")

calculator()

 Key Concepts Covered:


o Input/output operations.
o Conditional statements (if-else).
o Arithmetic operations and error handling.

pg. 39
Mastering Python: CosmiCode Learning Series

Exercise 2: Data Analysis Using Pandas

 Objective: Use the Pandas library to load, process, and analyze data from a CSV file.
 Steps:
1. Install the Pandas library using pip install pandas.
2. Load a sample dataset (e.g., a CSV file with student scores) into a DataFrame.
3. Perform operations such as calculating the mean, filtering data, and grouping by
categories.
4. Display the processed data.

import pandas as pd

# Sample data
data = {
"Name": ["Alice", "Bob", "Charlie", "David"],
"Score": [85, 90, 78, 92],
"Grade": ["A", "A", "B", "A"]
}

# Create a DataFrame
df = pd.DataFrame(data)

# Perform operations
print("Average Score:", df["Score"].mean())
print("\nStudents with Score > 80:")
print(df[df["Score"] > 80])

 Key Concepts Covered:


o Data structures (DataFrame).
o Basic data manipulation.
o Aggregations and filtering.

Exercise 3: Visualizing Data with Matplotlib

 Objective: Create simple visualizations using the Matplotlib library.


 Steps:
1. Install Matplotlib using pip install matplotlib.
2. Use sample data to create line, bar, and pie charts.
3. Customize the charts with titles, labels, and legends.

pg. 40
Mastering Python: CosmiCode Learning Series

import matplotlib.pyplot as plt

# Sample data
months = ["Jan", "Feb", "Mar", "Apr", "May"]
sales = [150, 200, 300, 250, 400]

# Line Chart
plt.plot(months, sales, marker="o")
plt.title("Monthly Sales")
plt.xlabel("Months")
plt.ylabel("Sales")
plt.grid(True)
plt.show()

 Key Concepts Covered:


o Data visualization.
o Creating and customizing plots.
o Adding titles, labels, and legends.

Exercise 4: A Simple AI/ML Project

 Objective: Implement a basic machine learning model using the Scikit-learn library.
 Steps:
1. Install Scikit-learn using pip install scikit-learn.
2. Use a dataset (e.g., Iris dataset) to build a classification model.
3. Split the dataset into training and testing sets.
4. Train a model (e.g., Decision Tree) and evaluate its accuracy.

from sklearn.datasets import load_iris


from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score

# Load the Iris dataset


iris = load_iris()
X, y = iris.data, iris.target

# Split the data


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Train the model


model = DecisionTreeClassifier()
model.fit(X_train, y_train)

# Predict and evaluate


predictions = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, predictions))

pg. 41
Mastering Python: CosmiCode Learning Series

 Key Concepts Covered:


o Machine learning basics.
o Data splitting and training.
o Model evaluation.

Exercise 5: Working with APIs

 Objective: Fetch data from a public API and process it.


 Steps:
1. Install the requests library using pip install requests.
2. Use an API (e.g., OpenWeatherMap) to fetch data.
3. Parse the JSON response and display relevant information.

import requests

# Fetch data from an API


response = requests.get("https://api.github.com")

if response.status_code == 200:
data = response.json()
print("GitHub API Data:")
print(data)
else:
print("Failed to fetch data.")

 Key Concepts Covered:


o HTTP requests using requests.
o Parsing JSON data.
o Working with APIs.

Summary

The Python practical work provides hands-on experience to reinforce programming concepts,
ranging from basic to advanced levels. The exercises begin with building a simple calculator,
focusing on user input/output, conditional statements, arithmetic operations, and error handling.
Data analysis tasks using the Pandas library introduce learners to data structures like DataFrames,
enabling them to manipulate and analyze datasets through operations such as aggregation and
filtering. Data visualization is explored through Matplotlib, where learners create line, bar, and
pie charts while customizing them with titles, labels, and legends. A basic AI/ML project with
Scikit-learn teaches machine learning fundamentals, including data splitting, training models,
and evaluating accuracy using a decision tree classifier. Finally, working with APIs demonstrates
how to fetch and process data from public APIs using the requests library and JSON parsing.
These exercises collectively provide a strong foundation for mastering Python programming in
real-world scenarios.

pg. 42
Mastering Python: CosmiCode Learning Series

Python Interview MCQs: Your Path to


Mastery
Here are the 50 Multiple-Choice Questions (MCQs) covering a wide range of Python topics.
These questions are designed to test your understanding of the core concepts and techniques
discussed throughout the chapters. While we have carefully crafted and reviewed the 50 MCQs
at the end of this book, there is always a possibility of mistakes or inaccuracies. If you encounter
any errors in the questions, answers, or explanations, please feel free to report them to
CosmiCode. Your feedback is invaluable in helping us improve the quality of our resources and
ensuring the best learning experience for all readers.

1. What is the correct extension for Python files?


a) .py
b) .java
c) .cpp
d) .txt

Correct Answer: a) .py

2. How do you create a single-line comment in Python?


a) //
b) /* */
c) #
d) <!-- -->

Correct Answer: c) #

3. What is the output of print(5 // 2)?


a) 2.5
b) 2
c) 3
d) 3.5

Correct Answer: b) 2

pg. 43
Mastering Python: CosmiCode Learning Series

4. Which of the following data types is immutable in Python?


a) List
b) Dictionary
c) Set
d) Tuple

Correct Answer: d) Tuple

5. Which of these is not a Python keyword?


a) def
b) class
c) main
d) pass

Correct Answer: c) main

6. What does len() do in Python?


a) Finds the length of a string
b) Finds the length of a list
c) Works for strings, lists, and other collections
d) Only works for integers

Correct Answer: c) Works for strings, lists, and other collections

7. What is the output of print(type(10))?


a) <class 'str'>
b) <class 'float'>
c) <class 'int'>
d) <class 'bool'>

Correct Answer: c) <class 'int'>

pg. 44
Mastering Python: CosmiCode Learning Series

8. Which of the following is not a valid Python operator?


a) +
b) **
c) %%
d) //

Correct Answer: c) %%

9. What is the result of bool([])?


a) True
b) False

Correct Answer: b) False

10. Which Python statement is used to handle exceptions?


a) try-except
b) if-else
c) while-break
d) pass-continue

Correct Answer: a) try-except

11. How do you import the math module in Python?


a) include math
b) import math
c) load math
d) using math

Correct Answer: b) import math

12. Which method is used to remove the last element from a list?
a) delete()
b) remove()

pg. 45
Mastering Python: CosmiCode Learning Series

c) pop()
d) discard()

Correct Answer: c) pop()

13. What is the output of print(3 * 'Python')?


a) Python3
b) PythonPythonPython
c) Python * 3
d) Error

Correct Answer: b) PythonPythonPython

14. Which of the following is not a Python collection?


a) List
b) Set
c) Dictionary
d) Array

Correct Answer: d) Array

15. How do you declare a function in Python?


a) func myFunction():
b) function myFunction():
c) def myFunction():
d) declare myFunction():

Correct Answer: c) def myFunction():

16. What is the purpose of the is operator in Python?


a) To compare values
b) To check identity of objects
c) To test membership
d) To perform logical operations

pg. 46
Mastering Python: CosmiCode Learning Series

Correct Answer: b) To check identity of objects

17. What is the output of print(10 / 3)?


a) 3
b) 3.33
c) 3.0
d) 3.3333333333333335

Correct Answer: d) 3.3333333333333335

18. Which Python function is used to open a file?


a) open()
b) read()
c) write()
d) file()

Correct Answer: a) open()

19. What is the default mode of the open() function?


a) r
b) w
c) rw
d) a

Correct Answer: a) r

20. How do you write an infinite loop in Python?


a) while(1)
b) while True:
c) for(;;)
d) repeat forever:

Correct Answer: b) while True:

pg. 47
Mastering Python: CosmiCode Learning Series

21. Which method is used to convert a string to lowercase in Python?


a) lower()
b) toLowerCase()
c) convert_lower()
d) downcase()

Correct Answer: a) lower()

22. What is the result of print(bool(''))?


a) True
b) False

Correct Answer: b) False

23. Which of the following is a valid variable name in Python?


a) 1name
b) name1
c) name-1
d) name@1

Correct Answer: b) name1

24. What is the correct way to create a dictionary in Python?


a) dict = {key1=value1, key2=value2}
b) dict = [key1:value1, key2:value2]
c) dict = {key1:value1, key2:value2}
d) dict = (key1:value1, key2:value2)

Correct Answer: c) dict = {key1:value1, key2:value2}

25. Which method can be used to replace a substring in a string?


a) replace()

pg. 48
Mastering Python: CosmiCode Learning Series

b) update()
c) swap()
d) substitute()

Correct Answer: a) replace()

26. What is the output of print(3 ** 2)?


a) 6
b) 9
c) 8
d) 12

Correct Answer: b) 9

27. What does the pass keyword do in Python?


a) Terminates a loop
b) Skips the current iteration of a loop
c) Does nothing
d) Ends a function

Correct Answer: c) Does nothing

28. How do you create a set in Python?


a) set = [1, 2, 3]
b) set = {1, 2, 3}
c) set = (1, 2, 3)
d) set = <1, 2, 3>

Correct Answer: b) set = {1, 2, 3}

29. Which of the following is not a valid loop in Python?


a) for
b) while

pg. 49
Mastering Python: CosmiCode Learning Series

c) do-while
d) None of the above

Correct Answer: c) do-while

30. How do you create a list in Python?


a) list = (1, 2, 3)
b) list = {1, 2, 3}
c) list = [1, 2, 3]
d) list = <1, 2, 3>

Correct Answer: c) list = [1, 2, 3]

31. What does range(5) return?


a) [0, 1, 2, 3, 4, 5]
b) (0, 1, 2, 3, 4)
c) [0, 1, 2, 3, 4]
d) None of the above

Correct Answer: c) [0, 1, 2, 3, 4]

32. What is the purpose of the continue statement in Python?


a) Exits the loop entirely
b) Skips the remaining code in the current iteration and moves to the next iteration
c) Stops the loop and raises an error
d) Pauses the loop temporarily

Correct Answer: b) Skips the remaining code in the current iteration and moves to the
next iteration

33. What is the output of print(type([1, 2, 3]))?


a) <class 'tuple'>
b) <class 'list'>

pg. 50
Mastering Python: CosmiCode Learning Series

c) <class 'set'>
d) <class 'dict'>

Correct Answer: b) <class 'list'>

34. What is the default value returned by a function that does not have a return statement?
a) 0
b) None
c) False
d) Null

Correct Answer: b) None

35. Which module is used to generate random numbers in Python?


a) randomize
b) random
c) randint
d) numbers

Correct Answer: b) random

36. What is the output of print(10 % 3)?


a) 1
b) 3
c) 0
d) 10

Correct Answer: a) 1

37. Which method is used to add an element to the end of a list?


a) append()
b) add()
c) push()
d) insert()

pg. 51
Mastering Python: CosmiCode Learning Series

Correct Answer: a) append()

38. How do you access the first element of a list my_list = [10, 20, 30]?
a) my_list(0)
b) my_list[1]
c) my_list[0]
d) my_list.first()

Correct Answer: c) my_list[0]

39. What is the purpose of the with statement in Python?


a) To create loops
b) To manage resources like file handling
c) To define functions
d) To create classes

Correct Answer: b) To manage resources like file handling

40. What does list(range(3)) return?


a) [1, 2, 3]
b) [0, 1, 2]
c) [1, 2, 3, 4]
d) [0, 1, 2, 3]

Correct Answer: b) [0, 1, 2]

41. How do you check the length of a string in Python?


a) count()
b) length()
c) len()
d) size()

Correct Answer: c) len()

pg. 52
Mastering Python: CosmiCode Learning Series

42. What does the in keyword do in Python?


a) Declares a variable
b) Tests for membership in a collection
c) Defines a function
d) Compares two variables

Correct Answer: b) Tests for membership in a collection

43. Which of the following is a Python framework for web development?


a) NumPy
b) Pandas
c) Django
d) Matplotlib

Correct Answer: c) Django

44. What is the output of print(2**3)?


a) 6
b) 8
c) 9
d) 12

Correct Answer: b) 8

45. What is the use of the break statement in Python?


a) To skip the current iteration
b) To exit the loop entirely
c) To pause the loop
d) To return to the beginning of the loop

Correct Answer: b) To exit the loop entirely

pg. 53
Mastering Python: CosmiCode Learning Series

46. Which library is used for numerical computations in Python?


a) Matplotlib
b) NumPy
c) Flask
d) Requests

Correct Answer: b) NumPy

47. How do you create a tuple in Python?


a) tuple = {1, 2, 3}
b) tuple = [1, 2, 3]
c) tuple = (1, 2, 3)
d) tuple = <1, 2, 3>

Correct Answer: c) tuple = (1, 2, 3)

48. What is the correct way to install a Python library?


a) install library_name
b) pip install library_name
c) python install library_name
d) load library_name

Correct Answer: b) pip install library_name

49. What does str() do in Python?


a) Converts a string to an integer
b) Converts an integer or other type to a string
c) Converts a string to lowercase
d) Converts a string to a float

Correct Answer: b) Converts an integer or other type to a string

50. Which of the following is a mutable data type in Python?


a) Tuple

pg. 54
Mastering Python: CosmiCode Learning Series

b) List
c) String
d) None of the above

Correct Answer: b) List

pg. 55
Mastering Python: CosmiCode Learning Series

Python Mastery Certification


Congratulations on completing the Python Mastery eBook by CosmiCode! You are now ready
to take the final step to earn your Python Mastery Certificate. Follow the steps below to get
certified and prove your Python expertise!

How to Get Your Python Mastery Certificate

1. Scan the Barcode


At the end of this page, you will find a unique barcode. Scan it using your mobile device or any
QR code scanner.

2. Fill in Your Personal Details


After scanning the barcode, you will be redirected to an online portal where you’ll need to fill in
your personal details (such as name, email, university/organization, etc.). This is necessary for
generating your certificate.

3. Complete the Python Test


You will then be directed to the Python Mastery Test, which includes 25 questions. The test
consists of:

 Multiple-Choice Questions (MCQs)


 Conceptual and Definition-Based Questions

4. Submit the Test


Once you’ve answered all the questions, submit your test for evaluation. No time limit is
enforced, so take your time to answer carefully.

5. Receive Your Certificate


Upon successful completion of the test, your Python Mastery Certificate will be sent to your
provided email address. The certificate will contain your name, test score, and a unique
verification code.

Python Mastery Test – Key Details

 Total Questions: 25
 Test Type:
o Multiple-choice questions (MCQs)
o Conceptual questions
o Definition-based questions
 Pass Mark: 80% (Minimum required score)

pg. 56
Mastering Python: CosmiCode Learning Series

 Certificate Issuance: Sent via email after passing the test

Why Take This Test?

 Validate Your Knowledge: This test allows you to confirm your understanding of core Python
concepts and their application.
 Industry Recognition: CosmiCode's Python Mastery Certificate is an excellent addition to your
resume or LinkedIn profile and can be a valuable asset when seeking opportunities in the tech
industry.
 Self-Assessment: Evaluate your understanding of important Python concepts, from basic syntax
to advanced programming techniques.

Barcode for Certification

Scan the barcode below to begin your certification process!

Important Notes:

 No Time Limit: You can take as long as needed to complete the test. Focus on conceptual clarity
and understanding.
 Accurate Details: Ensure the email address you provide is correct as the certificate will be sent
there.
 Certificate Delivery: Once you pass the test, your certificate will be sent directly to your email.
 Issue Reporting: If you encounter any issues during the process, contact
[email protected] for support.

By completing this test, you will not only solidify your knowledge of Python but also join a
community of passionate learners supported by CosmiCode.
pg. 57
Mastering Python: CosmiCode Learning Series

License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0
International License.

Usage Guidelines

 You may share and distribute this book for non-commercial purposes, provided that
proper credit is given to CosmiCode as the original creator.
 You may remix, transform, or build upon this book for non-commercial purposes as
long as you share your modifications under the same license and give appropriate credit.
 You may not use this book for commercial purposes without explicit permission from
CosmiCode.

If you discover any errors or wish to inquire about permissions, please contact us at:
[email protected]

Thank you for supporting free and accessible learning!

© 2025 CosmiCode. All rights reserved.


This book is provided as a free learning resource by CosmiCode, dedicated to empowering
students and tech enthusiasts with quality educational content.

pg. 58
COSMICODE
PRESENTS
E-BOOK

A PORTAL TO EXCELLENCE

Mastering Python: Your Journey to Programming Excellence

Congratulations on completing this learning journey with us! At CosmiCode, we


believe in empowering tech enthusiasts like you to achieve greatness. This eBook is
just one step in your endless path of growth and innovation.

CosmiCode is dedicated to helping tech students and professionals thrive in the


fast-evolving tech world. Through free resources, hands-on training, webinars, and
remote internships, we empower you to turn your ideas into reality.

We believe that knowledge should be accessible to everyone, and our mission is to


bridge the gap between learners and the tech industry. Whether you're starting out
or leveling up, CosmiCode is here to guide you every step of the way.

Hungry for More?


Explore our free resources, webinars, and training programs.
Follow us on LinkedIn to stay updated with new learning opportunities.
Stay Connected:
Join our global tech community and connect with like-minded learners.
Feedback & Reporting:
Found any errors? Have suggestions? Let us know at: [email protected]

COSMICODE LEARNING SERIES

You might also like