0% found this document useful (0 votes)
14 views58 pages

Python Notes

The document is a comprehensive Python programming guide covering various topics including strings, functions, lists, file handling, and exception handling. It provides detailed explanations, examples, and methods for manipulating data types and structures in Python. Key concepts such as list operations, string methods, and error handling techniques are summarized for quick reference.

Uploaded by

kaiqian8
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views58 pages

Python Notes

The document is a comprehensive Python programming guide covering various topics including strings, functions, lists, file handling, and exception handling. It provides detailed explanations, examples, and methods for manipulating data types and structures in Python. Key concepts such as list operations, string methods, and error handling techniques are summarized for quick reference.

Uploaded by

kaiqian8
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Contents

String – str() ............................................................................................................ 2


Function.................................................................................................................. 5
List, Set, Tuple ......................................................................................................... 8
Python Functions & Methods Cheat Sheet ......................................................... 10
List ....................................................................................................................... 14
File Handling......................................................................................................... 18
Exception Handlings .............................................................................................. 23
Import .................................................................................................................. 27
import math ....................................................................................................... 27
import datetime.................................................................................................. 28
import random ................................................................................................... 30
import pandas .................................................................................................... 32
import openpyxl ................................................................................................. 39
Triangle Patterns (Loops) ....................................................................................... 44
Classes, Inheritance, and UML Diagram ................................................................. 52
Three types of numbers:

1. Integer- whole number – int()


2. Float – num with decimal – float()
3. Complex – combination of num+alphabet

Types of Booleans – bool()

1. TRUE – 1 or with content


2. FALSE – 0 or empty inputs

Types of Operators

A variable cannot begin with a number nor include special characters.

String – str()
1. enclosed either with single quotes like 'hello' or double quotes, like "hello"
2. To use the same type of quote within a string, that quote needs to be escaped with
a \ - backwards slash.

3. Accessing Characters in a String (Indexing): Strings are indexed, meaning you can
access individual characters using their position.

4. String Methods: Python provides many built-in methods to manipulate strings:

• .upper(): Converts to uppercase.


• .lower(): Converts to lowercase.
• .strip(): Removes leading and trailing spaces.
• .replace(): Replaces parts of a string.


• .split(): Splits a string into a list.

o 1. Default Split (Splitting on Whitespace):

o 2. Splitting by a Specific Character:

o 3. Using maxsplit to Limit the Splits:

maxsplit=2 performs only 2 splits:


First split: "Python"
Second split: "is"
The remaining text ("very fun") is kept together.

5. String Length: Use len() to find the length of a string.


6. Checking Substrings: Use the in keyword to check if a substring exists.

7. Formatting Strings:
- Use f-strings for dynamic formatting (most recommend)

- %-formatting

Advanced:

- .format()
1. Positional Arguments:

2. Using Index Numbers:


3. Named Arguments:

8. Slicing Strings: You can extract parts of a string using slicing

Function
1. a new line
2. indentation (press tab on your keyboard)
3. one or more lines
4. (optional) a return statement
Function argument
- Order matter
- Required arguments go first, then only optional arguments

Complex number
List, Set, Tuple
Python Functions & Methods Cheat Sheet

1. String & List Related

join()

• Joins elements of a list into a string (must be strings).


words = ["I", "love", "Python"]

sentence = " ".join(words)

print(sentence) # I love Python

split()

• Splits a string into a list.

text = "apple,banana,cherry"
fruits = [Link](",")

print(fruits) # ["apple", "banana", "cherry"]

strip()

• Removes leading/trailing whitespace (or characters).

s = " hello "

print([Link]()) # "hello"

2. List Methods

Adding & Removing

[Link](x) # Add to end

[Link](i, x) # Insert at index

[Link](x) # Remove first occurrence

[Link]() # Remove last


[Link](i) # Remove at index

del lst[i] # Delete item

[Link]() # Empty list

Finding
[Link](x) # Find index of value

[Link](x) # Count occurrences

Sorting

[Link]() # Sort in place

[Link](reverse=True) # Sort descending

sorted(lst) # Return new sorted list

3. Built-in Functions (work with list/tuple)

len(lst) # length

max(lst) # maximum value

min(lst) # minimum value


sum(lst) # sum of elements

any(lst) # True if any element is True

all(lst) # True if all elements are True

4. String Methods (common)

[Link]() # to UPPERCASE

[Link]() # to lowercase
[Link]() # Title Case

[Link]("a","o") # replace characters

[Link]("word") # find index

5. Type Conversions

list("hello") # ['h','e','l','l','o']

tuple([1,2,3]) # (1,2,3)
set([1,1,2]) # {1,2}

str(123) # "123"

int("456") # 456
6. Math Related (need import math)

import math

[Link](16) # 4.0
[Link](2, 3) # 8.0

[Link](2.3) # 3

[Link](2.9) # 2

[Link] # 3.14159...

7. Random Module (need import random)

import random

[Link](1, 10) # random int 1–10

[Link]([1,2,3]) # pick random element

[Link](lst) # shuffle list

8. File Handling Functions

f = open("[Link]", "r")

[Link]() # read whole file


[Link]() # read one line

[Link]() # read all lines

[Link]("text") # write text

[Link]()

Quick Summary

• String ↔ List → split() and join().

• List modification → append, insert, remove, pop, sort.

• Math → sqrt, ceil, floor, pow, pi.

• Random → randint, choice, shuffle.


• File → read, readline, write, close.
List
len(list) Count number of items in a list
[Link](item name) Add single item into a list

[Link]([item1, takes all items from iterable and adds them one by one.
item2])
[Link](index, item add the new item at a specific position.
name)
[Link](item name) remove items using name
[Link](index) remove an item from a specific position
list[index of the Get items from a list
element]
[Link](item name) Find position of an Item
[Link]( ) returns strings into alphabetical order and a list of numbers in
ascending order.
[Link]() elements of the list is reversed
[Link] (reverse=1) reverse alphabetical order or descending order
list[index of the replace the items of a list.
element] = new item
[Link](item name) the count of the item in the list.
new list = [Link]() create its duplicate
[Link]() removes all the items of the list.
for i in list: Get each item of the list
print (i)
max(list); min(list) maximum and minimum number from a list of numbers
[Link](list) Pick random item from a list
[Link](list, 1) Pick random item from a list as a list
[Link](list) Randomly jumble the items of a list
[Link](‘character’) convert strings into a list
list(string) Convert a string into list of letters.
list = [ i for i in range() List comprehension
if (condition)]
Python List Notes

1. What is a List?
• A list is a collection of items in ordered, mutable (changeable) form.

• Can store different data types (int, str, float, etc.).

• Defined using square brackets [].

Example:

fruits = ["apple", "banana", "cherry"]

numbers = [1, 2, 3, 4, 5]

mixed = ["hello", 10, 3.14, True]

2. Accessing Elements

• Index starts at 0.

print(fruits[0]) # "apple"

print(fruits[-1]) # "cherry" (negative index = from end)

3. Updating Elements

fruits[1] = "orange"
print(fruits) # ["apple", "orange", "cherry"]

4. List Operations

• Concatenation

a = [1, 2]

b = [3, 4]

print(a + b) # [1, 2, 3, 4]
• Repetition

print([0] * 5) # [0, 0, 0, 0, 0]

• Membership

print("apple" in fruits) # True


print("pear" not in fruits) # True

5. Adding & Removing Items

[Link]("mango") # add to end


[Link](1, "grape") # insert at index

[Link]("orange") # remove by value

[Link]() # remove last item

[Link](0) # remove at index

del fruits[0] # delete element

[Link]() # remove all elements

6. List Functions
len(fruits) # number of items

max(numbers) # largest number

min(numbers) # smallest number

sum(numbers) # sum of numbers

sorted(numbers) # return sorted list

7. Looping Through a List


for fruit in fruits:

print(fruit)

for i in range(len(fruits)):

print(i, fruits[i])

8. List Slicing
print(numbers[1:4]) # [2, 3, 4] (index 1 to 3)

print(numbers[:3]) # [1, 2, 3] (start to 2)

print(numbers[2:]) # [3, 4, 5] (from 2 to end)


print(numbers[::-1]) # reversed list

9. List Comprehension

squares = [x**2 for x in range(1, 6)]


print(squares) # [1, 4, 9, 16, 25]

With condition:

even = [x for x in range(10) if x % 2 == 0]

print(even) # [0, 2, 4, 6, 8]

10. Nested Lists

matrix = [[1, 2], [3, 4], [5, 6]]


print(matrix[1][0]) # 3

Quick Summary

• Mutable → can be changed.

• Use append(), insert(), remove(), pop() for modifications.

• Use slicing [start:end:step] to access sublists.

• Use list comprehension for compact loops.


• Nested lists = lists inside lists.
File Handling

Opening Files

f = open("[Link]", "r") / with open("[Link]", "r") as f: # open file in read mode

File Modes

Mode Description

"r" Read (default). File must exist.

"w" Write. Creates new file or overwrites if exists.

"a" Append. Creates file if not exists, writes at end.

"x" Create new file. Fails if file exists.

"r+" Read and write. File must exist.

"w+" Write and read. Creates file or overwrites.

"a+" Append and read. Creates file if not exists.

"t" Text mode (default).

"b" Binary mode (e.g., "rb", "wb").

Examples:

• "rb" → Read binary file


• "w+b" → Write & read binary file

File Object Attributes

Attribute Description Example

.name File name [Link] → '[Link]'

.mode Mode used to open file [Link] → 'r'

.closed Returns True if file is closed [Link]


Reading Methods

Method Description Example

.read(size) Reads entire file or up to size chars [Link](10)

.readline() Reads one line [Link]()

.readlines() Reads all lines into list [Link]()

Writing Methods

Method Description Example

.write(str) Writes string [Link]("Hello")

.writelines(list) Writes list of strings [Link](["A\n","B\n"])

File Position Methods

Method Description Example

.tell() Get current cursor position [Link]()

.seek(offset) Move cursor to position [Link](0)

Closing Files

Method Description

.close() Closes file (important!)

Best Practice – Using with


with open("[Link]", "r") as f:

content = [Link]()

print(content)
# file automatically closed
Examples

Read File

with open("[Link]", "r") as f:

print([Link]()) # whole file


[Link](0)

print([Link]()) # one line

Write & Append

with open("[Link]", "w") as f:

[Link]("First line\n")

with open("[Link]", "a") as f:


[Link]("Appended line\n")
Read & Write Together

with open("[Link]", "r+") as f:

print([Link]())

[Link]("\nNew line")

Summary

1. Use correct mode (r, w, a, r+, etc.).

2. Use .read(), .readline(), .readlines() for input.

3. Use .write(), .writelines() for output.

4. Use .seek() and .tell() for cursor control.

5. Always .close() or use with open(...) (preferred).


File with one number on each row

File with more than one number on each row


Exception Handlings
What is an Exception?

• An exception is an error that occurs during program execution (e.g., dividing by zero,
invalid input).

• Without handling, the program stops when an error happens.

Basic Try–Except

try:

num = int(input("Enter a number: "))

print(10 / num)
except:

print("Something went wrong!")

• Code inside try is executed first.

• If an error occurs, control jumps to except.

Catching Specific Exceptions

try:
num = int("abc")

except ValueError:

print("Invalid number format!")

Best practice: catch specific exceptions instead of a general one.

Multiple Except Blocks

try:
num = int(input("Enter a number: "))

print(10 / num)

except ValueError:

print("Please enter a valid number.")

except ZeroDivisionError:
print("Cannot divide by zero!")

Try–Except–Else

try:
num = int(input("Enter a number: "))

result = 10 / num

except ZeroDivisionError:

print("You cannot divide by zero!")

else:

print(f"Result = {result}")

• else runs only if no exception occurs.

Try–Except–Finally

try:

f = open("[Link]", "r")

print([Link]())

except FileNotFoundError:

print("File not found!")

finally:
print("This always runs (closing file, cleanup, etc.)")

• finally block is always executed (good for cleanup).

Raising Exceptions

age = -5

if age < 0:

raise ValueError("Age cannot be negative!")


• Use raise to create your own exceptions.

Summary
• Use try to test code.

• Use except to handle errors.

• Use else for code that runs if no errors occur.

• Use finally for cleanup code (always runs).


• Always try to catch specific exceptions.
Common Python Exceptions

Exception When it Happens Example

ValueError Wrong value given to a int("abc")


function

TypeError Wrong data type used "2" + 3

ZeroDivisionError Division by zero 10 / 0

IndexError Index out of range in arr[5] when len(arr)=3


list/tuple

KeyError Key not found in dictionary d = {"a":1}; d["b"]


FileNotFoundError File does not exist open("[Link]")

NameError Variable not defined print(x) when x not


declared
AttributeError Object has no attribute "hello".append(3)

ImportError Module not found import non_existing

IndentationError Wrong indentation Misaligned code block

OverflowError Number too large for [Link](1000)


calculation

RuntimeError General runtime error Infinite recursion

Tips for remembering:

• Think of exception names as clues to the error type.

• Always test suspicious code inside try–except.

• When debugging, print the actual error message:

try:

num = int("abc")

except Exception as e:

print("Error:", e)
Import
import math

Common Functions

Function Description Example Output

[Link](x) Square root [Link](16) 4.0

[Link](x, y) Power (x^y) [Link](2, 3) 8.0

[Link](x) Factorial [Link](5) 120

[Link](x) Round down [Link](3.9) 3

[Link](x) Round up [Link](3.1) 4


[Link](x) Remove decimal [Link](7.8) 7
[Link](x) Natural log (base e) [Link](10) 2.302…

math.log10(x) Log base 10 math.log10(1000) 3.0

[Link](x) Sine (x in radians) [Link]([Link]/2) 1.0

[Link](x) Cosine [Link](0) 1.0

[Link](x) Tangent [Link]([Link]/4) 1.0

[Link](x) Convert radians → degrees [Link]([Link]) 180.0

[Link](x) Convert degrees → radians [Link](180) 3.14159…

Useful Constants

Constant Description Example

[Link] π ≈ 3.14159 area = [Link] * r**2

math.e Euler’s number ≈ 2.718 [Link](math.e) → 1.0

[Link] Infinity [Link](1e308*10) → True

[Link] Not-a-Number [Link](float('nan')) → True

Tip: Use dir(math) in Python to see all available functions in the module.
import datetime
from datetime import date, time, datetime, timedelta

Working with Date

Function Description Example Output

[Link]() Current date [Link]() 2025-09-29

date(year, month, Create a date date(2025, 1, 1) 2025-01-01


day)

.year, .month, .day Extract components d = [Link](); [Link] 2025

.weekday() Day of week [Link]().weekday() 0


(Mon=0 … Sun=6)

.isoformat() ISO string [Link]().isoformat() '2025-09-29'

Working with Time

Function Description Example Output

time(hour, min, sec) Create time time(14, 30, 0) 14:30:00

.hour, .minute, .second Extract parts t = time(9,15); [Link] 9

Working with Date & Time

Function Description Example Output

[Link]() Current local date & time [Link]() 2025-09-29


11:25:33

datetime(year, Create datetime datetime(2025, 9, 29, 10, 30) 2025-09-29


m, d, h, m, s) 10:30:00

.date() Get date only [Link]().date() 2025-09-29

.time() Get time only [Link]().time() 11:25:33


Formatting & Parsing

Function Description Example Output

.strftime(fmt) Format datetime → string [Link]().strfti '2025-09-29


me("%Y-%m-%d %H 11:25'
:%M")

[Link] Parse string → datetime [Link]("20 2025-09-29


me(str, fmt) 25-09-29", 00:00:00
"%Y-%m-%d")

Common Format Codes:

• %Y = Year (2025)

• %m = Month (01–12)
• %d = Day (01–31)

• %H = Hour (00–23)

• %M = Minute (00–59)

• %S = Second (00–59)

• %A = Weekday (Monday, etc.)

Date Arithmetic

Function Description Example Output

timedelta(days=7) Time difference [Link]() + 7 days later


timedelta(days=7)

Subtraction Difference between (date(2025,10,6) - 7


dates date(2025,9,29)).days

Tip: Use import calendar with datetime if you need month names, leap year checks, or
calendars.
import random
The random module is used to generate random numbers, choose random elements, or shuffle
data.

Common Functions

Function Description Example Possible


Output

[Link]() Float between [Link]() 0.3746


0.0 and 1.0

[Link](a, b) Random [Link](1, 10) 7


integer a ≤ N ≤
b

[Link](start, Random [Link](0, 10, 2) 4


stop, step) number in a
range

[Link](a, b) Float between [Link](1.5, 5.5) 3.72


a and b

[Link](seq) Random [Link](['red','blue','green']) 'blue'


element from a
list/tuple/string

[Link](seq, Random list of [Link]([1,2,3], k=5) [2,1,3,3,2]


k=n) n elements
(with
replacement)

[Link](seq, Random list of [Link](range(10), 3) [7,1,9]


k=n) n unique
elements

[Link](seq) Shuffle list in [Link](deck) (list order


place changes)

Seeding (for reproducibility)

[Link](42) # Fixes the sequence

print([Link](1, 10))

Every time you run with the same seed, you’ll get the same output.
Use random for simple randomness. For cryptographic security (e.g., passwords,
tokens), use the secrets module instead.
import pandas
import pandas as pd

1. Data Structures

(a) Series (1D)

import pandas as pd

s = [Link]([10, 20, 30, 40])

print(s)

Output:

0 10
1 20

2 30

3 40

dtype: int64

(b) DataFrame (2D)

data = {

"Name": ["Alice", "Bob", "Charlie"],


"Age": [25, 30, 35]

df = [Link](data)

print(df)

Output:

Name Age

0 Alice 25

1 Bob 30
2 Charlie 35

3. Reading & Writing Data


df = pd.read_csv("[Link]") # Read CSV

df = pd.read_excel("[Link]") # Read Excel

df.to_csv("[Link]", index=False) # Write CSV

4. Basic Information

[Link]() # First 5 rows

[Link]() # Last 5 rows

[Link]() # Column info

[Link] # (rows, columns)

[Link] # List of column names

[Link]() # Summary statistics

5. Selecting Data

df["Name"] # Select column

df[["Name", "Age"]] # Multiple columns

[Link][0] # Row by index

[Link][0:2] # First 2 rows


[Link][0, "Name"] # Specific value

6. Filtering Data

df[df["Age"] > 28] # Rows where Age > 28


df[(df["Age"] > 28) & (df["Age"] < 35)] # Multiple conditions

7. Adding & Modifying Data

df["Salary"] = [3000, 4000, 5000] # Add column

df["Age"] = df["Age"] + 1 # Modify column

[Link][1, "Age"] = 32 # Update single value

8. Deleting Data
[Link]("Salary", axis=1, inplace=True) # Drop column

[Link](0, axis=0, inplace=True) # Drop row

9. Sorting & Grouping

df.sort_values("Age") # Sort by Age

df.sort_values("Age", ascending=False) # Descending sort

[Link]("Age")["Name"].count() # Group by Age

10. Handling Missing Data

[Link]().sum() # Check missing values


[Link](inplace=True) # Drop missing rows

[Link](0, inplace=True) # Fill missing with 0

11. Useful Functions

[Link]() # Mean of numeric columns

[Link]() # Max values


[Link]() # Min values

df["Age"].unique() # Unique values

df["Age"].value_counts() # Frequency count

Summary

• Series = 1D, DataFrame = 2D


• Read/Write: read_csv(), read_excel(), to_csv()

• Explore data: head(), info(), shape, describe()

• Select data: loc[] (by label), iloc[] (by index)

• Clean data: dropna(), fillna()

• Analyze: groupby(), mean(), value_counts()

Pandas is essential for data analysis, often used together with NumPy and Matplotlib.
Pandas Cheat Sheet

Pandas is a powerful Python library for data analysis and manipulation.

1. Installation

pip install pandas

2. Importing

import pandas as pd

3. Creating Data

# From dictionary
data = {"Name": ["Alice", "Bob"], "Age": [25, 30]}

df = [Link](data)

# From list

df = [Link]([[1, 2], [3, 4]], columns=["A", "B"])

# From CSV/Excel
df = pd.read_csv("[Link]")

df = pd.read_excel("[Link]")

4. Viewing Data

[Link]() # First 5 rows

[Link](3) # Last 3 rows

[Link]() # Summary
[Link]() # Statistics

[Link] # (rows, columns)

[Link] # Column names

[Link] # Index (row labels)


5. Selecting Data

df["Name"] # Single column

df[["Name", "Age"]] # Multiple columns


[Link][0] # First row (by index)

[Link][0:2] # Row slice

[Link][0, "Name"] # Specific value

[Link][:, "Name"] # All rows, Name column

6. Filtering Data

df[df["Age"] > 25]


df[(df["Age"] > 20) & (df["Age"] < 30)]

7. Adding & Modifying Columns

df["Country"] = ["USA", "UK"]

df["Age+5"] = df["Age"] + 5

8. Deleting Data

[Link]("Age", axis=1, inplace=True) # Drop column


[Link](0, axis=0, inplace=True) # Drop row

9. Sorting

df.sort_values("Age", ascending=True)

df.sort_index()

10. Handling Missing Data


[Link]().sum() # Count missing

[Link]() # Drop missing rows

[Link](0) # Fill with 0


df["Age"].fillna(df["Age"].mean())

11. Grouping & Aggregation

[Link]("Country")["Age"].mean()
[Link]("Country").agg({"Age": ["mean", "max"]})

12. Merging & Joining

[Link](df1, df2, on="ID")

[Link](df2, lsuffix="_left", rsuffix="_right")

13. Concatenation
[Link]([df1, df2]) # Vertical
[Link]([df1, df2], axis=1) # Horizontal

14. Reading & Writing Files

df.to_csv("[Link]", index=False)

df.to_excel("[Link]", index=False)

df = pd.read_csv("[Link]")

df = pd.read_excel("[Link]")

15. Useful Functions

df["Age"].mean() # Average

df["Age"].max() # Max

df["Age"].min() # Min

df["Age"].unique() # Unique values

df["Age"].value_counts() # Count frequency

Tips:

• Use .iloc[] for index-based selection.


• Use .loc[] for label-based selection.

• inplace=True modifies the DataFrame directly.

• Always check data with .head() after loading.


import openpyxl
OpenPyXL is a Python library for reading, writing, and modifying Excel (.xlsx) files.

1. Installation

pip install openpyxl

2. Importing

import openpyxl

3. Creating and Saving Workbook

from openpyxl import Workbook

wb = Workbook() # Create new workbook

ws = [Link] # Get active sheet

[Link] = "MySheet" # Rename sheet

[Link]("[Link]") # Save workbook

4. Loading an Existing Workbook

wb = openpyxl.load_workbook("[Link]")
ws = [Link]

5. Working with Sheets

print([Link]) # List all sheets

ws = wb["Sheet1"] # Select sheet by name

wb.create_sheet("Data") # Add new sheet

[Link](ws) # Remove sheet

6. Writing Data

ws["A1"] = "Hello" # Write to cell


[Link](row=2, column=1, value="World")

7. Reading Data

print(ws["A1"].value) # Read from cell


print([Link](row=2, column=1).value)

8. Iterating Rows and Columns

for row in ws.iter_rows(min_row=1, max_row=3, min_col=1, max_col=2):

for cell in row:

print([Link])

for col in ws.iter_cols(min_row=1, max_row=3, min_col=1, max_col=2):


for cell in col:

print([Link])

9. Appending Rows

[Link]([1, 2, 3]) # Add row at the end

10. Cell Properties


print(ws["A1"].row) # Row number

print(ws["A1"].column) # Column number

print(ws["A1"].coordinate) # Cell coordinate (e.g., A1)

11. Styling Cells

from [Link] import Font, Color, Alignment

ws["A1"].font = Font(bold=True, color="FF0000")

ws["A1"].alignment = Alignment(horizontal="center")
12. Merging & Unmerging Cells

ws.merge_cells("A1:C1")

ws.unmerge_cells("A1:C1")

13. Column and Row Dimensions

ws.column_dimensions["A"].width = 20

ws.row_dimensions[1].height = 25

14. Formulas

ws["B1"] = "=SUM(A1:A10)"

15. Saving Changes


[Link]("[Link]")

Tips:

• Always save after making changes.

• Use .value to get/set cell values.

• Sheets, cells, and ranges are case-sensitive.


Triangle Patterns (Loops)
1. Star Patterns

(a) Right-Angled Triangle

rows = 5

for i in range(1, rows+1):

for j in range(i):

print("*", end="")

print()
Output:

(b) Inverted Right-Angled Triangle


rows = 5

for i in range(rows, 0, -1):

for j in range(i):

print("*", end="")
print()

Output:

(c) Pyramid

rows = 5

for i in range(1, rows+1):

print(" " * (rows-i), end="")


print("*" * (2*i-1))

Output:
2. Number Patterns

(a) Normal Number Triangle (Repetition of Row Number)

rows = 5

for i in range(1, rows+1):

for j in range(i):
print(i, end="")

print()

Output:

(b) Increasing Sequence Numbers

rows = 5
for i in range(1, rows+1):

for j in range(1, i+1):

print(j, end="")
print()

Output:

(c) Palindrome Number Pyramid


rows = 5

for i in range(1, rows+1):

print(" " * (rows-i), end="")

# Ascending

for j in range(1, i+1):

print(j, end="")

# Descending

for j in range(i-1, 0, -1):

print(j, end="")

print()

Output:

(d) Inverted Palindrome Pyramid

rows = 5

for i in range(rows, 0, -1):

print(" " * (rows-i), end="")

for j in range(1, i+1):

print(j, end="")

for j in range(i-1, 0, -1):

print(j, end="")
print()

Output:

3. While Loop Example (Palindrome Pyramid)

rows = 5

i=1

while i <= rows:

print(" " * (rows - i), end="")

j=1

while j <= i:

print(j, end="")

j += 1

j=i-1

while j >= 1:
print(j, end="")

j -= 1

print()

i += 1

Output:
Universal Format for Triangle and Diamond Patterns in Python

When solving triangle or diamond pattern problems, the logic is always the same.
You only change what you print inside the loops.

Step-by-Step Format

1. Set the number of rows

rows = 5

2. Outer loop → controls the row (height of triangle)

for i in range(1, rows+1): # row number = i


...

3. Print spaces (if needed, for centered shapes like pyramids/diamonds)

print(" " * (rows-i), end="") # spaces decrease each row

4. Ascending part (characters/numbers increasing)

for j in range(1, i+1):


print("*", end="") # or print(j, end="") for numbers

5. Descending part (only for palindrome or diamonds)


for j in range(i-1, 0, -1):

print(j, end="") # prints numbers backward

6. New line after finishing each row

print()

Universal Skeleton Code

rows = 5

for i in range(1, rows+1): # Outer loop (row control)

print(" " * (rows-i), end="") # Spaces (optional)


for j in range(1, i+1): # Ascending part

print("*", end="") # Change "*" → j → i

for j in range(i-1, 0, -1): # Descending part (optional)

print(j, end="") # Only needed for palindromes

print() # Newline

Examples Using the Same Format

1. Star Pyramid
for j in range(1, i+1):

print("*", end="")

Output (rows=5):

**

***

****
*****

2. Normal Number Triangle (row number repeated)

for j in range(1, i+1):

print(i, end="")

Output (rows=5):

1
22

333

4444

55555
3. Increasing Sequence Number Triangle

for j in range(1, i+1):

print(j, end="")
Output (rows=5):

12

123

1234

12345

4. Palindrome Number Pyramid


for j in range(1, i+1): # Ascending

print(j, end="")

for j in range(i-1, 0, -1): # Descending

print(j, end="")

Output (rows=5):

121
12321

1234321

123454321

For Diamonds

• Build an upper pyramid (using format above).


• Then build a lower inverted pyramid (reverse loop).

# Upper half

for i in range(1, rows+1):

...
# Lower half

for i in range(rows-1, 0, -1):

...

Key Idea

• Outer loop = row control

• Inner loops = spaces, ascending, descending

• By changing what’s printed (*, i, j), you can make any triangle or diamond.

• So, the format is always:

Outer loop (rows) → spaces → ascending loop → (optional) descending loop →


newline
Classes, Inheritance, and UML Diagram

1. What is a Class?

• A class is a blueprint for creating objects.

• An object is an instance of a class.

• Classes define attributes (data/variables) and methods (functions).

2. Defining a Class
class Student:

def __init__(self, name, age): # constructor

[Link] = name

[Link] = age

def display(self): # method

print(f"Name: {[Link]}, Age: {[Link]}")

3. Creating Objects

s1 = Student("Alice", 20)
s2 = Student("Bob", 22)

[Link]() # Output: Name: Alice, Age: 20

4. __init__ Method (Constructor)

• Special method that runs automatically when an object is created.

• Used to initialize attributes.

def __init__(self, name, age):

[Link] = name

[Link] = age
5. Attributes

• Instance attributes → specific to each object ([Link]).

• Class attributes → shared by all objects.

class Student:
school = "UTAR" # class attribute

def __init__(self, name):

[Link] = name # instance attribute

6. Methods

• Instance methods → operate on object data.


• Class methods → use @classmethod, affect the whole class.
• Static methods → use @staticmethod, utility functions.

class Example:

count = 0

def __init__(self):

[Link] += 1

@classmethod

def show_count(cls):

print(f"Objects created: {[Link]}")

@staticmethod

def greet():

print("Hello!")
7. Encapsulation (Access Modifiers)

Python doesn’t have true private variables, but uses conventions:

• [Link] → public

• _name → protected (convention only)


• __name → private (name mangled)

class Person:

def __init__(self, name, salary):

[Link] = name # public

self._role = "Student" # protected

self.__salary = salary # private

8. Mutator & Accessor Methods


• Accessor (getter) → get values.

• Mutator (setter) → modify values.

class BankAccount:

def __init__(self, balance):

self.__balance = balance

def get_balance(self): # accessor


return self.__balance

def set_balance(self, amount): # mutator

self.__balance = amount
9. Inheritance

• Allows a class to inherit methods/attributes from another class.

class Animal:

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

class Dog(Animal): # Dog inherits from Animal

def speak(self):

print("Woof!")

10. Polymorphism

• Different classes can have methods with the same name but different behavior.

for animal in [Animal(), Dog()]:

[Link]()

11. Special Methods (Magic Methods)

• __init__ → constructor

• __str__ → string representation

• __len__ → length of object

• __add__ → overload + operator


class Book:

def __init__(self, title, pages):

[Link] = title

[Link] = pages

def __str__(self):

return f"Book: {[Link]}"

def __len__(self):

return [Link]

12. Example: Full Program


class Student:

def __init__(self, sid, name, cgpa):

[Link] = sid

[Link] = name

[Link] = cgpa

def get_cgpa(self): # accessor


return [Link]

def set_cgpa(self, new_cgpa): # mutator

[Link] = new_cgpa

def display(self):

print(f"ID: {[Link]}, Name: {[Link]}, CGPA: {[Link]}")

# Main program
s1 = Student("2ABC2334", "Lily", 2.0)

[Link]()

s1.set_cgpa(3.5)

print("Updated CGPA:", s1.get_cgpa())

Key Takeaways for Exams

• Always define class using class.

• Use __init__ for initialization.

• Accessor = getter, Mutator = setter.

• Inheritance uses (ParentClass).

• __str__ makes objects readable when printed.

------------------------------------------------------

3. UML Class Diagram (Unified Modeling Language)


------------------------------------------------------

UML helps visualize classes and their relationships.

Basic structure:

+----------------+

| ClassName |

+----------------+
| - attribute1 |

| - attribute2 |

+----------------+

| + method1() |
| + method2() |

+----------------+

Symbols:
- "-" = private attribute/method

- "+" = public attribute/method

Example (Student → GraduateStudent):

+-------------------+ +-----------------------+

| Student |<----------| GraduateStudent |

+-------------------+ +-----------------------+

| - name: str | | - thesis_title: str |

| - age: int | +-----------------------+

+-------------------+ | + display() |

| + display() | | + show_thesis() |

+-------------------+ +-----------------------+

------------------------------------------------------

4. Quick Comparison Table

------------------------------------------------------

| Concept | Python Example | UML Symbol |

|---------------|-----------------------|---------------|
| Class | class Student: | Box |

| Attribute | [Link] | - name: str |

| Method | def display(self): | + display() |

| Inheritance | class Dog(Animal): | Arrow <|-- |

| Overriding | Redefine parent’s method in child | Same method in both |

You might also like