Python Lab - Bcomca - Docx - 20240716 - 164225 - 0000
Python Lab - Bcomca - Docx - 20240716 - 164225 - 0000
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):
def celsius_to_fahrenheit(celsius):
def main():
if choice == 1:
celsius = fahrenheit_to_celsius(fahrenheit)
elif choice == 2:
fahrenheit = celsius_to_fahrenheit(celsius)
else:
if __name__ == "__main__":
main()
Output:
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):
def main():
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):
return 'A'
return 'B'
return 'C'
return 'D'
else:
return 'E'
def main():
subjects = 5
marks = []
for i in range(subjects):
marks.append(mark)
total_marks = sum(marks)
grade = calculate_grade(percentage)
print(f"Percentage: {percentage:.2f}%")
print(f"Grade: {grade}")
if __name__ == "__main__":
main()
Output:
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:
import math
def main():
print("1. Rectangle")
print("2. Square")
print("3. Circle")
print("4. Triangle")
if choice == 1:
# Rectangle
elif choice == 2:
# Square
elif choice == 3:
# Circle
radius = float(input("Enter the radius of the circle: "))
elif choice == 4:
# Triangle
else:
if __name__ == "__main__":
main()
Output:
1. Rectangle
2. Square
3. Circle
4. Triangle
Aim:
To write a Python script that identifies and prints all prime numbers less than 20.
Algorithm:
Program:
import math
def is_prime(num):
if num <= 1:
return False
if num == 2:
if num % 2 == 0:
if num % i == 0:
return False
return True
def main():
prime_numbers = []
if is_prime(num):
prime_numbers.append(num)
print(prime_numbers)
if __name__ == "__main__":
main()
Output:
Aim:
To create a Python program that computes the factorial of a number using recursion.
Algorithm:
Program:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
def main():
if num < 0:
else:
result = factorial(num)
if __name__ == "__main__":
main()
Output:
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):
even_count = 0
odd_count = 0
if num % 2 == 0:
even_count += 1
else:
odd_count += 1
def main():
arr = []
for i in range(N):
arr.append(num)
if __name__ == "__main__":
main()
Output:
Enter element 1: 1
Enter element 2: 2
Enter element 3: 3
Enter element 4: 4
Enter element 5: 5
Enter element 6: 6
Aim:
To create a Python class that accepts a string input and reverses it word by word.
Algorithm:
Program:
class ReverseString:
self.input_str = input_str
def reverse_words(self):
words = self.input_str.split()
reversed_words = words[::-1]
return reversed_string
def main():
reverser = ReverseString(input_str)
reversed_string = reverser.reverse_words()
if __name__ == "__main__":
main()
Output:
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:
try:
line_number = 1
if line_number % 2 != 0:
file_out.write(line)
line_number += 1
except FileNotFoundError:
print("File not found. Please check the file path and try again.")
def main():
copy_odd_lines(input_file, output_file)
if __name__ == "__main__":
main()
Example:
Suppose you have a file named input.txt with the following content:
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:
Explanation:
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:
Algorithm:
Program:
import turtle
def main():
# Setup the Turtle screen
screen = turtle.Screen()
screen.setup(width=600, height=400)
screen.bgcolor("lightblue")
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:
Bottom of Form