0% found this document useful (0 votes)
45 views

1st B. Com (Ca) Python Program

Python programming

Uploaded by

fasihataranum637
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)
45 views

1st B. Com (Ca) Python Program

Python programming

Uploaded by

fasihataranum637
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/ 14

1.

Fahrenheit to Celsius

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.
2.Nested Loop

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:

*
**
***
****
*****
****
***
**
*
3.Student Mark Detail

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
4.Area of rectangle, square, circle and triangle

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
5.Prime numbers

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]
6.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
7.Even and Odd numbers from array

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
8.Reverse a 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
9.File Handling

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()

Output:

Enter the input file name:input.txt


Enter the output file name:output.txt
Odd lines from input.txt have been copied to output.txt successfully.
Input.txt

Output.txt
10.Turtle graphics window

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:

You might also like