Total Pageviews

Thursday, September 10, 2026

🌸 K-Nearest Neighbors (KNN) Implementation on Iris Dataset using Python

🌸 K-Nearest Neighbors (KNN)

Implementation on Iris Dataset using Python

Classification • Accuracy • Confusion Matrix • Classification Report

📌 Objective

The objective is to build a KNN classification model using the famous Iris dataset. The model learns from flower measurements and predicts whether a flower belongs to Iris Setosa, Iris Versicolor, or Iris Virginica.

```

The Iris dataset contains four important numerical features:

  • 🌿 Sepal Length
  • 🌿 Sepal Width
  • 🌸 Petal Length
  • 🌸 Petal Width
```

💻 Complete Python Program


# ---------------------------------------------------------
# KNN IMPLEMENTATION ON IRIS DATASET
# ---------------------------------------------------------

# 1. Import required libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import (
    accuracy_score,
    confusion_matrix,
    classification_report,
    ConfusionMatrixDisplay
)

# ---------------------------------------------------------
# 2. Load Iris Dataset
# ---------------------------------------------------------

iris = load_iris()

X = iris.data
y = iris.target

feature_names = iris.feature_names
target_names = iris.target_names

print("Feature Names:")
print(feature_names)

print("\nTarget Classes:")
print(target_names)

# ---------------------------------------------------------
# 3. Create DataFrame
# ---------------------------------------------------------

df = pd.DataFrame(X, columns=feature_names)
df["species"] = [target_names[i] for i in y]

print("\nFirst Five Records:")
print(df.head())

# ---------------------------------------------------------
# 4. Split Dataset into Training and Testing Data
# ---------------------------------------------------------

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

print("\nTraining Samples:", len(X_train))
print("Testing Samples :", len(X_test))

# ---------------------------------------------------------
# 5. Feature Scaling
# ---------------------------------------------------------

scaler = StandardScaler()

X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# ---------------------------------------------------------
# 6. Create KNN Model
# ---------------------------------------------------------

k = 5

knn = KNeighborsClassifier(n_neighbors=k)

# ---------------------------------------------------------
# 7. Train the Model
# ---------------------------------------------------------

knn.fit(X_train_scaled, y_train)

# ---------------------------------------------------------
# 8. Predict Test Data
# ---------------------------------------------------------

y_pred = knn.predict(X_test_scaled)

print("\nActual Values:")
print(y_test)

print("\nPredicted Values:")
print(y_pred)

# ---------------------------------------------------------
# 9. Calculate Accuracy
# ---------------------------------------------------------

accuracy = accuracy_score(y_test, y_pred)

print("\nAccuracy:", round(accuracy * 100, 2), "%")

# ---------------------------------------------------------
# 10. Confusion Matrix
# ---------------------------------------------------------

cm = confusion_matrix(y_test, y_pred)

print("\nConfusion Matrix:")
print(cm)

# ---------------------------------------------------------
# 11. Classification Report
# ---------------------------------------------------------

print("\nClassification Report:")
print(
    classification_report(
        y_test,
        y_pred,
        target_names=target_names
    )
)

# ---------------------------------------------------------
# 12. Display Confusion Matrix
# ---------------------------------------------------------

disp = ConfusionMatrixDisplay(
    confusion_matrix=cm,
    display_labels=target_names
)

disp.plot()
plt.title("KNN Confusion Matrix - Iris Dataset")
plt.show()

# ---------------------------------------------------------
# 13. Test a New Flower
# ---------------------------------------------------------

new_flower = np.array([
    [5.1, 3.5, 1.4, 0.2]
])

new_flower_scaled = scaler.transform(new_flower)

prediction = knn.predict(new_flower_scaled)

print("\nNew Flower Measurements:")
print(new_flower)

print("\nPredicted Species:")
print(target_names[prediction[0]])

# ---------------------------------------------------------
# END
# ---------------------------------------------------------

🔎 Step-by-Step Explanation

```

1️⃣ Load Dataset

load_iris() loads the built-in Iris dataset from Scikit-learn.

2️⃣ Select Features

Four measurements are used as input features: sepal length, sepal width, petal length and petal width.

3️⃣ Split Dataset

80% of the observations are used for training and 20% are used for testing.

4️⃣ Scaling

StandardScaler puts the numerical features on a comparable scale. This is useful for distance-based algorithms such as KNN.

5️⃣ Choose K

Here K = 5. The model considers the five nearest training observations when making a prediction.

6️⃣ Train Model

knn.fit() prepares the KNN classifier using the scaled training data.

7️⃣ Prediction

The model finds nearby training examples and assigns the class having the majority vote.

8️⃣ Evaluation

Accuracy, confusion matrix and classification report are used to evaluate the classifier.

```

📐 How KNN Works Mathematically

```

KNN calculates the distance between a new data point and existing training points. A common distance measure is Euclidean distance.

d = √[(x₁-y₁)² + (x₂-y₂)² + ... + (xₙ-yₙ)²]

After calculating the distances, KNN selects the K nearest observations and uses majority voting to determine the predicted class.

Example: If K = 5 and the nearest five flowers contain:

  • 3 → Setosa
  • 1 → Versicolor
  • 1 → Virginica

The new flower is classified as Iris Setosa because Setosa receives the majority vote.

```

📊 Evaluation Measures

```
Measure Meaning
Accuracy Percentage of correctly classified observations.
Confusion Matrix Shows actual classes versus predicted classes.
Precision Measures how many predicted members of a class were actually correct.
Recall Measures how many actual members of a class were correctly identified.
F1-score Harmonic mean of precision and recall.
```

🎓 Important Points for Students

```
  • KNN is a supervised machine learning algorithm.
  • It can be used for classification and regression.
  • KNN is called a lazy learning algorithm because it does not build a conventional model during training.
  • The value of K strongly influences the prediction.
  • Small K values can make the model sensitive to noise.
  • Large K values can make the model less sensitive to local patterns.
  • Feature scaling is important because KNN relies on distances.
  • For Iris classification, the four flower measurements are used to predict one of three species.
```
Python • Machine Learning • KNN • Iris Dataset

Wednesday, September 9, 2026

LIST


🐍 List in Python

Understanding Python Lists with Examples

1. What is a List?

A List in Python is an ordered and mutable collection of elements. A list can contain numbers, strings, Boolean values, or even other lists. Lists are created using square brackets [ ].

my_list = [10, 20, 30, 40, 50] 
print(my_list)

Output:
[10, 20, 30, 40, 50]

2. Creating a List

numbers = [10, 20, 30, 40] 
 names = ["Rahul", "Amit", "Priya"] 
 mixed = [10, "Python", 3.14, True] empty = []


Output:
numbers → [10, 20, 30, 40]
names → ['Rahul', 'Amit', 'Priya']
mixed → [10, 'Python', 3.14, True]
empty → []

3. Important Properties of a List

Property Description
Ordered Elements maintain their insertion order.
Mutable Elements can be changed after creation.
Allows duplicates The same value can appear multiple times.
Heterogeneous A list can contain different data types.
Indexed Every element has a position/index.

4. List Indexing

Python uses zero-based indexing. Therefore, the first element has index 0.

 fruits = ["Apple", "Mango", "Banana", "Orange"] 
 print(fruits[0])
 print(fruits[2]) 
print(fruits[-1])

 Output:
Apple
Banana
Orange

💡 Tip: Negative indexing starts from the end. -1 represents the last element.

5. List Slicing

Slicing is used to extract a portion of a list.

numbers = [10, 20, 30, 40, 50] 
 print(numbers[1:4]) 
print(numbers[:3]) 
print(numbers[2:])

Output:
[20, 30, 40]
[10, 20, 30]
[30, 40, 50]

6. Changing List Elements

numbers = [10, 20, 30, 40] 
numbers[1] = 200 
print(numbers)

 Output:
[10, 200, 30, 40]

✅ Lists are mutable, so their elements can be modified after the list has been created.

7. Adding Elements to a List

numbers = [10, 20, 30] 
numbers.append(40) 
print(numbers)

Output:
[10, 20, 30, 40]

append() adds one element at the end of the list.

numbers = [10, 20, 30] 
numbers.insert(1, 15)
print(numbers)

 Output:
[10, 15, 20, 30]

insert(index, value) adds an element at a specific position.

8. Removing Elements

numbers = [10, 20, 30, 40]
numbers.remove(30)
print(numbers)

Output:
[10, 20, 40]

numbers = [10, 20, 30, 40]
numbers.pop() 
print(numbers)
Output:
[10, 20, 30]

9. Important List Methods

Method Purpose
append() Adds an element at the end.
insert() Adds an element at a specified position.
remove() Removes a specified value.
pop() Removes an element using its index.
clear() Removes all elements.
sort() Sorts the list.
reverse() Reverses the list.
count() Counts occurrences of a value.
index() Returns the index of a value.

10. Sorting a List

numbers = [50, 10, 40, 20, 30] 
numbers.sort() 
print(numbers)
 Output:
[10, 20, 30, 40, 50]

numbers.sort(reverse=True) print(numbers)

Output:
[50, 40, 30, 20, 10]

11. Traversing a List

 numbers = [10, 20, 30, 40, 50] 
for n in numbers:
    print(n)

 Output:
10
20
30
40
50

12. List Length

numbers = [10, 20, 30, 40, 50]
print(len(numbers))

 Output:
5

13. List Comprehension

List comprehension provides a short and elegant way to create a new list from an existing iterable.
squares = [x * x for x in range(1, 6)] 
 print(squares)

 Output:
[1, 4, 9, 16, 25]

14. Example: Student Marks

 marks = [75, 82, 68, 91, 88] 
 total = sum(marks) 
average = total / len(marks) 
print("Total =", total)
print("Average =", average)

 Output:
Total = 404
Average = 80.8

15. Quick Revision

✔ List is ordered
✔ List is mutable
✔ List uses [ ] brackets
✔ Index starts from 0
✔ Negative indexing is supported
✔ Duplicate values are allowed
✔ Different data types can be stored
✔ List supports slicing
✔ Lists provide many built-in methods

Types of errors in programming


⚠️ Types of Errors in Programming

Understanding Errors in Python Programming

📘 What is an Error?

An error is a problem in a program that prevents the program from executing correctly or producing the expected result. Errors can occur because of incorrect syntax, invalid operations, wrong data, or incorrect program logic.

In Python, errors are generally classified into Syntax Errors, Runtime Errors (Exceptions), and Logical Errors.

🔹 Major Types of Programming Errors

1. Syntax Error Violation of Python's grammar or syntax rules.
2. Runtime Error An error that occurs while the program is executing.
3. Logical Error Program executes but produces an incorrect result.
4. Semantic Error The statement may be syntactically valid but does not express the intended meaning.

1️⃣ Syntax Error

A Syntax Error occurs when the rules of the programming language are violated.

Example

print("Hello"
❌ Missing closing parenthesis ).

Another Example

if age >= 18 print("Adult")
❌ Missing colon : after the condition.

Correct Code

if age >= 18: print("Adult")
Output: Adult

2️⃣ Runtime Error

A Runtime Error occurs while the program is running. The syntax may be correct, but an invalid operation occurs during execution.

Example: Division by Zero

a = 10
b = 0
print(a / b)
ZeroDivisionError: division by zero

Python successfully understands the syntax, but division by zero is not a valid mathematical operation.

Example: Invalid List Index

numbers = [10, 20, 30] print(numbers[5])
IndexError: list index out of range

3️⃣ Common Runtime Errors / Exceptions

Exception Cause Example
ZeroDivisionError Division by zero 10 / 0
ValueError Invalid value int("abc")
TypeError Incompatible data types "10" + 5
NameError Variable is not defined print(x)
IndexError Invalid sequence index list[10]
KeyError Missing dictionary key dict["unknown"]
FileNotFoundError Requested file does not exist open("abc.txt")
AttributeError Invalid object attribute or method number.upper()

4️⃣ ValueError

A ValueError occurs when the data type is appropriate but the actual value is invalid.

age = int("hello")
print(age)
ValueError: invalid literal for int()

5️⃣ TypeError

A TypeError occurs when an operation is performed on incompatible data types.

a = "10"
 b = 5 
 print(a + b)
TypeError: can only concatenate str to str

Correct Approach

a = "10"
 b = 5 
 print(int(a) + b)
15

6️⃣ Logical Error

A Logical Error occurs when the program runs without producing an error message, but the result is incorrect.

Example

a = 10
 b = 20
 average = a + b / 2
 print(average)
20.0
⚠️ The expected average is 15, but the program produces 20.

Correct Code

a = 10 
b = 20 
 average = (a + b) / 2 
 print(average)
15.0

There is no syntax or runtime error. The programmer simply used the wrong expression.

7️⃣ Semantic Error

A Semantic Error occurs when a statement is syntactically valid but its meaning does not match the programmer's intention.

Example

length = 10
 width = 5 
 area = length + width
 print(area)
15
⚠️ The formula for the area of a rectangle should be: Area = length × width.

Correct Code

length = 10
width = 5 
area = length * width 
print(area)
50

📊 Difference Between Major Errors

Error Type When Occurs? Program Executes? Example
Syntax Error Before execution ❌ No Missing :
Runtime Error During execution ❌ Stops at error 10 / 0
Logical Error During program design ✅ Yes Wrong formula
Semantic Error When meaning is incorrect ✅ Usually Wrong operation

🛡️ Handling Runtime Errors

Python provides try-except statements to handle exceptions and prevent abnormal termination of a program.

try: a = 10
b = 0
print(a / b) 
 except ZeroDivisionError: 
print("Cannot divide by zero")
Cannot divide by zero

🔍 How to Find and Correct Errors?

  1. Read the error message carefully.
  2. Check the line number mentioned by Python.
  3. Check spelling of variables and functions.
  4. Check indentation.
  5. Check data types.
  6. Check mathematical formulas and logic.
  7. Use print statements to inspect values.
  8. Use a debugger when necessary.
  9. Test the program with different inputs.

✅ Advantages of Error Detection

  • Helps identify problems in programs.
  • Improves program reliability.
  • Makes debugging easier.
  • Prevents incorrect results.
  • Improves software quality.
  • Helps programmers understand incorrect code.

❌ Problems Caused by Errors

  • Program may terminate unexpectedly.
  • Incorrect results may be produced.
  • Debugging can take significant time.
  • Runtime errors can affect users.
  • Logical errors can be difficult to detect because the program runs.

🎯 Important Examination Points

Syntax Error
Runtime Error
Logical Error
Semantic Error
Exception
try-except
  • Syntax Error: Violation of language grammar.
  • Runtime Error: Occurs during program execution.
  • Logical Error: Program runs but gives wrong output.
  • ValueError: Correct type but inappropriate value.
  • TypeError: Operation performed on incompatible types.
  • ZeroDivisionError: Division by zero.
  • IndexError: Invalid list/string/tuple index.
  • NameError: Undefined variable or name.
  • try-except: Used for handling exceptions.

📌 Quick Summary

Error Meaning
Syntax Error Incorrect grammar/syntax
Runtime Error Problem during execution
Logical Error Incorrect result due to wrong logic
Semantic Error Incorrect meaning or intention
Remember: Syntax errors prevent execution, runtime errors occur during execution, while logical errors allow execution but produce an incorrect result.
```

OPERATOR


🐍 OPERATORS IN PYTHON

Arithmetic • Relational • Logical • Assignment • Ternary • Bitwise • Increment / Decrement

📘 1. What is an Operator?

An operator is a symbol or keyword used to perform an operation on one or more values, called operands.

Example: 10 + 20
Here, + is the operator and 10 and 20 are operands.

📚 2. Types of Operators in Python

➕ Arithmetic
Mathematical calculations
⚖️ Relational
Compare values
🧠 Logical
Combine conditions
📝 Assignment
Assign values
❓ Ternary
Conditional expression
💻 Bitwise
Operate on bits
🔄 Increment / Decrement
Value modification

1️⃣ ➕ Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations on numerical values.
Operator Name Example Result
+ Addition 10 + 3 13
- Subtraction 10 - 3 7
* Multiplication 10 * 3 30
/ Division 10 / 3 3.333...
// Floor Division 10 // 3 3
% Modulus 10 % 3 1
** Exponentiation 2 ** 3 8
a = 10
b = 3

print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)
13
7
30
3.3333333333333335
3
1
1000

2️⃣ ⚖️ Relational / Comparison Operators

Relational operators compare two values and return either True or False.
Operator Meaning Example Result
== Equal to 10 == 10 True
!= Not equal to 10 != 5 True
> Greater than 10 > 5 True
< Less than 10 < 5 False
>= Greater than or equal 10 >= 10 True
<= Less than or equal 5 <= 10 True
a = 10
b = 5

print(a == b)
print(a != b)
print(a > b)
print(a < b)
print(a >= b)
print(a <= b)
False
True
True
False
True
False

3️⃣ 🧠 Logical / Boolean Operators

Logical operators are used to combine multiple conditions. They return True or False when used with Boolean conditions.
Operator Meaning Example
and True if both conditions are True A and B
or True if at least one condition is True A or B
not Reverses the Boolean result not A

Example: and

a = 10

print(a > 5 and a < 20)
True

Example: or

a = 10

print(a < 5 or a > 5)
True

Example: not

a = True

print(not a)
False

4️⃣ 📝 Assignment Operators

Assignment operators are used to assign or update values stored in variables.
Operator Example Equivalent Expression
= x = 10 x = 10
+= x += 5 x = x + 5
-= x -= 5 x = x - 5
*= x *= 5 x = x * 5
/= x /= 5 x = x / 5
//= x //= 5 x = x // 5
%= x %= 5 x = x % 5
**= x **= 2 x = x ** 2
&= x &= 2 x = x & 2
|= x |= 2 x = x | 2
^= x ^= 2 x = x ^ 2
>>= x >>= 1 x = x >> 1
<<= x <<= 1 x = x << 1
x = 10

x += 5
print(x)

x *= 2
print(x)

x -= 5
print(x)
15
30
25

5️⃣ ❓ Ternary Operator

Python does not have a separate ?: operator like C or Java. Instead, Python provides a conditional expression, commonly called the ternary operator.

Syntax

value_if_true if condition else value_if_false

Example

age = 20

result = "Adult" if age >= 18 else "Minor"

print(result)
Adult

Another Example

a = 10
b = 20

largest = a if a > b else b

print(largest)
20
💡 The ternary expression is useful when a simple if-else decision needs to be written in one line.

6️⃣ 💻 Bitwise Operators

Bitwise operators work directly on the binary representation of integer values.
Operator Name Example
& Bitwise AND 5 & 3
| Bitwise OR 5 | 3
^ Bitwise XOR 5 ^ 3
~ Bitwise NOT ~5
<< Left Shift 5 << 1
>> Right Shift 5 >> 1

Example

a = 5
b = 3

print(a & b)
print(a | b)
print(a ^ b)
print(~a)
print(a << 1)
print(a >> 1)
1
7
6
-6
10
2

🔢 7️⃣ Bitwise Operation Example

Consider:

a = 5
b = 3

Binary representations:

Decimal Binary
5 0101
3 0011

Bitwise AND

5 & 3
0101
0011
----
0001
Result = 1

Bitwise OR

0101
0011
----
0111
Result = 7

Bitwise XOR

0101
0011
----
0110
Result = 6

7️⃣ 🔄 Increment and Decrement Operators

Python does not provide the ++ increment or -- decrement operators found in languages such as C, C++ and Java.

Instead, Python uses += 1 and -= 1.

Increment

x = 10

x += 1

print(x)
11

Decrement

x = 10

x -= 1

print(x)
9
⚠️ Remember: x++ and x-- are invalid syntax in Python.

⚖️ 8️⃣ Python vs C/Java Increment Operators

Operation C / Java Python
Increment x++ x += 1
Decrement x-- x -= 1
Increase by 5 x += 5 x += 5
Decrease by 5 x -= 5 x -= 5

🧮 9️⃣ Combined Example

a = 10
b = 5

# Arithmetic
print(a + b)

# Relational
print(a > b)

# Logical
print(a > 5 and b < 10)

# Assignment
a += 2
print(a)

# Ternary
result = "Large" if a > 10 else "Small"
print(result)

# Bitwise
print(a & b)

# Increment
a += 1
print(a)

# Decrement
a -= 1
print(a)
15
True
True
12
Large
4
13
12

✅ Advantages of Operators

  • Make mathematical calculations simple.
  • Allow comparison between values.
  • Help combine multiple conditions.
  • Make variable updates easy.
  • Support conditional expressions.
  • Bitwise operators provide low-level bit manipulation.
  • Make programs shorter and more expressive.

❌ Common Problems / Limitations

  • Incorrect operator selection can produce wrong results.
  • Operator precedence can sometimes be confusing for beginners.
  • Bitwise operations require understanding binary numbers.
  • Python does not support ++ and --.
  • Division by zero causes an error.

🎯 Important Points for Examination

  1. + performs addition.
  2. - performs subtraction.
  3. * performs multiplication.
  4. / performs division.
  5. // performs floor division.
  6. % returns the remainder.
  7. ** performs exponentiation.
  8. Relational operators return True or False.
  9. and, or, not are logical operators.
  10. Assignment operators assign or update values.
  11. Python uses conditional expressions instead of the C-style ?: operator.
  12. Bitwise operators work on binary representations of integers.
  13. Python does not support ++ and --.
  14. Use += 1 for increment.
  15. Use -= 1 for decrement.

📌 Quick Summary

Operator Type Main Operators Purpose
Arithmetic + - * / // % ** Mathematical calculations
Relational == != > < >= <= Compare values
Logical and, or, not Combine conditions
Assignment = += -= *= /= %= **= Assign/update values
Ternary x if condition else y Short conditional decision
Bitwise & | ^ ~ << >> Bit-level operations
Increment += 1 Increase value
Decrement -= 1 Decrease value
```

Strings


🐍 STRINGS AND STRING FUNCTIONS IN PYTHON

Creating, Accessing, Manipulating and Processing Strings

📘 1. What is a String?

A string is a sequence of characters enclosed within single quotes, double quotes, or triple quotes.

Strings can contain: letters, numbers, spaces, symbols and special characters.
name = "Python"
college = 'Computer Science'
message = """Welcome to Python Programming"""

🔤 2. Creating Strings

str1 = 'Hello'
str2 = "Python"
str3 = '''Programming'''
str4 = """Computer Science"""
Hello
Python
Programming
Computer Science

3️⃣ Single and Double Quotes

a = 'Hello'
b = "World"

print(a)
print(b)
Hello
World
💡 Single quotes and double quotes can both be used to create strings.

4️⃣ Triple-Quoted Strings

Triple quotes are commonly used for multiline strings.

message = """Python
is
easy to learn."""

print(message)
Python
is
easy to learn.

🔒 5. Strings are Immutable

Strings in Python are immutable. This means that individual characters of an existing string cannot be changed directly.
text = "Python"

# text[0] = "J"   # Error
⚠️ A new string must be created if the value needs to be changed.
text = "Python"
text = "J" + text[1:]

print(text)
Jython

6️⃣ String Indexing

Each character has an index position.

text = "PYTHON"

print(text[0])
print(text[1])
print(text[5])
P
Y
N
Character P Y T H O N
Positive Index 0 1 2 3 4 5
Negative Index -6 -5 -4 -3 -2 -1

7️⃣ String Slicing

text = "PYTHON"

print(text[0:3])
print(text[2:6])
print(text[:4])
print(text[2:])
PYT
THON
PYTH
THON
Syntax: string[start : stop : step]

8️⃣ String Concatenation

The + operator joins two or more strings.

first = "Hello"
second = "Python"

result = first + " " + second

print(result)
Hello Python

9️⃣ String Repetition

The * operator can repeat a string.

print("Python " * 3)
Python Python Python

🔢 10. len() Function

The len() function returns the number of characters in a string.

text = "Python"

print(len(text))
6

🛠️ 11. Important String Functions and Methods

len()
Returns string length.
lower()
Converts characters to lowercase.
upper()
Converts characters to uppercase.
capitalize()
Capitalizes the first character.
title()
Capitalizes the first character of each word.
swapcase()
Swaps uppercase and lowercase characters.
strip()
Removes leading and trailing whitespace.
replace()
Replaces part of a string.
split()
Splits a string into a list.
join()
Joins elements into a string.
find()
Finds the position of a substring.
count()
Counts occurrences.
startswith()
Checks the beginning of a string.
endswith()
Checks the ending of a string.
isdigit()
Checks whether all characters are digits.
isalpha()
Checks whether all characters are alphabetic.

1️⃣2️⃣ lower()

text = "PYTHON"

print(text.lower())
python

1️⃣3️⃣ upper()

text = "python"

print(text.upper())
PYTHON

1️⃣4️⃣ capitalize()

text = "python programming"

print(text.capitalize())
Python programming

1️⃣5️⃣ title()

text = "python programming language"

print(text.title())
Python Programming Language

1️⃣6️⃣ swapcase()

text = "Python"

print(text.swapcase())
pYTHON

1️⃣7️⃣ strip()

text = "   Python   "

print(text.strip())
Python

1️⃣8️⃣ replace()

text = "I like Java"

print(text.replace("Java", "Python"))
I like Python

1️⃣9️⃣ find()

text = "Python Programming"

print(text.find("Program"))
7

The returned value is the starting index of the searched substring. If the substring is not found, find() returns -1.

2️⃣0️⃣ count()

text = "banana"

print(text.count("a"))
3

2️⃣1️⃣ split()

text = "Python is easy"

words = text.split()

print(words)
['Python', 'is', 'easy']

2️⃣2️⃣ join()

words = ["Python", "is", "easy"]

result = " ".join(words)

print(result)
Python is easy

2️⃣3️⃣ startswith() and endswith()

text = "Python Programming"

print(text.startswith("Python"))
print(text.endswith("Programming"))
True
True

2️⃣4️⃣ isalpha()

text = "Python"

print(text.isalpha())
True

2️⃣5️⃣ isdigit()

text = "12345"

print(text.isdigit())
True

🎨 2️⃣6️⃣ String Formatting

String formatting allows values to be inserted into strings.

name = "Bijan"
age = 25

print(f"My name is {name} and I am {age} years old.")
My name is Bijan and I am 25 years old.
💡 f-string is a convenient way to insert variables inside a string using { }.

🔐 2️⃣7️⃣ Escape Characters

Escape Character Meaning
\n New line
\t Tab
\\ Backslash
\' Single quote
\" Double quote
print("Hello\nPython")
print("Name\tAge")
Hello
Python
Name    Age

⚖️ 2️⃣8️⃣ String Comparison

a = "apple"
b = "banana"

print(a == b)
print(a != b)
False
True

Strings can be compared using operators such as ==, !=, <, >, <= and >=.

🔍 2️⃣9️⃣ Membership Operators

text = "Python Programming"

print("Python" in text)
print("Java" not in text)
True
True

🎮 3️⃣0️⃣ Interactive String Demonstration

Click a button to see a common string operation.

Result will appear here...

✅ Advantages of Strings in Python

  • Easy to create and manipulate.
  • Large number of built-in methods are available.
  • Supports indexing and slicing.
  • Supports Unicode characters.
  • Useful for text processing.
  • Can be combined using concatenation.
  • Useful in web development, data processing and file handling.
  • Immutable nature makes strings predictable and safe to use.

❌ Limitations of Strings

  • Individual characters cannot be changed directly.
  • Repeated string modification may create new string objects.
  • Very large text processing may require efficient techniques.
  • Incorrect indexing can produce an IndexError.

📋 Important String Functions / Methods at a Glance

Function / Method Purpose Example
len() Find length len("Python")
lower() Lowercase "PYTHON".lower()
upper() Uppercase "python".upper()
capitalize() Capitalize first character "python".capitalize()
title() Title case "python language".title()
strip() Remove surrounding whitespace " Python ".strip()
replace() Replace text "Java".replace("Java","Python")
find() Find substring position "Python".find("th")
count() Count occurrences "banana".count("a")
split() Split into list "A B C".split()
join() Join strings "-".join(["A","B"])
startswith() Check beginning "Python".startswith("Py")
endswith() Check ending "Python".endswith("on")
isalpha() Check alphabetic characters "Python".isalpha()
isdigit() Check digits "123".isdigit()

🎯 Important Points for Examination

  1. A string is a sequence of characters.
  2. Strings can be enclosed in single, double or triple quotes.
  3. Python strings are immutable.
  4. String indexing starts from 0.
  5. Negative indexing starts from -1.
  6. String slicing uses [start:stop:step].
  7. len() returns the length of a string.
  8. lower() converts a string to lowercase.
  9. upper() converts a string to uppercase.
  10. split() converts a string into a list.
  11. join() joins elements into a string.
  12. find() returns the position of a substring.
  13. replace() replaces one substring with another.
  14. isalpha() checks alphabetic characters.
  15. isdigit() checks whether all characters are digits.

📌 Quick Summary

Concept Example
Create String "Python"
Indexing "Python"[0]
Slicing "Python"[0:3]
Length len("Python")
Uppercase "python".upper()
Lowercase "PYTHON".lower()
Replace "Java".replace("Java","Python")
Split "A B".split()
Join "-".join(["A","B"])
Find "Python".find("th")
```

Indentation.

```html

🐍 INDENTATION IN PYTHON

Understanding Python's Block Structure

📘 What is Indentation?

Indentation means adding spaces or tabs at the beginning of a line of code to define a block of statements.

In Python, indentation is not optional. It is used to identify which statements belong to a particular block such as if, else, for, while, function, class, etc.

1️⃣ Simple Example

if 10 > 5:
    print("10 is greater than 5")
10 is greater than 5

The print() statement is indented, so Python understands that it belongs to the if block.

2️⃣ How Indentation Works

if condition:

Indentation
Statement 1
Statement 2

All statements having the same indentation level belong to the same block.

3️⃣ Standard Indentation

Python's recommended standard is 4 spaces for each indentation level.

if True:
    print("Statement 1")
    print("Statement 2")
Statement 1
Statement 2
💡 Tip: Most Python programmers use 4 spaces for one indentation level.

4️⃣ What Happens Without Indentation?

if 10 > 5:
print("Correct")
IndentationError: expected an indented block

Python generates an IndentationError because the statement inside the if block is not indented.

5️⃣ Indentation with if-else

age = 20

if age >= 18:
    print("Adult")
else:
    print("Minor")
Adult

Notice that both print() statements are indented inside their respective blocks.

6️⃣ Indentation in Nested Statements

age = 20

if age >= 18:
    if age >= 60:
        print("Senior Citizen")
    else:
        print("Adult")
Adult

Here there are two indentation levels:

Level Statement
Level 0 if age >= 18:
Level 1 if age >= 60:
Level 2 print("Senior Citizen")

7️⃣ Indentation with for Loop

for i in range(1, 4):
    print(i)
1
2
3

The indented print(i) statement executes during each iteration of the loop.

8️⃣ Indentation in Functions

def greet():
    print("Hello")
    print("Welcome to Python")

greet()
Hello
Welcome to Python

The two print() statements form the body of the function because they are indented.

9️⃣ Multiple Indentation Levels

for i in range(1, 3):
    if i == 1:
        print("One")
    else:
        print("Two")
One
Two

Different indentation levels allow Python to identify nested blocks.

🔟 Same Indentation = Same Block

if True:
    a = 10
    b = 20
    print(a + b)
30

All three statements have the same indentation and therefore belong to the same if block.

⚠️ Spaces vs Tabs

Method Description
Spaces Recommended approach; normally 4 spaces per level.
Tabs Can be used, but mixing tabs and spaces can cause errors.
⚠️ Important: Do not mix tabs and spaces inconsistently within the same Python block.

🧱 Python Block Structure

if condition:
    statement 1
    statement 2
    statement 3

statement 4

Here, statements 1, 2 and 3 are inside the if block, while statement 4 is outside the block.

✅ Advantages of Indentation

  • Makes Python code easy to read.
  • Clearly defines blocks of code.
  • Improves program structure.
  • Reduces the need for braces such as { }.
  • Makes nested statements easier to understand.
  • Encourages clean and consistent programming.
  • Helps identify the scope of statements visually.

❌ Problems Caused by Incorrect Indentation

  • Can produce IndentationError.
  • Incorrect indentation can change program logic.
  • Mixing tabs and spaces may cause errors.
  • Beginners may initially find indentation confusing.
  • Moving a statement to the wrong level can change its block.

📏 Rules of Indentation in Python

  1. Indentation is mandatory for Python blocks.
  2. Use consistent indentation throughout the program.
  3. Four spaces are conventionally used for one indentation level.
  4. Statements belonging to the same block must have the same indentation.
  5. Nested blocks require additional indentation.
  6. Do not mix tabs and spaces inconsistently.
  7. A colon : generally introduces a new indented block.

🚨 Common Indentation Errors

Error Reason
IndentationError Expected indentation is missing.
Unexpected indentation A line has more indentation than expected.
Inconsistent indentation Different indentation styles are used incorrectly.

🎯 Important Points for Examination

  1. Python uses indentation to define blocks of code.
  2. Indentation is mandatory in Python.
  3. Four spaces are conventionally used for one indentation level.
  4. Statements in the same block must have the same indentation.
  5. Nested blocks require additional indentation.
  6. Incorrect indentation can produce IndentationError.
  7. Python does not normally use braces { } to define blocks.
  8. Do not mix tabs and spaces inconsistently.

📌 Quick Summary

Concept Meaning
Indentation Spaces/tabs at the beginning of a line.
Purpose Defines blocks of Python code.
Recommended 4 spaces per indentation level.
Same level Statements belong to the same block.
Nested block Requires additional indentation.
Wrong indentation May produce IndentationError or change program logic.
```

Using Python as calculator

```html

🐍 Using Python as a Calculator

Performing Arithmetic Calculations Using Python

📘 What is Python as a Calculator?

Python can be used like a simple calculator to perform addition, subtraction, multiplication, division, exponentiation and other mathematical operations.

We can directly type mathematical expressions at the Python prompt and immediately obtain the result.

1️⃣ Basic Calculation

For example, to add two numbers:

>>> 10 + 20
30

Python evaluates the expression and displays the result.

2️⃣ Arithmetic Operators in Python

Operator Operation Example Result
+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division 10 / 5 2.0
// Floor Division 10 // 3 3
% Modulus 10 % 3 1
** Exponentiation 2 ** 3 8

3️⃣ Addition

>>> 25 + 15
40

4️⃣ Subtraction

>>> 50 - 18
32

5️⃣ Multiplication

>>> 12 * 8
96

6️⃣ Division

>>> 20 / 4
5.0
💡 Important: The / operator normally returns a floating-point value.

7️⃣ Floor Division

>>> 20 // 6
3

Floor division returns the quotient after removing the fractional part for positive numbers.

8️⃣ Modulus Operator

>>> 20 % 6
2

The modulus operator % returns the remainder.

9️⃣ Exponentiation

>>> 2 ** 5
32
Mathematical meaning:
25 = 2 × 2 × 2 × 2 × 2 = 32

🔟 Order of Operations

Python follows the standard mathematical order of operations.

>>> 10 + 5 * 2
20

Multiplication is performed before addition.

>>> (10 + 5) * 2
30

Parentheses can be used to change the order of evaluation.

🧮 Complex Mathematical Expression

>>> (25 + 15) * 2 / 5
16.0

Python evaluates the complete mathematical expression automatically.

📦 Using Variables as a Calculator

a = 25
b = 15

sum = a + b

print(sum)
40

⌨️ Calculator Using User Input

a = float(input("Enter first number: "))
b = float(input("Enter second number: "))

print("Sum =", a + b)
print("Difference =", a - b)
print("Product =", a * b)
print("Division =", a / b)
Enter first number: 20
Enter second number: 5

Sum = 25.0
Difference = 15.0
Product = 100.0
Division = 4.0

🎮 Interactive Python Calculator Concept

Click a button to see the result of a Python expression.

Result will appear here...

✅ Advantages of Using Python as a Calculator

  • Very easy to perform mathematical calculations.
  • Supports integers and floating-point numbers.
  • Can evaluate complex expressions.
  • Supports many mathematical operators.
  • Calculations can be stored in variables.
  • Useful for learning programming fundamentals.
  • Can perform calculations using user input.
  • Useful for scientific and engineering calculations.

⚠️ Limitations

  • Python must be installed to use the Python interpreter.
  • Very large symbolic calculations may require special libraries.
  • Beginners must understand Python syntax.
  • Division by zero produces an error.

🎯 Important Points for Examination

  1. Python can be used as a calculator.
  2. + is used for addition.
  3. - is used for subtraction.
  4. * is used for multiplication.
  5. / performs true division.
  6. // performs floor division.
  7. % returns the remainder.
  8. ** is used for exponentiation.
  9. Parentheses can be used to control the order of evaluation.
  10. Python follows operator precedence rules.

📌 Quick Summary

Task Python Expression
Addition 10 + 5
Subtraction 10 - 5
Multiplication 10 * 5
Division 10 / 5
Floor Division 10 // 3
Remainder 10 % 3
Power 2 ** 3
```