WEEK 4 Programs:
1. Command Line / Terminal (Most
Common)
Save your program in a file, e.g., program.py.
- Open a terminal/command prompt.
- Navigate to the folder where the file is
saved:
·
cd path/to/your/file
Run the file:
·
python program.py
(Use python3 instead of python on Linux/Mac if needed.)
2. IDLE (Python’s Built-in IDE)
·
Open
IDLE (comes with Python).
·
Go
to File → Open…
and select your .py file.
·
Press
F5 (or Run
→ Run Module).
·
Output
will appear in the IDLE shell.
3. VS Code (Visual Studio Code)
·
Install
VS Code.
·
Install
Python Extension
(by Microsoft).
·
Open
your .py file in VS Code.
·
Run:
o
Press
Run ▶ in the top right corner.
o
Or
use terminal inside VS Code:
bash
python program.py
4. PyCharm
·
Install
PyCharm.
·
Open
a new project or import your existing one.
·
Right-click
your Python file → Run
'program'.
·
Output
shows in PyCharm’s console.
5. Jupyter Notebook
·
Install
Jupyter:
bashpip install notebook
·
Start
it:
bashjupyter notebook
·
A
browser window opens → you can open .ipynb or create a new notebook.
·
To
run .py files:
python
%run program.py
6. Google Colab (Online)
·
Open
Google Colab.
·
Upload
your .py file or copy-paste the code.
·
Run
a cell with:
python!python program.py
·
Great
for cloud execution (no installation needed).
7. Anaconda / Spyder
·
Install
Anaconda (includes Spyder IDE).
·
Open
Spyder → open your .py file.
·
Click
Run ▶
·
Output
appears in Spyder’s console.
ü
For
beginners → IDLE or VS
Code.
ü
For
data science → Jupyter
Notebook / Colab.
ü
For
advanced development → PyCharm
/ VS Code.
ü
For
quick testing → Command
Line.
·
For 1st to 3rd Program write a separate program in notepad
and save it with source.txt and sorted_words.txt
·
Save that file in drive with separate folder and upload it in Google
colab
·
Now write a program in Google
colab and run you will get your output
1. Write a program to sort
words in a file and put them in another file. The output file should have only
lower-case words, so any upper-case words from source must be lowered.
# Create a
source.txt file with some words
with
open("source.txt", "w") as f:
f.write("Apple
orange Banana grape Cherry Mango Kiwi")
# Program to
read words from a file, sort them, and write to another file in lowercase
#
Input and output file names
input_file =
"source.txt"
output_file =
"sorted_words.txt"
#
Step 1: Read all words from the input file
with
open(input_file, "r") as f:
text = f.read()
#
Step 2: Convert text to lowercase and split into words
words =
text.lower().split()
#
Step 3: Sort words alphabetically
words.sort()
#
Step 4: Write sorted words into the output file
with
open(output_file, "w") as f:
for word in words:
f.write(word + "\n")
print("Words
have been sorted and saved in", output_file)
OUTPUT:
Words have been sorted and saved in sorted_words.txt
#
Display the sorted words file
with open("sorted_words.txt",
"r") as f:
print(f.read())
OUTPUT:
apple
banana
cherry
grape
kiwi
mango
orange
2. Python program to print
each line of a file in reverse order.
#
Program to print each line of a file in reverse order
#
Input file name
input_file =
"source.text.txt" # Corrected filename
#
Open and read file
with
open(input_file, "r") as f:
lines = f.readlines()
#
Print each line in reverse
print("Reversed
lines:\n")
for line in
lines:
# Strip newline, reverse, then print
print(line.strip()[::-1])
(Optional) — Save reversed lines into
another file
output_file = "reversed.txt"
with open(output_file, "w") as f:
for line in
lines:
f.write(line.strip()[::-1] + "\n")
print(f"Reversed lines saved in {output_file}")
OUTPUT:
Reversed
lines:
elppA
ananab
yreehc
iwik
eparg
3. Python program to
compute the number of characters, words and lines in a file.
CODE:
filename =
"source.txt"
#
Initialize counters
num_lines = 0
num_words = 0
num_chars = 0
#
Open and read file
with
open(filename, "r") as f:
for line in f:
num_lines += 1
num_words += len(line.split())
num_chars += len(line)
#
Display the results
print("Number
of lines:", num_lines)
print("Number
of words:", num_words)
print("Number
of characters:", num_chars)
OUTPUT:
Number of
lines: 5
Number of
words: 5
Number of characters: 34
Explanation:
·
len(line.split()) →
counts words in a line.
·
len(line) → counts all
characters including spaces and newline (\n).
·
num_lines += 1 → counts
total lines.
4. Write a program to
create, display, append, insert and reverse the order of the items in the
array.
from array
import array
#
Step 1: Create an array of integers
arr = array('i',
[10, 20, 30, 40, 50])
print("Original
array:", arr.tolist())
#
Step 2: Display array elements
print("Array
elements:")
for i in arr:
print(i, end=" ")
print()
#
Step 3: Append an element
arr.append(60)
print("\nAfter
appending 60:", arr.tolist())
#
Step 4: Insert an element at a specific position
arr.insert(2,
25) # insert 25 at index 2
print("After
inserting 25 at index 2:", arr.tolist())
#
Step 5: Reverse the array
arr.reverse()
print("After
reversing:", arr.tolist())
OUTPUT:
Original
array: [10, 20, 30, 40, 50]
Array
elements:
10 20 30 40
50
After
appending 60: [10, 20, 30, 40, 50, 60]
After
inserting 25 at index 2: [10, 20, 25, 30, 40, 50, 60]
After reversing: [60, 50, 40, 30, 25, 20, 10]
Explanation
·
array('i', [...]) → creates an integer
array.
·
append() → adds an item at the end.
·
insert(index, value) → inserts at a
specific index.
·
reverse() → reverses the array in place.
·
tolist() → converts the array to a
normal Python list for easy printing.
5. Write a program to add,
transpose and multiply two matrices.
#
Program to add, transpose, and multiply two matrices
#
Step 1: Define two matrices
A = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
B = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
]
#
Step 2: Matrix Addition
add_result =
[[A[i][j] + B[i][j] for j in range(len(A[0]))] for i in range(len(A))]
#
Step 3: Transpose of Matrix A
transpose_A =
[[A[j][i] for j in range(len(A))] for i in range(len(A[0]))]
#
Step 4: Matrix Multiplication (A × B)
multiply_result
= [[sum(A[i][k] * B[k][j] for k in range(len(B))) for j in range(len(B[0]))]
for i in range(len(A))]
#
Step 5: Display Results
print("Matrix
A:")
for row in A:
print(row)
print("\nMatrix
B:")
for row in B:
print(row)
print("\nAddition
of A and B:")
for row in
add_result:
print(row)
print("\nTranspose
of A:")
for row in
transpose_A:
print(row)
print("\nMultiplication
of A and B:")
for row in
multiply_result:
print(row)
OUTPUT:
Matrix A:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Matrix B:
[9, 8, 7]
[6, 5, 4]
[3, 2, 1]
Addition of
A and B:
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]
Transpose of
A:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
Multiplication
of A and B:
[30, 24, 18]
[84, 69, 54]
[138, 114,
90]
Explanation
·
Addition: Add elements at the same positions.
·
Transpose: Swap rows with columns.
·
Multiplication: Use dot product of rows and columns.
6. Write a Python program to create a class that represents
a shape. Include methods to calculate its area and perimeter. Implement
subclasses for different shapes like circle, triangle, and square.
Program: Shape Class with Subclasses
import math
# Base class
class Shape:
def
area(self):
return 0
def
perimeter(self):
return 0
# Subclass:
Circle
class Circle(Shape):
def
__init__(self, radius):
self.radius = radius
def
area(self):
return math.pi * self.radius ** 2
def
perimeter(self):
return 2 * math.pi * self.radius
# Subclass:
Square
class Square(Shape):
def
__init__(self, side):
self.side = side
def
area(self):
return self.side ** 2
def
perimeter(self):
return 4 * self.side
# Subclass:
Triangle
class Triangle(Shape):
def
__init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def
perimeter(self):
return
self.a + self.b + self.c
def
area(self):
#
Using Heron's Formula
s =
self.perimeter() / 2
return math.sqrt(s * (s - self.a) * (s - self.b) * (s - self.c))
# ---- Test the
classes ----
# Create objects
circle = Circle(5)
square = Square(4)
triangle = Triangle(3, 4, 5)
# Display results
print("Circle: Area =",
round(circle.area(), 2), "Perimeter =", round(circle.perimeter(), 2))
print("Square: Area =", square.area(),
"Perimeter =", square.perimeter())
print("Triangle: Area =",
round(triangle.area(), 2), "Perimeter =", triangle.perimeter())
OUTPUT:
Circle: Area = 78.54 Perimeter = 31.42
Square: Area = 16 Perimeter = 16
Triangle: Area = 6.0 Perimeter = 12
Concepts Used
- Base class (Shape) defines common methods (area() and perimeter()).
- Subclasses (Circle, Square, Triangle)
override these methods.
- Heron’s formula is used to calculate the triangle’s area.
No comments:
Post a Comment