0% found this document useful (0 votes)
11 views33 pages

Convert Markdown to PDF Online

The document provides a comprehensive guide on using Markdown2PDF for converting Markdown files to PDF, along with a detailed syllabus for a Python programming course. It covers various programming concepts such as variables, data types, operators, file handling, lists, and includes practical problems with complete code examples. Additionally, it highlights best practices and common operations in Python programming.

Uploaded by

suiujjh
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)
11 views33 pages

Convert Markdown to PDF Online

The document provides a comprehensive guide on using Markdown2PDF for converting Markdown files to PDF, along with a detailed syllabus for a Python programming course. It covers various programming concepts such as variables, data types, operators, file handling, lists, and includes practical problems with complete code examples. Additionally, it highlights best practices and common operations in Python programming.

Uploaded by

suiujjh
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

Markdown2PDF

[Link]

Awesome Markdown to PDF!

- Online? Upload [Link] to stranger server?


+ Try Offline Web App!

How to use md2pdf?

1. Click button choose .md file.

2. Edit in editor (left panel).


3. Click Transform!
4. Switch 'Destination' to Save as PDF.
5. Chrome recommended

Tips

Resize the layout what you want.

After click Transform button, inverse the checkbox of 'Headers and Footers'.

反選頁首與頁尾.
What's special?

You can use html tag!

Hey I'm in blockquote!

Profile

Github: @realdennis
Project: md2pdf (Markdown2PDF)
What about me: ☕ 、 👨🏻‍💻️、 🍕、 🎞️
Code Like this
// [Link]
function Hello(){
[Link]('World!')
}
Hello();

or this

# [Link]
def awesome():
print('awesome!')
awesome()

WBSU SEMESTER 1 - PYTHON PROGRAMMING

COMPLETE FULL SYLLABUS GUIDE

TABLE OF CONTENTS
1. Introduction to Programming in Python
2. File Handling in Python
3. List Handling in Python
4. Least Square Fitting
5. Solution of Algebraic and Transcendental Equations by Bisection Method
6. Solution of Algebraic and Transcendental Equations by Newton-Raphson Method

TOPIC 1: INTRODUCTION TO PROGRAMMING IN


PYTHON

1.1 THEORY: Variables, Data Types, and Operators


What is a Variable?

A variable is a container that stores a value. Think of it as a named box holding data.

Example: age = 25

age is the variable name

25 is the value stored

= assigns the value

Python Data Types

Data Type Description Examples

int Whole numbers 5, -3, 0, 100

float Decimal numbers 3.14, -2.5

str Text "Hello", 'Name'

bool True/False True, False

complex Complex numbers 3+4j

Operators

Operator Name Example Result

+ Addition 10 + 5 15

- Subtraction 10 - 5 5

* Multiplication 10 * 5 50

/ Division 20 / 4 5.0

** Power 2 ** 3 8

% Modulo 10 % 3 1

// Floor Division 20 // 6 3

PROBLEM 1.1: Basic Arithmetic Operations


Question

Perform arithmetic operations on two numbers.

STEP-BY-STEP SOLUTION

Step 1: Define Numbers

num1 = 20
num2 = 5

Step 2: Perform Operations

addition = num1 + num2 # 25


subtraction = num1 - num2 # 15
multiplication = num1 * num2 # 100
division = num1 / num2 # 4.0
modulo = num1 % num2 # 0
power = num1 ** num2 # 3200000
floor_division = num1 // num2 # 4

Step 3: Display Results

print("Addition:", addition)
print("Subtraction:", subtraction)
print("Multiplication:", multiplication)
print("Division:", division)
print("Modulo:", modulo)
print("Power:", power)
print("Floor Division:", floor_division)

COMPLETE CODE

num1 = 20
num2 = 5

addition = num1 + num2


subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2
modulo = num1 % num2
power = num1 ** num2
floor_division = num1 // num2

print("Addition:", addition)
print("Subtraction:", subtraction)
print("Multiplication:", multiplication)
print("Division:", division)
print("Modulo:", modulo)
print("Power:", power)
print("Floor Division:", floor_division)

OUTPUT

Addition: 25
Subtraction: 15
Multiplication: 100
Division: 4.0
Modulo: 0
Power: 3200000
Floor Division: 4

PROBLEM 1.2: User Input and Sum

Question

Take two numbers from user and calculate sum.

COMPLETE CODE

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
sum_result = num1 + num2
print(f"Sum of {num1} and {num2} is {sum_result}")

EXAMPLE OUTPUT

Enter first number: 15


Enter second number: 10
Sum of 15 and 10 is 25
1.3 THEORY: Conditional Statements (if-elif-else)

Comparison Operators

Operator Meaning Example

== Equal to 5 == 5

!= Not equal 5 != 3

> Greater 5>3

< Less 5<3

>= Greater or equal 5 >= 5

<= Less or equal 5 <= 3

if-elif-else Structure

if condition1:
# Code if condition1 is True
elif condition2:
# Code if condition2 is True
else:
# Code if both are False

PROBLEM 1.3: Age-Based Category

Question

Read age and classify: Child (<13), Teen (13-17), Adult (18-59), Senior (≥60).

COMPLETE CODE

age = int(input("Enter your age: "))

if age < 13:


category = "Child"
elif age >= 13 and age < 18:
category = "Teen"
elif age >= 18 and age < 60:
category = "Adult"
else:
category = "Senior"

print(f"Age: {age}")
print(f"Category: {category}")

EXAMPLE OUTPUT

Enter your age: 15


Age: 15
Category: Teen

1.4 THEORY: Loops (for and while)

for Loop

for variable in range(start, stop):


# Code to repeat

while Loop

while condition:
# Code to repeat

PROBLEM 1.4: Print Numbers 1 to 10

COMPLETE CODE

# Using for loop


print("Using for loop:")
for i in range(1, 11):
print(i)

# Using while loop


print("\nUsing while loop:")
i = 1
while i <= 10:
print(i)
i = i + 1

OUTPUT

Using for loop:


1
2
3
...
10

Using while loop:


1
2
3
...
10

PROBLEM 1.5: Calculate Factorial

Question

Calculate n! = 1 × 2 × 3 × ... × n

COMPLETE CODE

n = int(input("Enter number: "))


factorial = 1

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


factorial = factorial * i

print(f"{n}! = {factorial}")

EXAMPLE OUTPUT
Enter number: 5
5! = 120

TOPIC 2: FILE HANDLING IN PYTHON

2.1 THEORY: Introduction to File Handling

What is File Handling?

File handling means working with files - reading, writing, and manipulating them.

File Operations

Operation Function Purpose

Open open() Open a file

Read read() Read file contents

Write write() Write data to file

Close close() Close the file

File Opening Modes

Mode Meaning Description

'r' Read Read existing file (default)

'w' Write Create new file or overwrite

'a' Append Add to end of file

'x' Create Create new file (error if exists)

PROBLEM 2.1: Create and Write to File


Question

Create a file and write text to it.

COMPLETE CODE

# Create and write to file


file = open("[Link]", "w")
[Link]("Hello World!\n")
[Link]("Python is awesome!\n")
[Link]("File handling is easy.")
[Link]()

print("File created and written successfully!")

EXPLANATION

open("[Link]", "w") - Create file named "[Link]" in write mode

[Link]() - Write text to file

[Link]() - Close the file (IMPORTANT!)

PROBLEM 2.2: Read from File

Question

Read the file created in Problem 2.1.

COMPLETE CODE

# Method 1: Read entire file


file = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()

# Method 2: Read line by line


print("\n--- Reading line by line ---")
file = open("[Link]", "r")
for line in file:
print([Link]())
[Link]()
# Method 3: Read all lines as list
print("\n--- Read as list ---")
file = open("[Link]", "r")
lines = [Link]()
for line in lines:
print([Link]())
[Link]()

OUTPUT

Hello World!
Python is awesome!
File handling is easy.

--- Reading line by line ---


Hello World!
Python is awesome!
File handling is easy.

--- Read as list ---


Hello World!
Python is awesome!
File handling is easy.

PROBLEM 2.3: Append to File

Question

Add new lines to existing file.

COMPLETE CODE

# Append to file
file = open("[Link]", "a")
[Link]("\nAppended line 1")
[Link]("\nAppended line 2")
[Link]()

# Read and display


file = open("[Link]", "r")
print([Link]())
[Link]()

OUTPUT

Hello World!
Python is awesome!
File handling is easy.
Appended line 1
Appended line 2

PROBLEM 2.4: Using with Statement (Best Practice)

Question

Use 'with' statement for automatic file closing.

COMPLETE CODE

# Write using with statement


with open("[Link]", "w") as file:
[Link]("Line 1\n")
[Link]("Line 2\n")
[Link]("Line 3\n")

# Read using with statement


with open("[Link]", "r") as file:
content = [Link]()
print(content)

OUTPUT

Line 1
Line 2
Line 3

EXPLANATION

with open() as file: automatically closes the file when done


No need for explicit [Link]()
Better and safer practice

PROBLEM 2.5: Write and Read Numbers to File

Question

Write numbers to file and read them back.

COMPLETE CODE

# Write numbers to file


with open("[Link]", "w") as file:
for i in range(1, 6):
[Link](f"{i}\n")

# Read and calculate sum


total = 0
with open("[Link]", "r") as file:
for line in file:
number = int([Link]())
total = total + number

print(f"Sum of numbers: {total}")

OUTPUT

Sum of numbers: 15

TOPIC 3: LIST HANDLING IN PYTHON

3.1 THEORY: Introduction to Lists

What is a List?
A list is a collection of items enclosed in square brackets [ ].

Example: marks = [85, 92, 78, 88, 95]

List Features

Can store multiple values


Can access by index (position)
Can modify (add, remove, change)
Index starts from 0

List Operations

Operation Code Example

Create list = [items] marks = [85, 90]

Access list[index] marks[0] returns 85

Add [Link](item) [Link](95)

Remove [Link](item) [Link](85)

Length len(list) len(marks) returns 5

Sum sum(list) sum(marks) returns total

PROBLEM 3.1: Sum and Average of List

Question

Given marks, find sum, average, max, and min.

COMPLETE CODE

marks = [85, 92, 78, 88, 95]

total = sum(marks)
average = total / len(marks)
highest = max(marks)
lowest = min(marks)
print(f"Marks: {marks}")
print(f"Total: {total}")
print(f"Average: {average:.2f}")
print(f"Highest: {highest}")
print(f"Lowest: {lowest}")

OUTPUT

Marks: [85, 92, 78, 88, 95]


Total: 438
Average: 87.60
Highest: 95
Lowest: 78

PROBLEM 3.2: Add and Remove Elements

Question

Modify a list by adding and removing elements.

COMPLETE CODE

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

print("Original:", fruits)

# Add element
[Link]("date")
print("After append:", fruits)

# Add at specific position


[Link](1, "blueberry")
print("After insert:", fruits)

# Remove element
[Link]("cherry")
print("After remove:", fruits)

# Remove by index
[Link](0)
print("After pop:", fruits)
OUTPUT

Original: ['apple', 'banana', 'cherry']


After append: ['apple', 'banana', 'cherry', 'date']
After insert: ['apple', 'blueberry', 'banana', 'cherry', 'date']
After remove: ['apple', 'blueberry', 'banana', 'date']
After pop: ['blueberry', 'banana', 'date']

PROBLEM 3.3: Separate Passing and Failing Marks

Question

Separate marks into passing (≥60) and failing (<60).

COMPLETE CODE

marks = [45, 78, 92, 55, 88, 35, 91, 65]

passing = []
failing = []

for mark in marks:


if mark >= 60:
[Link](mark)
else:
[Link](mark)

print(f"Marks: {marks}")
print(f"Passing (≥60): {passing}")
print(f"Failing (<60): {failing}")
print(f"Pass percentage: {len(passing)/len(marks)*100:.2f}%")

OUTPUT

Marks: [45, 78, 92, 55, 88, 35, 91, 65]


Passing (≥60): [78, 92, 88, 91, 65]
Failing (<60): [45, 55, 35]
Pass percentage: 62.50%
PROBLEM 3.4: Double Each Element

Question

Multiply each list element by 2.

COMPLETE CODE

numbers = [10, 20, 30, 40, 50]

# Method 1: Using for loop


for i in range(len(numbers)):
numbers[i] = numbers[i] * 2

print(f"Doubled: {numbers}")

# Method 2: Using list comprehension


numbers2 = [10, 20, 30, 40, 50]
numbers2 = [n * 2 for n in numbers2]
print(f"Using comprehension: {numbers2}")

OUTPUT

Doubled: [20, 40, 60, 80, 100]


Using comprehension: [20, 40, 60, 80, 100]

PROBLEM 3.5: Sort and Search List

Question

Sort a list and search for elements.

COMPLETE CODE

numbers = [45, 23, 89, 12, 56, 34, 78, 91]

# Original
print(f"Original: {numbers}")

# Sort ascending
numbers_sorted = sorted(numbers)
print(f"Sorted: {numbers_sorted}")

# Sort descending
numbers_descending = sorted(numbers, reverse=True)
print(f"Descending: {numbers_descending}")

# Search
search_value = 56
if search_value in numbers:
print(f"{search_value} found at index {[Link](search_value)}")
else:
print(f"{search_value} not found")

# Count occurrences
numbers_with_duplicates = [1, 2, 3, 2, 2, 4]
print(f"Count of 2: {numbers_with_duplicates.count(2)}")

OUTPUT

Original: [45, 23, 89, 12, 56, 34, 78, 91]


Sorted: [12, 23, 34, 45, 56, 78, 89, 91]
Descending: [91, 89, 78, 56, 45, 34, 23, 12]
56 found at index 4
Count of 2: 3

TOPIC 4: LEAST SQUARE FITTING

4.1 THEORY: Least Squares Method

What is Least Squares Fitting?

Least squares fitting is a method to find the best-fit curve or line through data points by minimizing the
sum of squared errors.

Why Use It?

Fit experimental data to a mathematical model


Predict values based on existing data
Reduce the effect of random errors

Linear Regression (y = mx + c)

The least squares method finds m and c such that the line best fits the data.

Formulas:

m = (n∑xy - ∑x∑y) / (n∑x² - (∑x)²)


c = (∑y - m∑x) / n

Where:

n = number of data points


∑x = sum of x values
∑y = sum of y values
∑xy = sum of (x × y)
∑x² = sum of (x²)

PROBLEM 4.1: Linear Least Squares Fitting

Question

Fit a line to data points using least squares method.

Data: (1,2), (2,4), (3,5), (4,8), (5,10)

STEP-BY-STEP SOLUTION

Step 1: Input Data

x = [1, 2, 3, 4, 5]
y = [2, 4, 5, 8, 10]
n = len(x)

Step 2: Calculate Sums

sum_x = sum(x) # 15
sum_y = sum(y) # 29
sum_xy = sum([x[i]*y[i] for i in range(n)]) # 1*2 + 2*4 + 3*5 + 4*8 + 5*10 = 120
sum_x2 = sum([x[i]**2 for i in range(n)]) # 1 + 4 + 9 + 16 + 25 = 55

Step 3: Calculate m and c

m = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x**2)


c = (sum_y - m * sum_x) / n

Step 4: Display Results

print(f"Line equation: y = {m:.2f}x + {c:.2f}")

COMPLETE CODE

import math

# Data points
x = [1, 2, 3, 4, 5]
y = [2, 4, 5, 8, 10]
n = len(x)

# Calculate sums
sum_x = sum(x)
sum_y = sum(y)
sum_xy = sum([x[i]*y[i] for i in range(n)])
sum_x2 = sum([x[i]**2 for i in range(n)])

# Calculate slope (m) and intercept (c)


m = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x**2)
c = (sum_y - m * sum_x) / n

# Display results
print(f"Data points: {list(zip(x, y))}")
print(f"\nLine equation: y = {m:.2f}x + {c:.2f}")

# Predict values
print("\nPredicted values:")
for xi in x:
yi = m * xi + c
print(f"x = {xi}, y = {yi:.2f}")

OUTPUT
Data points: [(1, 2), (2, 4), (3, 5), (4, 8), (5, 10)]

Line equation: y = 1.90x + 0.20

Predicted values:
x = 1, y = 2.10
x = 2, y = 4.00
x = 3, y = 5.90
x = 4, y = 7.80
x = 5, y = 9.70

PROBLEM 4.2: Using NumPy for Least Squares

Question

Use NumPy polyfit function for easier fitting.

COMPLETE CODE

import numpy as np
import [Link] as plt

# Data points
x = [Link]([1, 2, 3, 4, 5])
y = [Link]([2, 4, 5, 8, 10])

# Fit polynomial of degree 1 (line)


coefficients = [Link](x, y, 1)
m = coefficients[0]
c = coefficients[1]

print(f"Slope (m) = {m:.2f}")


print(f"Intercept (c) = {c:.2f}")
print(f"Line equation: y = {m:.2f}x + {c:.2f}")

# Create polynomial function


p = np.poly1d(coefficients)

# Predict values
print("\nPredicted values:")
for xi in x:
print(f"x = {xi}, y = {p(xi):.2f}")
OUTPUT

Slope (m) = 1.90


Intercept (c) = 0.20
Line equation: y = 1.90x + 0.20

Predicted values:
x = 1, y = 2.10
x = 2, y = 4.00
x = 3, y = 5.90
x = 4, y = 7.80
x = 5, y = 9.70

TOPIC 5: BISECTION METHOD

5.1 THEORY: Bisection Method for Root Finding

What is Bisection Method?

Bisection method is a numerical technique to find roots of equations by repeatedly dividing an interval in
half.

How It Works?

1. Start with interval [a, b] where f(a) and f(b) have opposite signs
2. Calculate midpoint c = (a + b) / 2
3. Check if f(c) ≈ 0 (found root)
4. If not, choose new interval where sign changes
5. Repeat until root is found

Advantages

Simple and reliable


Always converges (if initial interval is correct)
No derivatives needed

Disadvantages
Slower than Newton-Raphson
Requires initial interval [a, b]
May not work if f(a) and f(b) have same sign

PROBLEM 5.1: Find Root Using Bisection

Question

Find root of equation: f(x) = x² - 4 = 0

The root should be x = 2 (or x = -2)

STEP-BY-STEP SOLUTION

Step 1: Define Function

def f(x):
return x**2 - 4

Step 2: Set Interval and Tolerance

a = 1 # Lower bound (f(a) = 1 - 4 = -3, negative)


b = 3 # Upper bound (f(b) = 9 - 4 = 5, positive)
tolerance = 0.0001

Step 3: Apply Bisection Method

iterations = 0
while (b - a) > tolerance:
c = (a + b) / 2

if f(c) == 0:
break # Root found exactly
elif f(a) * f(c) < 0:
b = c # Root is in left half
else:
a = c # Root is in right half

iterations = iterations + 1
Step 4: Display Root

root = (a + b) / 2
print(f"Root: {root:.6f}")
print(f"f({root:.6f}) = {f(root):.6f}")
print(f"Iterations: {iterations}")

COMPLETE CODE

def f(x):
return x**2 - 4

a = 1 # Lower bound
b = 3 # Upper bound
tolerance = 0.0001
iterations = 0

print(f"Initial interval: [{a}, {b}]")


print(f"f({a}) = {f(a)}, f({b}) = {f(b)}")
print()

while (b - a) > tolerance:


c = (a + b) / 2

print(f"Iteration {iterations + 1}: a={a:.4f}, b={b:.4f}, c={c:.4f}, f(c)={f(c):.4f}

if f(c) == 0:
print(f"Root found exactly: {c}")
break
elif f(a) * f(c) < 0:
b = c # Root is in [a, c]
else:
a = c # Root is in [c, b]

iterations = iterations + 1

root = (a + b) / 2
print(f"\nFinal root: {root:.6f}")
print(f"f({root:.6f}) = {f(root):.6f}")
print(f"Total iterations: {iterations}")

OUTPUT

Initial interval: [1, 3]


f(1) = -3, f(3) = 5
Iteration 1: a=1.0000, b=3.0000, c=2.0000, f(c)=0.0000
Root found exactly: 2.0

Final root: 2.000000


f(2.000000) = 0.000000
Total iterations: 1

PROBLEM 5.2: Bisection for Different Equation

Question

Find root of: f(x) = x³ - 5x + 1 = 0

Initial interval: [0, 1]

COMPLETE CODE

def f(x):
return x**3 - 5*x + 1

a = 0
b = 1
tolerance = 0.00001
iterations = 0

while (b - a) > tolerance:


c = (a + b) / 2

if abs(f(c)) < tolerance:


break
elif f(a) * f(c) < 0:
b = c
else:
a = c

iterations = iterations + 1

root = (a + b) / 2
print(f"Root: {root:.6f}")
print(f"f({root:.6f}) = {f(root):.6f}")
print(f"Iterations: {iterations}")
OUTPUT

Root: 0.201640
f(0.201640) = 0.000004
Iterations: 19

TOPIC 6: NEWTON-RAPHSON METHOD

6.1 THEORY: Newton-Raphson Method

What is Newton-Raphson Method?

Newton-Raphson is a numerical method to find roots of equations using the derivative (slope).

Formula

x_{n+1} = x_n - f(x_n) / f'(x_n)

Where:

x_n = current approximation


f(x_n) = function value at x_n
f'(x_n) = derivative of f at x_n

How It Works?

1. Start with initial guess xâ‚€


2. Calculate next approximation using formula above
3. Repeat until convergence (|x_{n+1} - x_n| < tolerance)

Advantages

Converges faster than Bisection (quadratic convergence)


Requires only initial guess (not interval)
Fewer iterations needed

Disadvantages
Requires derivative f'(x)
May diverge if initial guess is far from root
Derivative must be non-zero

PROBLEM 6.1: Newton-Raphson for x² - 4 = 0

Question

Find root of: f(x) = x² - 4 Derivative: f'(x) = 2x Initial guess: x₀ = 3

STEP-BY-STEP SOLUTION

Step 1: Define Function and Derivative

def f(x):
return x**2 - 4

def f_prime(x):
return 2*x

Step 2: Set Initial Guess and Tolerance

x = 3 # Initial guess
tolerance = 0.0001

Step 3: Apply Newton-Raphson Formula

iterations = 0
while True:
x_new = x - f(x) / f_prime(x)

if abs(x_new - x) < tolerance:


break

x = x_new
iterations = iterations + 1

Step 4: Display Root


print(f"Root: {x:.6f}")
print(f"Iterations: {iterations}")

COMPLETE CODE

def f(x):
return x**2 - 4

def f_prime(x):
return 2*x

x = 3 # Initial guess
tolerance = 0.0001
iterations = 0

print(f"Finding root of f(x) = x² - 4")


print(f"Initial guess: xâ‚€ = {x}")
print()

while True:
fx = f(x)
fpx = f_prime(x)
x_new = x - fx / fpx

print(f"Iteration {iterations + 1}: x = {x:.6f}, f(x) = {fx:.6f}, x_new = {x_new:.6f

if abs(x_new - x) < tolerance:


print(f"\nConverged!")
break

x = x_new
iterations = iterations + 1

print(f"\nFinal root: {x:.6f}")


print(f"f({x:.6f}) = {f(x):.6f}")
print(f"Total iterations: {iterations}")

OUTPUT

Finding root of f(x) = x² - 4


Initial guess: xâ‚€ = 3

Iteration 1: x = 3.000000, f(x) = 5.000000, x_new = 2.166667


Iteration 2: x = 2.166667, f(x) = 0.694444, x_new = 2.006211
Iteration 3: x = 2.006211, f(x) = 0.024860, x_new = 2.000015
Converged!

Final root: 2.000015


f(2.000015) = 0.000059
Total iterations: 3

PROBLEM 6.2: Newton-Raphson for x³ - 5x + 1 = 0

Question

Find root of: f(x) = x³ - 5x + 1 Derivative: f'(x) = 3x² - 5 Initial guess: x₀ = 0.2

COMPLETE CODE

def f(x):
return x**3 - 5*x + 1

def f_prime(x):
return 3*x**2 - 5

x = 0.2 # Initial guess


tolerance = 0.00001
iterations = 0

while True:
fx = f(x)
fpx = f_prime(x)
x_new = x - fx / fpx

if abs(x_new - x) < tolerance:


break

x = x_new
iterations = iterations + 1

print(f"Root: {x:.6f}")
print(f"f({x:.6f}) = {f(x):.6f}")
print(f"Iterations: {iterations}")

OUTPUT
Root: 0.201640
f(0.201640) = 0.000000
Iterations: 4

PROBLEM 6.3: Comparison of Bisection vs Newton-Raphson

Question

Compare both methods for finding root of x³ - 2 = 0

COMPLETE CODE

def f(x):
return x**3 - 2

def f_prime(x):
return 3*x**2

tolerance = 0.00001

# BISECTION METHOD
print("=== BISECTION METHOD ===")
a, b = 1, 2
bisection_iterations = 0

while (b - a) > tolerance:


c = (a + b) / 2
if f(a) * f(c) < 0:
b = c
else:
a = c
bisection_iterations = bisection_iterations + 1

bisection_root = (a + b) / 2

# NEWTON-RAPHSON METHOD
print("=== NEWTON-RAPHSON METHOD ===")
x = 1.5
newton_iterations = 0

while True:
x_new = x - f(x) / f_prime(x)
if abs(x_new - x) < tolerance:
break
x = x_new
newton_iterations = newton_iterations + 1

newton_root = x

# COMPARISON
print(f"Bisection root: {bisection_root:.6f} (Iterations: {bisection_iterations})")
print(f"Newton-Raphson root: {newton_root:.6f} (Iterations: {newton_iterations})")
print(f"\nNewton-Raphson converged {bisection_iterations/newton_iterations:.1f}x faster!

OUTPUT

Bisection root: 1.259921 (Iterations: 24)


Newton-Raphson root: 1.259921 (Iterations: 4)

Newton-Raphson converged 6.0x faster!

QUICK REFERENCE GUIDE

All Operators

Type Examples

Arithmetic +, -, *, /, **, %, //

Comparison ==, !=, <, >, <=, >=

Logical and, or, not

Assignment =, +=, -=, *=, /=

All Methods

Task Code

Print print()

Input input()
Task Code

Type type()

Length len()

Sum sum()

Max max()

Min min()

Range range()

File open() , close() , read() , write()

List append() , remove() , pop() , insert()

Sort sorted()

Loop Structures

# For loop
for i in range(10):
print(i)

# While loop
while condition:
print("doing")

# For with list


for item in my_list:
print(item)

Function Structure

def function_name(parameter1, parameter2):


# Code
return result

IMPORTANT EXAM TIPS


✅ Always indent code properly (4 spaces) ✅ Use meaningful variable names ✅ Add comments
to explain code ✅ Test code with different inputs ✅ Close files after using them ✅ Check math
formulas carefully ✅ Start with simple examples ✅ Write code step by step ✅ Don't copy-paste
during exams ✅ Show all your working

COMMON ERRORS TO AVOID


⠌ Forgetting to close files ⠌ Mixing up = and == ⠌ Not indenting if/while/for blocks ⠌ Wrong
list index (remember: starts at 0) ⠌ Division by zero ⠌ Variable used before definition ⠌ Wrong
number of function parameters ⠌ Forgetting parentheses on print()

STUDY SCHEDULE
Week 1:

Day 1-2: Topic 1 (Variables, Operators, Conditions)


Day 3-4: Topic 1 (Loops, Functions)
Day 5: Topic 2 (File Handling)
Day 6-7: Topic 3 (Lists)

Week 2:

Day 1-2: Topic 4 (Least Squares)


Day 3-4: Topic 5 (Bisection Method)
Day 5-6: Topic 6 (Newton-Raphson)
Day 7: Revision and Practice

COMPLETE SYLLABUS DOCUMENT All 6 Topics Covered WBSU Semester 1 - Python Programming

Study one topic per day. Write all code yourself. Practice with different values. Good luck!

Created: December 2025 For: WBSU Semester 1 Students Status: COMPLETE FULL SYLLABUS

You might also like