0% found this document useful (0 votes)
35 views25 pages

Python Lab - Bcomca - Docx - 20240716 - 164225 - 0000

Uploaded by

sfasihataranum
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)
35 views25 pages

Python Lab - Bcomca - Docx - 20240716 - 164225 - 0000

Uploaded by

sfasihataranum
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
You are on page 1/ 25

1.

Fahrenheit to Celsius

Aim:

To develop a Python program that converts the given temperature from Fahrenheit to Celsius and vice
versa based on the user's choice.

Algorithm:

1. Start.
2. Display a menu to the user:
Option 1: Convert Fahrenheit to Celsius.
Option 2: Convert Celsius to Fahrenheit.
3. Read the user's choice.
4. If the choice is 1:
Prompt the user to enter the temperature in Fahrenheit.
Convert the temperature to Celsius using the formula: C=(F−32)×59C = (F - 32) \times \frac{5}
{9}C=(F−32)×95​.
Display the temperature in Celsius.
5. If the choice is 2:
Prompt the user to enter the temperature in Celsius.
Convert the temperature to Fahrenheit using the formula: F=C×95+32F = C \times \frac{9}{5} +
32F=C×59​+32.
Display the temperature in Fahrenheit.
6. If the choice is neither 1 nor 2:
Display an error message.
7. End.

Program:

def fahrenheit_to_celsius(fahrenheit):

return (fahrenheit - 32) * 5.0 / 9.0

def celsius_to_fahrenheit(celsius):

return celsius * 9.0 / 5.0 + 32

def main():

print("Temperature Conversion Program")

print("1. Convert Fahrenheit to Celsius")

print("2. Convert Celsius to Fahrenheit")


choice = int(input("Enter your choice (1 or 2): "))

if choice == 1:

fahrenheit = float(input("Enter temperature in Fahrenheit: "))

celsius = fahrenheit_to_celsius(fahrenheit)

print(f"{fahrenheit} Fahrenheit is equal to {celsius:.2f} Celsius.")

elif choice == 2:

celsius = float(input("Enter temperature in Celsius: "))

fahrenheit = celsius_to_fahrenheit(celsius)

print(f"{celsius} Celsius is equal to {fahrenheit:.2f} Fahrenheit.")

else:

print("Invalid choice! Please enter 1 or 2.")

if __name__ == "__main__":

main()

Output:

Case 1: Converting Fahrenheit to Celsius

Temperature Conversion Program

1. Convert Fahrenheit to Celsius

2. Convert Celsius to Fahrenheit

Enter your choice (1 or 2): 1

Enter temperature in Fahrenheit: 98.6

98.6 Fahrenheit is equal to 37.00 Celsius.

Case 2: Converting Celsius to Fahrenheit

Temperature Conversion Program

1. Convert Fahrenheit to Celsius


2. Convert Celsius to Fahrenheit

Enter your choice (1 or 2): 2

Enter temperature in Celsius: 37

37 Celsius is equal to 98.60 Fahrenheit.

Case 3: Invalid Choice

Temperature Conversion Program

1. Convert Fahrenheit to Celsius

2. Convert Celsius to Fahrenheit

Enter your choice (1 or 2): 3

Invalid choice! Please enter 1 or 2.

1. Nested Loop

Aim:

To write a Python program that constructs the following pattern using nested loops:

Algorithm:
1. Define a function called print_pattern that takes a single argument rows.
2. Inside the function:
Loop through each row from 1 to rows (inclusive) to print the upper part of the pattern.
For each row, calculate the number of spaces needed before printing the asterisks for center
alignment.
Print the spaces followed by the appropriate number of asterisks.
Next, loop through each row from rows-1 down to 1 to print the lower part of the pattern.
Again, calculate the spaces and print the asterisks.
3. Define a main function:
Set the value of rows to 5.
Call the print_pattern function with the specified number of rows.
4. Finally, execute the main function if the script is run directly (i.e., not imported as a module).

Program:

def print_pattern(rows):

# Upper part of the pattern

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

# Print spaces before printing asterisks for center alignment

print(' ' * (rows - i) + '* ' * i)

# Lower part of the pattern

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

# Print spaces before printing asterisks for center alignment

print(' ' * (rows - i) + '* ' * i)

def main():

rows = 5 # Number of rows in the pattern

print_pattern(rows)

if __name__ == "__main__":

main()
Output:

**

***

****

*****

****

***

**

*
1. Student Mark Detail

Aim:

To develop a Python program that calculates the total marks, percentage, and grade of a student based on
marks obtained in five subjects’ input by the user.

Algorithm:

1. Start.
2. Prompt the user to input the marks for five subjects.
3. Calculate the total marks by summing the marks of all five subjects.
4. Calculate the percentage by dividing the total marks by the number of subjects and multiplying by
100.
5. Determine the grade based on the percentage:
If percentage >= 80, assign Grade A.
If 70 <= percentage < 80, assign Grade B.
If 60 <= percentage < 70, assign Grade C.
If 40 <= percentage < 60, assign Grade D.
If percentage < 40, assign Grade E.
6. Display the total marks, percentage, and grade.
d
7. End.

Program:

def calculate_grade(percentage):

if percentage >= 80:

return 'A'

elif percentage >= 70:

return 'B'

elif percentage >= 60:

return 'C'

elif percentage >= 40:

return 'D'

else:

return 'E'

def main():

subjects = 5

marks = []

for i in range(subjects):

mark = float(input(f"Enter marks for subject {i+1}: "))

marks.append(mark)

total_marks = sum(marks)

percentage = (total_marks / (subjects * 100)) * 100

grade = calculate_grade(percentage)

print(f"Total Marks: {total_marks}")

print(f"Percentage: {percentage:.2f}%")

print(f"Grade: {grade}")
if __name__ == "__main__":

main()

Output:

Enter marks for subject 1: 85

Enter marks for subject 2: 78

Enter marks for subject 3: 90

Enter marks for subject 4: 68

Enter marks for subject 5: 74

Total Marks: 395.0

Percentage: 79.00%

Grade: B
1. Area of rectangle, square, circle and triangle

Aim:

To create a Python program that calculates and displays the area of a rectangle, square, circle, or triangle
based on user-provided dimensions.

Algorithm:

1. Display a menu of shapes to the user (Rectangle, Square, Circle, Triangle).


2. Prompt the user to enter the choice of shape.
3. Depending on the choice:
For Rectangle:
Prompt for length and breadth.
Calculate area using the formula: area=length×breadth\text{area} = \text{length} \times
\text{breadth}area=length×breadth.
For Square:
Prompt for side length.
Calculate area using the formula: area=side×side\text{area} = \text{side} \times
\text{side}area=side×side.
For Circle:
Prompt for radius.
Calculate area using the formula: area=π×radius2\text{area} = \pi \times
\text{radius}^2area=π×radius2, where π\piπ is a constant provided by the math module.
For Triangle:
Prompt for base and height.
Calculate area using the formula: area=12×base×height\text{area} = \frac{1}{2} \times
\text{base} \times \text{height}area=21​×base×height.
4. Print the calculated area for the chosen shape.
Program:

import math

def main():

print("Welcome to the Area Calculator!")

print("Choose a shape to find the area:")

print("1. Rectangle")

print("2. Square")

print("3. Circle")

print("4. Triangle")

choice = int(input("Enter your choice (1/2/3/4): "))

if choice == 1:

# Rectangle

length = float(input("Enter the length of the rectangle: "))

breadth = float(input("Enter the breadth of the rectangle: "))

area = length * breadth

print(f"The area of the rectangle is: {area}")

elif choice == 2:

# Square

side = float(input("Enter the side length of the square: "))

area = side * side

print(f"The area of the square is: {area}")

elif choice == 3:

# Circle
radius = float(input("Enter the radius of the circle: "))

area = math.pi * (radius ** 2)

print(f"The area of the circle is: {area}")

elif choice == 4:

# Triangle

base = float(input("Enter the base of the triangle: "))

height = float(input("Enter the height of the triangle: "))

area = 0.5 * base * height

print(f"The area of the triangle is: {area}")

else:

print("Invalid choice. Please enter a valid option.")

if __name__ == "__main__":

main()

Output:

Welcome to the Area Calculator!

Choose a shape to find the area:

1. Rectangle

2. Square

3. Circle

4. Triangle

Enter your choice (1/2/3/4): 3

Enter the radius of the circle: 5

The area of the circle is: 78.53981633974483


1. Prime numbers

Aim:

To write a Python script that identifies and prints all prime numbers less than 20.

Algorithm:

1. Initialize an empty list to store prime numbers.


2. Loop through numbers from 2 to 19 (since prime numbers are greater than 1).
3. For each number, check if it is prime:
A number is prime if it is greater than 1 and has no divisors other than 1 and itself.
Use a nested loop to check divisibility from 2 up to the square root of the number (for
optimization).
4. If the number is prime, add it to the list of prime numbers.
5. Print the list of prime numbers less than 20.

Program:

import math

def is_prime(num):

""" Function to check if a number is prime """

if num <= 1:

return False

if num == 2:

return True # 2 is a prime number

if num % 2 == 0:

return False # Other even numbers are not primes

# Check for odd factors from 3 upwards


max_check = math.isqrt(num) + 1

for i in range(3, max_check, 2):

if num % i == 0:

return False

return True

def main():

prime_numbers = []

for num in range(2, 20):

if is_prime(num):

prime_numbers.append(num)

print("Prime numbers less than 20:")

print(prime_numbers)

if __name__ == "__main__":

main()

Output:

Prime numbers less than 20:

[2, 3, 5, 7, 11, 13, 17, 19]


1. Factorial

Aim:

To create a Python program that computes the factorial of a number using recursion.

Algorithm:

1. Define a function factorial(n) that:


Checks if n is 0 or 1. If so, returns 1 (base case for factorial).
Otherwise, recursively calls itself with n-1 and multiplies the result by n.
2. In the main program:
Prompt the user to enter a number whose factorial is to be calculated.
Call the factorial() function with the user-provided number.
Print the computed factorial.

Program:

def factorial(n):

""" Recursive function to calculate factorial """

if n == 0 or n == 1:

return 1

else:

return n * factorial(n - 1)

def main():

num = int(input("Enter a number to find its factorial: "))

if num < 0:

print("Factorial is not defined for negative numbers.")

else:

result = factorial(num)

print(f"The factorial of {num} is: {result}")

if __name__ == "__main__":
main()

Output:

Enter a number to find its factorial: 5

The factorial of 5 is: 120

1. Even and Odd numbers from array

Aim:

To create a Python program that allows the user to input an array of N numbers and then counts and
prints the number of even and odd numbers in the array.

Algorithm:

1. Prompt the user to input the number of elements NNN in the array.
2. Initialize two counters: even_count and odd_count to 0.
3. Iterate through each number in the array:
Check if the number is even (i.e., num % 2 == 0). If true, increment even_count.
Otherwise, increment odd_count.
4. Print the counts of even and odd numbers.

Program:

def count_even_odd(arr):

""" Function to count even and odd numbers """

even_count = 0
odd_count = 0

for num in arr:

if num % 2 == 0:

even_count += 1

else:

odd_count += 1

return even_count, odd_count

def main():

# Prompt the user to enter the array

N = int(input("Enter the number of elements in the array: "))

arr = []

print("Enter the elements of the array:")

for i in range(N):

num = int(input(f"Enter element {i+1}: "))

arr.append(num)

# Call function to count even and odd numbers

even_count, odd_count = count_even_odd(arr)

# Print the counts

print(f"Number of even numbers: {even_count}")

print(f"Number of odd numbers: {odd_count}")

if __name__ == "__main__":

main()
Output:

Enter the number of elements in the array: 6

Enter the elements of the array:

Enter element 1: 1

Enter element 2: 2

Enter element 3: 3

Enter element 4: 4

Enter element 5: 5

Enter element 6: 6

Number of even numbers: 3

Number of odd numbers: 3


1. Reverse a string

Aim:

To create a Python class that accepts a string input and reverses it word by word.

Algorithm:

1. Define a class ReverseString with:


A constructor (__init__) that initializes with the input string.
A method reverse_words() that splits the string into words, reverses their order, and joins them
back into a single string.
2. In the reverse_words() method:
Split the string into words using split().
Reverse the list of words using slicing ([::-1]).
Join the reversed words into a single string using join().
3. Create an instance of ReverseString, call the reverse_words() method, and print the reversed string.

Program:

class ReverseString:

def __init__(self, input_str):

self.input_str = input_str
def reverse_words(self):

words = self.input_str.split()

reversed_words = words[::-1]

reversed_string = ' '.join(reversed_words)

return reversed_string

def main():

input_str = input("Enter a string to reverse word by word: ")

reverser = ReverseString(input_str)

reversed_string = reverser.reverse_words()

print("Original string:", input_str)

print("Reversed string (word by word):", reversed_string)

if __name__ == "__main__":

main()

Output:

Enter a string to reverse word by word: Hello World

Original string: Hello World

Reversed string (word by word): World Hello

1. File Handling

Aim:

To create a Python program that reads the contents of a file and copies only the contents at odd lines into
a new file.
Algorithm:

1. Prompt the user to enter the filenames for the input and output files.
2. Open the input file in read mode.
3. Open the output file in write mode.
4. Iterate through each line in the input file:
Check if the line number is odd (line_number % 2 != 0).
If true, write the line to the output file.
5. Close both the input and output files.

Program:

def copy_odd_lines(input_file, output_file):

try:

with open(input_file, 'r') as file_in, open(output_file, 'w') as file_out:

line_number = 1

for line in file_in:

if line_number % 2 != 0:

file_out.write(line)

line_number += 1

print(f"Odd lines from {input_file} have been copied to {output_file} successfully.")

except FileNotFoundError:

print("File not found. Please check the file path and try again.")

def main():

input_file = input("Enter the input file name: ")

output_file = input("Enter the output file name: ")

copy_odd_lines(input_file, output_file)

if __name__ == "__main__":

main()

Example:
Suppose you have a file named input.txt with the following content:

Line 1: This is the first line.

Line 2: This is the second line.

Line 3: This is the third line.

Line 4: This is the fourth line.

Line 5: This is the fifth line.

Output:

If you run the program and provide input.txt as the input file and output.txt as the output file, the
program will create a new file output.txt with the following content:

Line 1: This is the first line.

Line 3: This is the third line.

Line 5: This is the fifth line.

Explanation:

copy_odd_lines(input_file, output_file) function:


Takes input_file (the file to read from) and output_file (the file to write odd lines to) as
parameters.
Opens input_file in read mode ('r') and output_file in write mode ('w').
Iterates through each line in input_file.
Checks if the line number is odd (line_number % 2 != 0) and writes the line to output_file if true.
Handles FileNotFoundError if the input file is not found.
main() function:
Prompts the user to enter the filenames (input_file and output_file).
Calls copy_odd_lines(input_file, output_file) to perform the operation.

This program effectively reads a file, copies only the contents at odd lines into a new file, and handles basic
file operations and exceptions gracefully.Top of Form
1. Turtle graphics window

Aim:

To create a Turtle graphics window with a specific size.

Algorithm:

1. Import the turtle module.


2. Initialize the Turtle screen with a specific size using setup(width, height).
3. Set the background color of the screen if desired using bgcolor().
4. Optionally, set the title of the window using title().
5. Keep the window open until the user closes it by calling mainloop().

Program:

import turtle

def main():
# Setup the Turtle screen

screen = turtle.Screen()

# Set the screen size (width, height)

screen.setup(width=600, height=400)

# Set background color (optional)

screen.bgcolor("lightblue")

# Set window title (optional)

screen.title("Turtle Graphics Window")

# Keep the window open until user closes it

turtle.done()

if __name__ == "__main__":

main()

Output:

Upon running the program, a Turtle graphics window with dimensions 600 pixels wide and 400 pixels high
will appear. The background color will be set to light blue (if specified), and the window title will be
"Turtle Graphics Window".

Explanation:

turtle.Screen(): Initializes the Turtle screen, allowing for customization.


screen.setup(width, height): Sets the dimensions of the Turtle graphics window.
screen.bgcolor("color"): Sets the background color of the Turtle graphics window (optional).
screen.title("title"): Sets the title of the Turtle graphics window (optional).
turtle.done(): Keeps the Turtle graphics window open until the user closes it.

Bottom of Form

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy