0% found this document useful (0 votes)
4 views11 pages

BCA Python Program 1 to 14

The document contains 14 Python programs that demonstrate various functionalities including area calculation of a circle, arithmetic operations, finding the largest of three numbers, identifying prime numbers, separating odd and even numbers, implementing a simple calculator, calculating factorials, summing an array, performing string operations, calculating date differences, and manipulating lists, tuples, dictionaries, and files. Each program is designed to prompt user input and display results based on the operations performed. The programs cover a wide range of basic programming concepts and operations.

Uploaded by

karpagam
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)
4 views11 pages

BCA Python Program 1 to 14

The document contains 14 Python programs that demonstrate various functionalities including area calculation of a circle, arithmetic operations, finding the largest of three numbers, identifying prime numbers, separating odd and even numbers, implementing a simple calculator, calculating factorials, summing an array, performing string operations, calculating date differences, and manipulating lists, tuples, dictionaries, and files. Each program is designed to prompt user input and display results based on the operations performed. The programs cover a wide range of basic programming concepts and operations.

Uploaded by

karpagam
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/ 11

Program 1

Area Calculation
PI = 3.14

def calc_radius():
radius = float(input("Enter Radius of Circle : "))
area = PI * radius ** 2
print(f"The area of Circle Radius {radius} is : ", area)

calc_radius()

Program 2
Arithmetic Operations
def calculate():
num1 = float(input("Enter First Value : " ))
num2 = float(input("Enter Second Value : "))

print("\n Arithmetic Operations")


print(f"Addition : {num1} + {num2} = {num1 + num2}")
print(f"Subtract : {num1} - {num2} = {num1 - num2}")
print(f"Divide : {num1} / {num2} = {num1 / num2}")
print(f"Multiply : {num1} * {num2} = {num1 * num2}")
print(f"Modulus : {num1} % {num2} = {num1 % num2}")

calculate()
Program 3
Largest Among Three Numbers
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
c = int(input("Enter the third number: "))

if a >= b and a >= c:


result=a
elif b >= a and b >= c:
result=b
else:
result=c

print(f"The largest number among {a}, {b}, {c} is {result}.")

Program 4
Prime Number
start = int(input("Enter the starting number of the range: "))
end = int(input("Enter the ending number of the range: "))

print(f"Prime numbers between {start} and {end} are:")

for num in range(start, end + 1):


if num > 1:
for i in range(2, int(num ** 0.5) + 1):
if (num % i) == 0:
break
else:
print(num)
Program 5
Odd and Even Numbers
def odd_even(numbers):
even_no = []
odd_no = []

for num in numbers:


if num == 0:
continue
elif num % 2 == 0:
even_no.append(num)
else:
odd_no.append(num)

return even_no, odd_no

def get_no():
start = int(input("Enter the start of the range: "))
end = int(input("Enter the end of the range: "))
return list(range(start, end + 1))

numbers_list = get_no()

evens, odds = odd_even(numbers_list)

print(f"Even numbers: {evens}")


print(f"Odd numbers: {odds}")
Program 6
Simple Calculator

def add(a, b):


return a + b

def subtract(a, b):


return a - b

def multiply(a, b):


return a * b

def divide(a, b):


if b == 0:
return "Error: Division by zero is not allowed."
return a / b

def calculator():
print("Simple Calculator!")
print("Select an operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

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

if choice in ['1', '2', '3', '4']:


num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(f"Adding {num1} and {num2} is :", add(num1, num2))
elif choice == '2':
print(f"Subtracting {num1} from {num2} is :", subtract(num1, num2))
elif choice == '3':
print(f"Multiplying {num1} and {num2} is :", multiply(num1, num2))
elif choice == '4':
print(f"Dividing {num1} by {num2} is :", divide(num1, num2))
else:
print("Invalid input! Please select a valid operation.")

calculator()

Program 7
Factorial

def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

def main():
number = int(input("Enter an Integer: "))
if number < 0:
print("Negative Number not Allowed.")
else:
result = factorial(number)
print(f"The factorial of {number} is {result}")

main()
Program 8
Sum of Array

def sum_array(numbers):
total = 0
for num in numbers:
total += num
return total

def main_arr():
n = int(input("Enter the number of elements in the array: "))

numbers = []

for i in range(n):
num = int(input(f"Enter element {i + 1}: "))
numbers.append(num)

print("Array elements are:", numbers)

total_sum = sum_array(numbers)
print("Sum of Array Elements :", total_sum)

main_arr()
Program 9
String Operations

def string_operations():
s1 = input("Enter the first string: ")
s2 = input("Enter the second string: ")

con_str = s1 + " " + s2


print("\nConcatenated String:", con_str)

print("Length of the concatenated string:", len(con_str))

print("First character:", con_str[0])


print("Last character:", con_str[-1])

print("Sliced String (from index 1 to 4):", con_str[1:5])

print("Uppercase string:", con_str.upper())


print("Lowercase string:", con_str.lower())

string_operations()

Program 10
Date Difference

import datetime

def date_difference():
date1_str = input("Enter the first date (YYYY-MM-DD): ")
date2_str = input("Enter the second date (YYYY-MM-DD): ")

date1 = datetime.datetime.strptime(date1_str, "%Y-%m-%d")


date2 = datetime.datetime.strptime(date2_str, "%Y-%m-%d")
if date2 < date1:
date1, date2 = date2, date1
difference = date2 - date1
print(f"Difference between {date1_str} and {date2_str} is {difference.days} days.")

print("Calculate Date Difference")


date_difference()

Program 11
List Operation

def list_operations():
numbers = []

n = int(input("Enter the Number of Elements: "))

for i in range(n):
getno = int(input(f"Enter element {i+1}: "))
numbers.append(getno)

print("\nThe list of numbers entered:", numbers)

print("Sum Value: ",sum(numbers))

print("Ascending Order: ", sorted(numbers))

print("Descending Order:",sorted(numbers, reverse=True))

del_no = int(input("\nEnter an Element to Remove : "))


if del_no in numbers:
numbers.remove(del_no)
print(f"After Removing {del_no}:", numbers)
else:
print(f"Element {del_no} Not Found.")

list_operations()
Program 12
Tuple Operations
def tuple_func():
n = int(input("Enter the number of elements: "))
my_tuple = tuple(input(f"Enter Element {i+1}: ") for i in range(n))

print("\nTuple Elements:", my_tuple)

try:
index = int(input(f"Enter an index to access (0 to {n-1}): "))
print(f"Selected Element at {index}: {my_tuple[index]}")
except IndexError:
print("Invalid index")

print(f"Length of the tuple: {len(my_tuple)}")

count_element = input("Enter an element to count: ")


print(f"{count_element} occurs {my_tuple.count(count_element)} time(s) in the tuple.")

tuple_func()
Program 13
Dictionary Operations

def dict_op():
user_dict = {}

get_entry = int(input("Enter No. of Key - Pair Values : "))

for i in range(get_entry):
key = input(f"Enter key {i+1}: ")
value = input(f"Enter value for '{key}': ")
user_dict[key] = value

print("\nDictionary created:", user_dict)

search_key = input("\nEnter the key to show value: ")

value = user_dict.get(search_key, "Key not found")


print(f"The value for '{search_key}' is: {value}")

new_key = input("Enter new key: ")


new_value = input(f"Enter value for '{new_key}': ")
user_dict[new_key] = new_value

print(f"\nUpdated Dictionary: {user_dict}")

dict_op()
Program 14
File Handling

def file_handle():
with open("sample.txt", "w") as file:
file.write("Hello, this is the first line of text.\n")
file.write("This is the second line of text.\n")
print("Data written to 'sample.txt'.\n")

print("Reading data from 'sample.txt':")


with open("sample.txt", "r") as file:
print(file.read())

with open("sample.txt", "a") as file:


file.write("This is an appended line.\n")
print("New data appended to 'sample.txt'.\n")

print("Reading updated data from 'sample.txt':")


with open("sample.txt", "r") as file:
print(file.read())

file_handle()

You might also like