Shubhash
Shubhash
Of
Submitted by
Shubhash .N
U18EX22S0065
1
[Certificate of Internship from company letter head]
Certificate of Internship
Signature of authority
Seal of Organization
2
CERTIFICATE
This to certify that the internship entitled
Shubhash .N
U18EX22S0065
BCA C1
Internship Guide
Mrs. Shilpa Nayak
Assistant Professor
3
NAGARJUNA DEGREE COLLEGE
(Affiliated to Bengaluru City University)
# 38/36, Ramagondanahalli, Yelahanka, Bengaluru -560 064.
Phone: 6364231112
E Mail: [email protected] Website: www.nagarjunadegreecollege.co.in
Student Declaration
I SHUBHASH .N , hereby declare that this report entitled “Calculator using python “is uniquely
prepared by me during my internship at YBI Foundation from 10th April 2025 to 10th May2025.
This report is submitted as a partial fulfillment of the requirements for the VI Semester BCA
Internship Course.
Signature
Shubhash.N
4
ACKNOWLEDGEMENT
Firstly I would like to thank [Shri. Dr Alok Yadav of YBI Foundation for giving an
opportunity to do an internship within the organization.
We are indebted to our cherished Principal, Dr. Harish Babu S, whose support and permission
were instrumental in undertaking this dissertation. Their guidance throughout this challenging
endeavor has been invaluable.
We are deeply grateful to our respected Head of Department, Mrs. Uma, whose support and
permission were instrumental in enabling us to embark on this dissertation journey and
guiding us through its completion.
Our sincere appreciation goes to our dedicated guide, Mrs. Shilpa Nayak, for their invaluable
mentorship and timely assistance in bringing our project to fruition.
We are also indebted to the members of the Computer Department for their guidance and
support throughout this endeavor.
Last but not least, we express our heartfelt gratitude to our beloved parents and dear friends
for their unwavering encouragement and inspiration.
Shubhash .N
U18EX22S0065
5
CONTENTS
Serial No. Page No
1.1 Purpose 1
5 Bibliography 25
Annexures
Questionaries
6
7
1. Executive Summary
1.1 Purpose
The purpose of this internship was to provide hands-on experience in software development
through a practical project. I was assigned the task of creating a calculator using Python. This task
aimed to reinforce my foundational understanding of Python programming, GUI development,
logic building, and application deployment. The project enabled me to bridge the gap between
theoretical knowledge and practical implementation, thereby enhancing my problem-solving
capabilities, algorithmic thinking, and user interface design skills.
1.2 Scope of the Internship
The internship, conducted under the guidance of experienced mentors at the YBI Foundation,
focused on software development and digital skills enhancement. As part of the broader objective
to empower youth through technology, I was given the opportunity to develop a functional
calculator application. The project was designed to include key programming concepts such as
functions, event-driven programming, data validation, and GUI creation using libraries like
Tkinter. It also included phases of design, implementation, testing, and debugging.
1.3 Outcome of the Internship
The final outcome of the internship was a fully functional, user-friendly calculator built using
Python. This calculator could perform fundamental arithmetic operations (addition, subtraction,
multiplication, division) and some advanced operations such as square root, percentage, and
modulus. Additionally, I gained proficiency in Python syntax, GUI design, event handling,
exception handling, and debugging techniques. The project improved my logical reasoning and
provided real-world experience of building a complete software application from scratch.
8
aspiring developer.
2.3 Organizational Profile
YBI Foundation (Youth Empowerment and Digital Skills Training Organization) is a non-profit,
tech-oriented institution focused on empowering youth with essential digital and technological
skills. The foundation organizes multiple training programs and internships to enhance
employability and foster innovation among youth. YBI emphasizes hands-on learning and project-
based internships to encourage students to build real applications.
2.3.1 Products & Clients
YBI Foundation offers training programs in:
Web Development
Python Programming
Data Science
Android App Development
Machine Learning
Internet of Things (IoT)
Clients and Beneficiaries:
Students from various academic backgrounds
Young job seekers
Educational institutions
NGOs focused on digital literacy
Government youth development initiatives
3. Work Description
3.1 Organizational Chart
Chairman
↓
Program Director
↓
Technical Trainers
↓
Internship Coordinators
↓
Interns (Students, including me)
I worked under the guidance of a technical trainer and coordinator who evaluated weekly progress
and provided feedback and support.
9
3.2 Intern’s Job Role Description
As an intern, my primary responsibility was to:
Understand the requirements of the calculator project
Learn and apply Python programming to implement the logic
Design a simple but functional user interface
Handle user inputs and events
Debug and test the application thoroughly
Document the development process
Additional tasks included participating in review meetings, preparing presentations, and
collaborating with fellow interns to learn and share feedback.
3.3 Programming Language/Concept/Technology
Language Used: Python
Key Concepts Applied:
Variables and Data Types
Control Statements (if-else, loops)
Functions and Modular Programming
Exception Handling
GUI Programming using Tkinter
Event Handling
Data Binding and User Input Validation
This project helped me understand how programming logic is mapped to real-world functionality
and how to interact with users via graphical components.
3.4 Software/Hardware Used
Software:
Python 3.x
Tkinter Library (built-in)
Visual Studio Code / PyCharm IDE
GitHub (for version control and submission)
Hardware:
Laptop with minimum configuration: i5 Processor, 8GB RAM, Windows 10 OS
The calculator app was designed to be lightweight, so it could run efficiently on any standard PC
or laptop.
10
SOURCE CODE:
# -*- coding: utf-8 -*-
from tkinter import Tk, END, Entry, N, E, S, W, Button
from tkinter import font
from tkinter import Label
from functools import partial
def backspace(entry):
input_len = len(entry.get())
entry.delete(input_len - 1)
def clear(entry):
entry.delete(0, END)
def calc(entry):
input_info = entry.get()
try:
if(input_info==""):
popup = Tk()
popup.resizable(0, 0)
popup.geometry("150x100")
popup.title("Alert")
label = Label(popup, text="Enter valid values")
label.pack(side="top", fill="x", pady=10)
B1 = Button(popup, text="Okay", bg="#DDDDDD", command=popup.destroy)
B1.pack()
else:
output = str(eval(input_info.strip()))
except ZeroDivisionError:
popupmsg()
11
output = ""
clear(entry)
entry.insert(END, output)
def popupmsg():
popup = Tk()
popup.resizable(0, 0)
popup.geometry("150x100")
popup.title("Alert")
label = Label(popup, text="Cannot divide by 0 ! \n Enter valid values")
label.pack(side="top", fill="x", pady=10)
B1 = Button(popup, text="Okay", bg="#DDDDDD", command=popup.destroy)
B1.pack()
def cal():
root = Tk()
root.title("Calc")
root.resizable(0, 0)
entry_font = font.Font(size=15)
entry = Entry(root, justify="right", font=entry_font)
entry.grid(row=0, column=0, columnspan=4,
sticky=N + W + S + E, padx=5, pady=5)
cal_button_bg = '#FF6600'
num_button_bg = '#4B4B4B'
other_button_bg = '#DDDDDD'
text_fg = '#FFFFFF'
button_active_bg = '#C0C0C0'
12
button7 = num_button(text='7', bg=num_button_bg,
command=lambda: get_input(entry, '7'))
button7.grid(row=2, column=0, pady=5)
13
button12 = cal_button(text='*', command=lambda: get_input(entry, '*'))
button12.grid(row=2, column=3, pady=5)
14
exit.grid(row=8, column=2)
root.mainloop()
if __name__ == '__main__':
cal()
4. Learning Outcome
4.1 Abstract of Work Experience
During the internship at YBI Foundation, I worked on a calculator project that allowed me to
experience the complete cycle of software development—from concept to deployment. Initially, I
analyzed existing calculator models and identified key functionalities. I then planned my app's
layout using wireframes and began coding the core functionality. Using Python’s Tkinter library,
I created buttons, display screens, and event listeners.
Throughout the development process, I learned:
How to structure a Python application
How to handle errors and prevent application crashes
How to connect backend logic with frontend design
Daily interactions with mentors and peers helped improve my collaboration and communication
skills. By the end of the internship, I had not only developed a fully operational calculator but also
gained confidence in tackling future development projects.
4.2 Application Development / Technology Learned
Application Developed:
Name: Python Calculator
Functionality:
Basic Arithmetic: Addition, Subtraction, Multiplication, Division
Advanced Operations: Modulus, Square root, Percentage
Clear and Reset Functionality
Error Display and Handling
GUI Interface using Tkinter
Technologies Learned:
1. Python Programming:
15
Enhanced understanding of:
o Syntax
o Loops and conditionals
o Function-based programming
o Exception handling
2. Tkinter GUI Library:
Gained knowledge of:
o Widgets (Button, Label, Entry)
o Grid and Pack Layout Managers
o Event handling via command binding
o Aesthetic improvement (colors, fonts, padding)
3. Software Development Lifecycle:
o Requirement gathering
o Design and prototyping
o Development and testing
o Documentation and review
4. Debugging and Testing:
o Identifying runtime errors
o Ensuring input validation
o Logical correctness of arithmetic operations
5. Version Control (GitHub):
o Learned basic Git commands
o Created repositories
o Uploaded and shared source code
6. Time and Project Management:
o Creating development timelines
o Following weekly milestones
o Meeting submission deadlines
This internship helped me develop a foundational understanding of building real-world
applications and introduced me to core software engineering practices.
16
5. Bibliography
1. Books & Online Resources:
o Python Crash Course by Eric Matthes
o Automate the Boring Stuff with Python by Al Sweigart
o Tkinter Documentation – https://docs.python.org/3/library/tkinter.html
o GeeksforGeeks Python Programming Tutorials –
https://www.geeksforgeeks.org
o W3Schools Python GUI –
https://www.w3schools.com/python/python_gui_tkinter.asp
2. Software & Tools:
o Python.org for official Python software downloads
o GitHub for repository management
o Visual Studio Code for code editing
3. Mentorship and Guidance:
o Trainers and coordinators at YBI Foundation for hands-on support and
feedback
17
Log Sheet
Duration
Sn Date Concept learnt
(in Hours)
18
15 24/04/2025 Practice quix 1 Hours
Declaration:
It is declared that the student is completed his/her internship in our organization as per
above schedule.
Signature of Authority
Seal of Organization
19
Introduction to Python
Python is a high-level, general-purpose programming language that has gained immense popularity
due to its simplicity, readability, and versatility. It was created by Guido van Rossum and first
released in 1991. Python emphasizes code readability and allows developers to express concepts in
fewer lines of code compared to many other languages.
The language supports multiple programming paradigms, including procedural, object-oriented, and
functional programming. Python's vast standard library and active community support make it
suitable for a wide range of applications, such as web development, data analysis, machine learning,
automation, and software development.
During the course of the internship, Python was used extensively due to its flexibility and efficiency
in solving real-world problems, writing scripts, and developing scalable applications.
Python is a powerful, interpreted, high-level programming language that supports multiple
programming paradigms including procedural, object-oriented, and functional programming.
Designed with code readability in mind, Python uses clear and concise syntax that enables developers
to write logical and maintainable code for both small-scale scripts and large-scale applications.
Originally developed by Guido van Rossum and released in 1991, Python has grown to become one
of the most widely used programming languages in the world. It is open-source and supported by a
large global community, which contributes to its rich ecosystem of libraries and frameworks. These
libraries, such as NumPy, Pandas, TensorFlow, Flask, and Django, extend Python’s capabilities and
make it a go-to language for fields like data science, web development, artificial intelligence,
machine learning, automation, and software testing.
Python’s platform independence allows code to run seamlessly across various operating systems,
such as Windows, Linux, and macOS. Furthermore, its compatibility with modern development tools
and integration capabilities with other languages (like C, C++, and Java) enhance its utility in
enterprise and academic environments.
🔹 Key Features of Python
Python has clean and readable syntax, similar to English, which makes it ideal for beginners and
reduces the learning curve.
2. Interpreted Language
Python is an interpreted language, meaning the code is executed line-by-line, which makes debugging
easier and quicker.
3. Dynamically Typed
You don’t need to declare the data type of a variable. Python automatically detects it based on the
value assigned.
4. Cross-Platform Compatibility
Python works on all major operating systems (Windows, macOS, Linux), so programs can run almost
anywhere without modification.
20
5. Large Standard Library
Python comes with a vast library of built-in modules and third-party packages, which makes
development faster and easier.
6. Object-Oriented and Functional
Python supports both object-oriented and functional programming paradigms, giving developers
flexibility in how they structure their code.
7. Extensible and Embeddable
Python can integrate with other languages like C, C++, and Java, making it suitable for complex
applications and systems programming.
8. High-Level Language
Python handles low-level details like memory management automatically, so developers can focus on
problem-solving rather than technical complexi.
BASIC PYTHON POGRAMS
if num % 2 == 0:
print(f"{num} is even.")
else:
print(f"{num} is odd.")
output:
Enter a number: 4
4 is even.
21
Anaconda
Anaconda is a free and open-source distribution of Python and R programming languages, designed
for scientific computing, data science, machine learning, and large-scale data processing.
It simplifies package management and deployment using tools like Conda, and comes pre-installed
with many popular data science libraries and tools.
Key Features of Anaconda:
Pre-installed packages: Comes with 250+ scientific and data packages like NumPy, pandas,
Matplotlib, scikit-learn, TensorFlow, etc.
Environment management: Easily create isolated environments to avoid dependency conflicts.
Package manager: Uses conda, which can install packages from both Conda and pip repositories.
User-friendly tools:
Jupyter Notebook – for interactive data analysis.
Spyder – an IDE for scientific programming.
Anaconda Navigator – a graphical interface for managing environments and launching tools.
Why we use Anaconda ?
1. All-in-One Data Science Toolkit
➡️Keeps your projects organized and prevents interference between different package versions.
4. Cross-Platform Support
Graphical interface (Anaconda Navigator) for managing tools and environments without
using the command line.
Pre-configured setup removes complexity from the development process.
➡️Great starting point for people new to Python or data science.
6. Trusted by Professionals
Used by researchers, data scientists, and companies globally due to its stability and rich ecosystem.
Applications You Can Launch from Navigator:
24
Python Data Types
Data types define the kind of data a variable can hold in a programming language like Python.
They help Python understand how to store and manipulate values correctly—whether it’s a number,
text, list, or something else.
Why Are Data Types Important?
. Ensure that operations are valid (e.g., you can't add a string to a number).
. Allow Python to manage memory efficiently.
. Help you organize and structure your program’s data logically.
Types of Data Types in python:
1. Numeric Types
int (Integer)
3. Sequence Types
🔹 list
25
Represents a sequence of numbers, commonly used in loops.
Example: range(5) generates numbers from 0 to 4.
4. Mapping Type
🔸 dict (Dictionary)
5. Set Types
🔹 set
6. Boolean Type
bool
7. Binary Types
🔹 bytes
Python Variables
A variable in Python is essentially a name that refers to a value. You can think of it as a container
that stores data (such as a number, string, list, etc.). Once a variable is assigned a value, you can use
that variable in your program to manipulate or display the stored data.
Features of Variables in Python
1. Dynamically Typed
26
No need to declare types: Python automatically determines the type of a variable based on
the value assigned to it.
You don’t have to declare the type of a variable when you create it.
2. No Explicit Declaration
Python does not require explicit declaration of variables. You simply assign a value to a
variable name, and Python handles the rest.
This makes Python a high-level language, with fewer lines of code needed to manage
variables.
3. Reassignable
Variables in Python are mutable and can be reassigned any time. You can change the value or
type of a variable during the program’s execution.
4. No Memory Allocation Issues
Python manages memory allocation and garbage collection automatically. Variables will
automatically be freed when they are no longer in use (i.e., when there are no references to
them).
5. Supports Multiple Assignments
Variables in Python are not restricted to any specific data type. A variable can hold any type
of data, such as integers, strings, lists, tuples, dictionaries, and more.
7. Case Sensitivity
Variable names are case-sensitive. This means that myVariable and myvariable are
considered different variables in Python.
8. No Restrictions on Variable Names (Except Keywords)
Variables can be named using letters, digits, and underscores, but they cannot start with a
digit. Additionally, Python keywords (reserved words) like if, for, and while cannot be used
as variable names.
9. Garbage Collection
Python has an automatic garbage collection system that manages memory and removes
unused variables from memory. When a variable is no longer referenced, it is automatically
deleted.
27
Variables can be local (inside a function) or global (available throughout the program).
You can use the global keyword to modify global variables inside a function.
Python operators
Operators are symbols or keywords that let you perform operations on values or variables. Think of
them like instructions for doing things like math, comparisons, or combining logic.
1. Arithmetic Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
7. Identity Operators
output:
output:
31
print("After a += 5, a =", a)
a -= 3
print("After a -= 3, a =", a)
a *= 2
print("After a *= 2, a =", a)
a /= 4
print("After a /= 4, a =", a)
a //= 2
print("After a //= 2, a =", a)
a %= 3
print("After a %= 3, a =", a)
a **= 2
print("After a **= 2, a =", a)
output:
Initial value of a: 10
After a += 5, a = 15
After a -= 3, a = 12
After a *= 2, a = 24
After a /= 4, a = 6.0
After a //= 2, a = 3.0
After a %= 3, a = 0.0
After a **= 2, a = 0.0
QUIX
32
Introduction To Pandas
Pandas (styled as pandas) is a software library written for the Python programming language for
data manipulation and analysis. In particular, it offers data structures and operations for manipulating
numerical tables and time series. It is free software released under the three-clause BSD license.
[2]
The name is derived from the term "panel data", an econometrics term for data sets that include
observations over multiple time periods for the same individuals, [3] as well as a play on the phrase
"Python data analysis".[4]: 5 Wes McKinney started building what would become Pandas at AQR
Capital while he was a researcher there from 2007 to 2010.[5]
The development of Pandas introduced into Python many comparable features of working with
DataFrames that were established in the R programming language.[6] The library is built upon another
library, NumPy.
1. Data Structures:
o Series: A one-dimensional labeled array.
o DataFrame: A two-dimensional labeled data structure, like a table in a database or Excel
spreadsheet.
2. Data Handling:
o Supports reading and writing data from various formats: CSV, Excel, SQL, JSON, and
more.
o Powerful tools for filtering, transforming, grouping, and cleaning data.
3. Missing Data Handling:
o Provides tools like isna(), fillna(), and dropna() for dealing with missing data.
4. Label-based Indexing:
o Use of labels for rows and columns to access data instead of relying solely on integer
indices.
5. Data Aggregation and Grouping:
o Easily group data using groupby() and apply functions like sum, mean, or custom
aggregations.
6. Time Series Support:
o Built-in support for time series data, including date range generation and frequency
conversion.
python
33
CopyEdit
import pandas as pd
s = pd.Series([10, 20, 30], index=['a', 'b', 'c'])
print(s)
b. DataFrame
python
CopyEdit
data = {'Name': ['Anna', 'Ben'], 'Age': [28, 34]}
df = pd.DataFrame(data)
print(df)
# Filtering rows
df[df['Age'] > 30]
4. Data Cleaning
python
CopyEdit
df.dropna() # Remove missing data
df.fillna(0) # Replace missing values with 0
df.rename(columns={'Name': 'FullName'}, inplace=True)
df['Age'] = df['Age'].astype(int) # Change data type
34
5. GroupBy and Aggregation
python
CopyEdit
df.groupby('City').mean() # Average age by city
df['Age'].sum() # Sum of age
df['Age'].agg(['min', 'max']) # Multiple aggregations
# Extracting parts
df['Year'] = df['Date'].dt.year
df['Age'].plot(kind='bar')
plt.show()
8. Common Operations
Sorting: df.sort_values(by='Age')
Merging: pd.merge(df1, df2, on='id')
Concatenating: pd.concat([df1, df2])
Pivot tables: df.pivot_table(values='Sales', index='Region', columns='Month')
import pandas as pd
35
'English': [88, 76, 89, 65, 90]
}
df = pd.DataFrame(data)
output:
Student Marks:
Name Math Science English
0 Alice 85 90 88
1 Bob 78 80 76
2 Charlie 92 95 89
3 David 60 70 65
4 Eva 88 85 90
36
Top Students (Average > 85):
Name Math Science English Average
0 Alice 85 90 88 87.666667
2 Charlie 92 95 89 92.000000
4 Eva 88 85 90 87.666667
🔹 Additional Parameters
A CSV file (short for Comma-Separated Values) is a simple text file used to store tabular data
(like a spreadsheet or database table).
37
Plain text format
Each line in the file is a data record
Each record consists of fields, separated by commas
Often used for data exchange between systems (e.g., Excel, databases, web apps)
🔹 Example CSV Content:
pgsql
CopyEdit
Name,Age,Country
Alice,30,USA
Bob,25,Canada
Charlie,35,UK
This represents a table with three columns (Name, Age, Country) and three rows of data.
🔹 Common Uses:
Fields are separated by commas (,), but other delimiters like tabs (\t), semicolons (;), or pipes (|)
can also be used.
The first row often contains column names (headers), but it's not required.
🔹 7. No Hierarchical Structure
CSV is flat — not suitable for nested or complex data like JSON or XML.
🔹 8. Encoding
In a CSV file, the separator (or delimiter) is the character used to divide fields (columns) in each
row. The default separator is a comma (,), but other separators can be used depending on the region,
software, or data structure.
🔹 Common Separators in CSV-like Files
Separator Character Example Line Common Use
Comma , Name,Age,Country Standard CSV (US, international)
Used in Europe (due to comma used as decimal
Semicolon ; Name;Age;Country
separator)
Tab \t Name\tAge\tCountry TSV (Tab-Separated Values)
Pipe ` ` `Name
Space '' Name Age Country Rare, not recommended
DataFrame Attribute in Pandas
A DataFrame in Pandas has several attributes that help you inspect and understand the structure and
metadata of your data — not to be confused with methods, which perform operations.
39
1. df.shape
python
CopyEdit
df.shape # (100, 5)
🔹 2. df.columns
python
CopyEdit
df.columns # Index(['Name', 'Age', 'Country'], dtype='object')
🔹 3. df.index
python
CopyEdit
df.index # RangeIndex(start=0, stop=100, step=1)
🔹 4. df.dtypes
python
CopyEdit
df.dtypes
# Name object
# Age int64
# Country object
🔹 5. df.size
40
python
CopyEdit
df.size # 500
🔹 6. df.ndim
python
CopyEdit
df.ndim # 2
🔹 7. df.head(n)
python
CopyEdit
df.head() # First 5 rows
🔹 8. df.tail(n)
python
CopyEdit
df.tail(3) # Last 3 rows
🔹 9. df.info()
Summary of the DataFrame: index, column data types, non-null counts, memory usage.
Example:
python
CopyEdit
df.info()
41
Exploring a Pandas DataFrame means getting a quick understanding of its structure, content,
summary statistics, and potential data quality issues. Here’s a step-by-step breakdown of how to
explore a DataFrame:
3. Summary Statistics
python
CopyEdit
df.describe() # Descriptive stats for numeric columns
df.describe(include='object') # Stats for categorical (object) columns
42
df['col'] = df['col'].astype(str) # Convert column to string
df.select_dtypes(include='number') # Select only numeric columns
python
CopyEdit
print(df.shape)
print(df.columns)
print(df.dtypes)
print(df.head())
print(df.describe(include='all'))
print(df.isnull().sum())
print(df['target'].value_counts(normalize=True))
Syntax
python
CopyEdit
df.mode(axis=0, numeric_only=False, dropna=True)
Parameters
43
Parameter Description
Axis 0 for columns (default), 1 for rows
numeric_only If True, only includes numeric data
Dropna If True, excludes NA/null when determining mode
Returns
data = {
'A': [1, 2, 2, 3],
'B': ['x', 'x', 'y', 'y'],
'C': [10, 20, 20, 10]
}
df = pd.DataFrame(data)
print(df.mode())
Output:
css
CopyEdit
A B C
0 2.0 x 10
1 NaN y 20
Use Cases
44
Finding the most common category in a column
Checking data skew in distributions
Preprocessing for replacing missing values
1. Multi-Mode Behavior
If a column has more than one most frequent value, .mode() returns multiple rows.
python
CopyEdit
import pandas as pd
print(df.mode())
Output:
css
CopyEdit
A
0 1.0
1 2.0
python
CopyEdit
df = pd.DataFrame({
'A': [1, 2, 3],
'B': [1, 2, 3],
'C': [1, 3, 3]
})
df.mode(axis=1)
Output:
markdown
CopyEdit
45
0
0 1.0
1 2.0
2 3.0
df.mode()
Output:
css
CopyEdit
Color
0 Red
🎯 Useful for finding the most common category in survey or label data.
You can combine .groupby() and .mode() to get the most common value per group.
python
CopyEdit
df = pd.DataFrame({
'Group': ['A', 'A', 'B', 'B', 'B'],
'Score': [1, 2, 2, 3, 2]
})
# Group-wise mode
df.groupby('Group')['Score'].agg(lambda x: x.mode().iloc[0])
Output:
css
CopyEdit
Group
46
A 1
B 2
Name: Score, dtype: int64
python
CopyEdit
df = pd.DataFrame({'A': [1, 1, None, None, 2]})
df.mode(dropna=False)
Output:
css
CopyEdit
A
0 1.0
1 NaN
Manipulate Data Frame
DataFrame manipulation refers to the process of modifying, transforming, or restructuring the
contents of a Pandas DataFrame to make the data more suitable for analysis, visualization, or
modeling.
Common DataFrame Manipulation Tasks Include:
5. Sorting Data
python
CopyEdit
df.sort_values(by='Age', ascending=True, inplace=True)
df.sort_index(inplace=True) # Sort by index
6. Replacing Values
python
CopyEdit
df['Gender'].replace({'M': 'Male', 'F': 'Female'}, inplace=True)
df.replace(0, np.nan, inplace=True) # Replace 0s with NaN
Data manipulation helps reveal patterns, trends, and relationships by organizing and
aggregating information properly.
Example: Grouping sales by region, pivoting customer behavior, or filtering key segments.
3. Essential for Machine Learning & Modeling
49
Models require numerical, well-structured, normalized data.
You often need to encode categories, scale values, or impute missing entries.
4. Supports Decision Making
Clean, transformed data feeds into dashboards, KPIs, and reports that guide business
strategy.
Without manipulation, stakeholders would be overwhelmed with noise.
Data Science is an interdisciplinary field that uses statistics, programming, and domain
knowledge to extract insights and knowledge from structured and unstructured data.
Core Components of Data Science:
1. Data Collection – Gathering data from sources like databases, sensors, web APIs.
2. Data Cleaning – Handling missing, incorrect, or inconsistent data.
3. Data Exploration & Visualization – Using tools like Pandas, Matplotlib, and Seaborn.
4. Statistical Analysis – Understanding relationships and trends in data.
5. Machine Learning – Building predictive models using algorithms.
6. Data Communication – Reporting results via dashboards, charts, and reports.
Applications:
Business analytics
Fraud detection
Recommendation systems
Healthcare diagnostics
Social media analysis
🤖 Introduction to AI and Machine Learning (AIML)
Artificial Intelligence (AI):
ML is a subset of AI that enables systems to learn from data and improve over time without being
explicitly programmed.
50
Type Description Example
Real-World Example
Application Agent Environment Reward
Game playing (e.g. Chess,
Game AI The game Win = +1, Lose = -1
Go)
Car control
Self-driving cars Road conditions Safe driving = positive
algorithm
Task completion =
Robotics Robot arm Assembly task
reward
Ad placement Ad selector User interaction Click = +1, No click = 0
52
Type Description
Model-
Learns a model of the environment
based
Challenges in RL
Exploration vs Exploitation: Should the agent try new actions (explore) or stick with the known
best ones (exploit)?
Delayed rewards: The agent may need to make several steps before knowing if its action was
good.
Large state spaces: Real-world problems often have millions of states or actions.
Training time: Can be very slow compared to supervised learning.
Deep Learning
Definition
Deep Learning is a subfield of Machine Learning that uses artificial neural networks with many
layers (hence “deep”) to model and solve complex problems — especially those involving
unstructured data like images, text, and audio.
It mimics the way the human brain processes information — learning from raw data through
layers of neurons.
Real-World Applications
Field Deep Learning Use Case
Vision Image recognition, facial recognition, object detection
NLP (Text) Chatbots, translation, sentiment analysis
Audio Speech recognition, music generation
Healthcare Disease detection, medical imaging
Self-driving cars Lane detection, pedestrian recognition
Robotics Visual perception and control
55
Industry Use Case
Healthcare Medical imaging, drug discovery
Finance Report generation, data simulation
Design Logo creation, website mockups
Definition
Linear Regression is a supervised machine learning algorithm used to predict a continuous
(numeric) value based on one or more input features (independent variables).
It models the relationship between variables by fitting a straight line (called the regression line)
through the data.
It answers questions like: “How does the price of a house change with its size?”
The Equation
For Simple Linear Regression (1 input feature):
56
y=mx+by = mx + by=mx+b
Where:
y = predicted value (dependent variable)
x = input feature (independent variable)
m = slope (how much y changes with x)
b = intercept (value of y when x = 0)
For Multiple Linear Regression (multiple features):
y=b0+b1x1+b2x2+...+bnxny = b_0 + b_1x_1 + b_2x_2 + ... + b_nx_ny=b0+b1x1+b2x2+...+bnxn
Use Cases
Scenario Input (X) Output (Y)
House price prediction Size, bedrooms, location Price
Salary estimation Experience, education level Annual salary
Sales forecasting Ad spend, past sales Future sales
Temperature prediction Time of day, humidity Temperature
Performance Metrics
Metric Meaning
R² Score % of variance explained by the model
MSE (Mean Squared
Average squared error of predictions
Error)
RMSE Root of MSE – interpretable like original units
MAE Mean absolute error – average magnitude of errors
# Sample data
X = [[1000], [1500], [2000]] # Size of house
y = [200000, 250000, 300000] # Price
# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y)
# Predict
predictions = model.predict(X_test)
# Evaluate
print("MSE:", mean_squared_error(y_test, predictions))
# Example data
X = np.array([[150], [160], [170], [180], [190]]) # height in cm
y = np.array([50, 60, 65, 70, 80]) # weight in kg
model = LinearRegression()
model.fit(X, y)
59
Step-by-Step Simple Linear Regression
61
Step-by-Step Multiple Linear Regression
63
Conclusion
Tic Tac Toe is a deceptively simple game that offers profound educational and technical value.
Through its 3×3 grid and minimal rules, it introduces players and developers alike to key principles in
logic, strategy, and artificial intelligence. Its finite number of game states makes it a "solved game,"
meaning the outcome can be predicted with perfect play. This characteristic allows learners to explore
concepts such as game trees, state evaluation, and minimax algorithms in a manageable environment.
From a programming perspective, implementing Tic Tac Toe is often a beginner’s first foray into
interactive application development. It challenges the developer to think critically about user input
validation, game state management, condition checking, and user interface feedback. It also serves as
a gateway into more advanced topics like AI-driven opponents and GUI development.
In terms of game theory, Tic Tac Toe serves as a practical example of zero-sum games and Nash
equilibrium. It demonstrates how certain outcomes (win, lose, or draw) are not just probable but
predictable when both players act rationally.
Beyond academics and software, Tic Tac Toe highlights important human-centric ideas such as turn-
taking, fairness, and strategic planning. It is universally recognizable and easy to understand, making
it an enduring tool in both education and entertainment.
In summary, Tic Tac Toe is more than just a simple game — it’s a versatile platform for learning,
experimentation, and understanding foundational principles in computer science and game theory.
64
Project Conclusion
This project on Tic Tac Toe successfully demonstrates the design, logic, and implementation of a
classic two-player game using both programming logic and user interaction principles. Through the
development process, we implemented core game functionalities such as turn-based play, win/draw
detection, game reset, and a simple user interface.
The project not only strengthened our understanding of conditional logic, loops, and event handling,
but also emphasized the importance of user experience and code organization. It served as an
excellent introduction to building interactive applications, providing a practical foundation for more
complex game or software development in the future.
Overall, the Tic Tac Toe project achieved its objectives: creating a functional, user-friendly game
while reinforcing key programming concepts and encouraging logical thinking and problem-solving
skills.
65