Ques 7: Create DataFrame
import pandas as pd
# Define the data as a dictionary
data = {
'Student_ID': [556, 557, 558],
'Name': ['Mothi', 'Alice', 'Bob'],
'Math_Score': [84, 90, 78],
'Science_Score': [96, 85, 88],
'English_Score': [84, 79, 92]
# Create the DataFrame
df = pd.DataFrame(data)
# Print the DataFrame
print("DataFrame:")
print(df)
OUTPUT :
DataFrame:
Student_ID Name Math_Score Science_Score English_Score
0 556 Mothi 84 96 84
1 557 Alice 90 85 79
2 558 Bob 78 88 92
Ques 8: write a program to check whether the given no is even or odd
def check_even_odd(number):
if number % 2 == 0:
return "even"
else:
return "odd"
def main():
try:
# Take input from the user
Mahesh Singh Parihar BCA section-B Roll No-2271176
number = int(input("Enter a number: "))
# Check whether the number is even or odd
result = check_even_odd(number)
# Print the result
print("The number {} is {}.".format(number, result))
except ValueError:
print("Please enter a valid integer.")
if __name__ == "__main__":
main()
OUTPUT :
Enter a number: 12
The number 12 is even.
Ques 9 :Write a program to get the marks of 5 subjects and calculate the average marks scored and
calculate the grade based on the average marks
If
Avg 91 to 100 (A grade)
71 to 80 (C grade )
61 to 60 (D grade)
51 to 60 (E grade)
>50 (fail)
def calculate_grade(average):
if average >= 91 and average <= 100:
return 'A'
elif average >= 81 and average <= 90:
return 'B'
elif average >= 71 and average <= 80:
return 'C'
Mahesh Singh Parihar BCA section-B Roll No-2271176
elif average >= 61 and average <= 70:
return 'D'
elif average >= 51 and average <= 60:
return 'E'
else:
return 'Fail'
def main():
try:
# Take input for the marks of 5 subjects
marks = []
for i in range(1, 6):
mark = float(input(f"Enter the marks for subject {i}: "))
marks.append(mark)
# Calculate the average marks
average = sum(marks) / len(marks)
# Calculate the grade based on the average marks
grade = calculate_grade(average)
# Print the results
print(f"\nAverage Marks: {average:.2f}")
print(f"Grade: {grade}")
except ValueError:
print("Please enter valid numeric values for the marks.")
if __name__ == "__main__":
main()
OUTPUT :
Enter the marks for subject 1: 77
Enter the marks for subject 2: 93
Enter the marks for subject 3: 69
Enter the marks for subject 4: 90
Mahesh Singh Parihar BCA section-B Roll No-2271176
Enter the marks for subject 5: 59
Average Marks: 77.60
Grade: C
Ques 10: Write a program to implement the simple calculator that performs basic mathematical
operation it takes 3 inputs from the user at first the user is asked to enter 2 numbers after that the
user is asked to enter the operator based on which arithmetic operation is performed
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Error! Division by zero."
else:
return x / y
def main():
try:
# Take input from the user for the first number
num1 = float(input("Enter the first number: "))
# Take input from the user for the second number
num2 = float(input("Enter the second number: "))
# Take input from the user for the operator
operator = input("Enter the operator (+, -, *, /): ")
# Perform the calculation based on the operator
if operator == '+':
result = add(num1, num2)
elif operator == '-':
Mahesh Singh Parihar BCA section-B Roll No-2271176
result = subtract(num1, num2)
elif operator == '*':
result = multiply(num1, num2)
elif operator == '/':
result = divide(num1, num2)
else:
result = "Invalid operator entered."
# Print the result
print("Result:", result)
except ValueError:
print("Please enter valid numeric values for the numbers.")
except Exception as e:
print("An error occurred:", str(e))
if __name__ == "__main__":
main()
OUTPUT :
Enter the first number: 10
Enter the second number: 5
Enter the operator (+, -, *, /): +
Result: 15.0
Ques 11: Write a program to check whether the character enter by the user is in upper case or in
lower case
def check_case(char):
if char.islower():
return "Lowercase"
elif char.isupper():
return "Uppercase"
else:
return "Not an alphabet"
def main():
Mahesh Singh Parihar BCA section-B Roll No-2271176
try:
# Take input from the user
char = input("Enter a character: ")
# Check the case of the character
case = check_case(char)
# Print the result
print("The character '{}' is in {}.".format(char, case))
except Exception as e:
print("An error occurred:", str(e))
if __name__ == "__main__":
main()
OUTPUT :
Enter a character: a
The character 'a' is in Lowercase.
Ques 12: Write a program that ask user to enter the number and if the entered number is greater
that or equal to 100 check the number is even or odd if number is less that 100 it will not check the
number is even or not it will only print the message that the number is less 100
def check_even_odd(number):
if number % 2 == 0:
return "even"
else:
return "odd"
def main():
try:
# Take input from the user
number = int(input("Enter a number: "))
# Check if the number is greater than or equal to 100
if number >= 100:
# Check if the number is even or odd
Mahesh Singh Parihar BCA section-B Roll No-2271176
result = check_even_odd(number)
print("The number {} is greater than or equal to 100 and it is {}.".format(number, result))
else:
print("The number {} is less than 100.".format(number))
except ValueError:
print("Please enter a valid integer.")
if __name__ == "__main__":
main()
OUTPUT :
Enter a number: 103
The number 103 is greater than or equal to 100 and it is odd.
Ques 13: Write a program to check whether the given year is leap or not
def is_leap_year(year):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
def main():
try:
# Take input from the user
year = int(input("Enter a year: "))
# Check if the year is a leap year
if is_leap_year(year):
print("{} is a leap year.".format(year))
else:
print("{} is not a leap year.".format(year))
except ValueError:
print("Please enter a valid integer.")
Mahesh Singh Parihar BCA section-B Roll No-2271176
if __name__ == "__main__":
main()
OUTPUT :
Enter a year: 2024
2024 is a leap year.
Ques 14: write a program to print even numbers upto n using while loop
def print_even_numbers(n):
i=2
while i <= n:
print(i, end=" ")
i += 2
def main():
try:
# Take input from the user for the value of n
n = int(input("Enter the value of n: "))
# Print even numbers up to n
print("Even numbers up to {}:".format(n))
print_even_numbers(n)
except ValueError:
print("Please enter a valid integer.")
if __name__ == "__main__":
main()
OUTPUT :
Enter the value of n: 100
Even numbers up to 100:
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76
78 80 82 84 86 88 90 92 94 96 98 100
Ques 15: wap to find the sum of the two matrixes using for loop
def add_matrices(matrix1, matrix2):
if len(matrix1) != len(matrix2) or len(matrix1[0]) != len(matrix2[0]):
Mahesh Singh Parihar BCA section-B Roll No-2271176
return "Matrices are not of the same size"
result = []
for i in range(len(matrix1)):
row = []
for j in range(len(matrix1[0])):
row.append(matrix1[i][j] + matrix2[i][j])
result.append(row)
return result
def main():
try:
# Take input for the dimensions of the matrices
rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))
# Take input for the elements of the first matrix
print("Enter elements of the first matrix:")
matrix1 = [[int(input("Enter element [{},{}]: ".format(i, j))) for j in range(cols)] for i in
range(rows)]
# Take input for the elements of the second matrix
print("Enter elements of the second matrix:")
matrix2 = [[int(input("Enter element [{},{}]: ".format(i, j))) for j in range(cols)] for i in
range(rows)]
# Calculate the sum of the matrices
result = add_matrices(matrix1, matrix2)
# Print the result
if isinstance(result, str):
print(result)
else:
print("Sum of the matrices:")
Mahesh Singh Parihar BCA section-B Roll No-2271176
for row in result:
print(row)
except ValueError:
print("Please enter valid integer values for the matrix elements.")
if __name__ == "__main__":
main()
OUTPUT :
Enter the number of rows: 2
Enter the number of columns: 2
Enter elements of the first matrix:
Enter element [0,0]: 1
Enter element [0,1]: 2
Enter element [1,0]: 3
Enter element [1,1]: 4
Enter elements of the second matrix:
Enter element [0,0]: 5
Enter element [0,1]: 6
Enter element [1,0]: 7
Enter element [1,1]: 8
Sum of the matrices:
[6, 8]
[10, 12]
Ques 16: wap to find the sum of n natural numbers using while loop and for loop and should be
entered by the user
def sum_of_natural_numbers_while(n):
sum = 0
i=1
while i <= n:
sum += i
i += 1
return sum
def main_while():
try:
n = int(input("Enter the value of n: "))
if n < 1:
Mahesh Singh Parihar BCA section-B Roll No-2271176
print("Please enter a positive integer.")
return
result = sum_of_natural_numbers_while(n)
print("Sum of the first {} natural numbers using while loop: {}".format(n, result))
except ValueError:
print("Please enter a valid integer.")
if __name__ == "__main__":
main_while()
OUTPUT :
Enter the value of n: 10
Sum of the first 10 natural numbers using while loop: 55
def sum_of_natural_numbers_for(n):
sum = 0
for i in range(1, n + 1):
sum += i
return sum
def main_for():
try:
n = int(input("Enter the value of n: "))
if n < 1:
print("Please enter a positive integer.")
return
result = sum_of_natural_numbers_for(n)
print("Sum of the first {} natural numbers using for loop: {}".format(n, result))
except ValueError:
print("Please enter a valid integer.")
if __name__ == "__main__":
main_for()
Mahesh Singh Parihar BCA section-B Roll No-2271176
OUTPUT :
Enter the value of n: 10
Sum of the first 10 natural numbers using for loop: 55
Ques 17: print the pattern
22
333
4444
55555
def print_pattern(rows):
for i in range(1, rows + 1):
print(str(i) * i)
def main():
try:
rows = int(input("Enter the number of rows: "))
print("Pattern:")
print_pattern(rows)
except ValueError:
print("Please enter a valid integer.")
if __name__ == "__main__":
main()
OUTPUT :
Enter the number of rows: 5
Pattern:
1
22
333
4444
55555
Ques 18: wap to calculate the power of the number using the anonymous function
# Define an anonymous function to calculate the power of a number
Mahesh Singh Parihar BCA section-B Roll No-2271176
power = lambda base, exponent: base ** exponent
def main():
try:
# Take input from the user for the base and exponent
base = float(input("Enter the base number: "))
exponent = float(input("Enter the exponent: "))
# Calculate the power using the anonymous function
result = power(base, exponent)
# Print the result
print("Result:", result)
except ValueError:
print("Please enter valid numeric values for the base and exponent.")
if __name__ == "__main__":
main()
OUTPUT :
Enter the base number: 2
Enter the exponent: 3
Result: 8.0
Ques 19: wap to create basic calculator using module
# Define functions for basic arithmetic operations
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Error! Division by zero."
Mahesh Singh Parihar BCA section-B Roll No-2271176
else:
return x / y
def main():
try:
# Take input from the user for two numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Display the menu of operations
print("\nOperations:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
# Take input from the user for the choice of operation
choice = input("Enter the operation (1/2/3/4): ")
# Perform the selected operation and display the result
if choice == '1':
print("Result:", add(num1, num2))
elif choice == '2':
print("Result:", subtract(num1, num2))
elif choice == '3':
print("Result:", multiply(num1, num2))
elif choice == '4':
print("Result:", divide(num1, num2))
else:
print("Invalid choice. Please enter a valid operation.")
except ValueError:
Mahesh Singh Parihar BCA section-B Roll No-2271176
print("Please enter valid numeric values.")
if __name__ == "__main__":
main()
OUTPUT :
Enter the first number: 20
Enter the second number: 2
Operations:
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter the operation (1/2/3/4): 3
Result: 40.0
Ques 20: create a txt file intern.txt and ask the user to write a single line of text by user input
def main():
try:
# Open the file in write mode ('w')
with open("intern.txt", "w") as file:
# Ask the user to write a single line of text
line = input("Write a single line of text: ")
# Write the user's input to the file
file.write(line)
print("Text has been written to 'intern.txt'.")
except Exception as e:
print("An error occurred:", str(e))
if __name__ == "__main__":
main()
OUTPUT :
Write a single line of text: HELLO THIS IS A TEXT PAGE
Text has been written to 'intern.txt'.
Ques 21: create a txt file myfile.txt and ask the user to write separate 3 lines with 3 inputs
statements from the user
def main():
Mahesh Singh Parihar BCA section-B Roll No-2271176
try:
# Open the file in write mode ('w')
with open("myfile.txt", "w") as file:
# Ask the user to write three separate lines
for i in range(3):
line = input("Enter line {}: ".format(i + 1))
file.write(line + "\n")
print("Three lines have been written to 'myfile.txt'.")
except Exception as e:
print("An error occurred:", str(e))
if __name__ == "__main__":
main()
OUTPUT :
Enter line 1: Hello, this is line 1.
Enter line 2: This is line 2.
Enter line 3: This is line 3.
Three lines have been written to 'myfile.txt'.
Ques 22: wap to read the content of both the file created in above program and merge the content
intol merge.txt
def merge_files():
try:
# Open the first file (intern.txt) in read mode ('r')
with open("intern.txt", "r") as file1:
# Read the contents of the first file
content1 = file1.read()
# Open the second file (myfile.txt) in read mode ('r')
with open("myfile.txt", "r") as file2:
# Read the contents of the second file
content2 = file2.read()
# Merge the contents of both files
Mahesh Singh Parihar BCA section-B Roll No-2271176
merged_content = content1 + "\n" + content2
# Write the merged content to a new file (merge.txt)
with open("merge.txt", "w") as merge_file:
merge_file.write(merged_content)
print("Contents of both files have been merged into 'merge.txt'.")
except Exception as e:
print("An error occurred:", str(e))
if __name__ == "__main__":
merge_files()
OUTPUT :
Contents of both files have been merged into 'merge.txt'.
Ques 23: count the total number of uppercase and lowercase and digit used in merge.txt
def count_characters(filename):
try:
# Open the file in read mode ('r')
with open(filename, "r") as file:
# Read the contents of the file
content = file.read()
# Initialize counters
uppercase_count = 0
lowercase_count = 0
digit_count = 0
# Iterate through each character in the content
for char in content:
if char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1
Mahesh Singh Parihar BCA section-B Roll No-2271176
elif char.isdigit():
digit_count += 1
print("Total number of uppercase letters:", uppercase_count)
print("Total number of lowercase letters:", lowercase_count)
print("Total number of digits:", digit_count)
except Exception as e:
print("An error occurred:", str(e))
if __name__ == "__main__":
count_characters("merge.txt")
OUTPUT :
Total number of uppercase letters: 23
Total number of lowercase letters: 32
Total number of digits: 3
Ques 24: wap to find a given number is prime or not
def is_prime(number):
if number <= 1:
return False
elif number <= 3:
return True
elif number % 2 == 0 or number % 3 == 0:
return False
i=5
while i * i <= number:
if number % i == 0 or number % (i + 2) == 0:
return False
i += 6
return True
def main():
try:
Mahesh Singh Parihar BCA section-B Roll No-2271176
num = int(input("Enter a number: "))
# Check if the number is prime
if is_prime(num):
print(num, "is a prime number.")
else:
print(num, "is not a prime number.")
except ValueError:
print("Please enter a valid integer.")
if __name__ == "__main__":
main()
OUTPUT :
Enter a number: 23
23 is a prime number.
Ques 25: develop a python program to print all the prime numbers within a range of numbers
def is_prime(number):
if number <= 1:
return False
elif number <= 3:
return True
elif number % 2 == 0 or number % 3 == 0:
return False
i=5
while i * i <= number:
if number % i == 0 or number % (i + 2) == 0:
return False
i += 6
return True
def print_primes(start, end):
Mahesh Singh Parihar BCA section-B Roll No-2271176
print("Prime numbers between", start, "and", end, "are:")
for num in range(start, end + 1):
if is_prime(num):
print(num, end=" ")
def main():
try:
# Take input from the user for the range of numbers
start = int(input("Enter the start of the range: "))
end = int(input("Enter the end of the range: "))
# Print prime numbers within the range
print_primes(start, end)
except ValueError:
print("Please enter valid integers for the range.")
if __name__ == "__main__":
main()
OUTPUT :
Enter the start of the range: 1
Enter the end of the range: 50
Prime numbers between 1 and 50 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Ques 26:develop a python program to find the largest and smallest number in the list
def find_largest_and_smallest(numbers):
if not numbers:
return None, None
largest = numbers[0]
smallest = numbers[0]
for number in numbers:
if number > largest:
largest = number
Mahesh Singh Parihar BCA section-B Roll No-2271176
if number < smallest:
smallest = number
return largest, smallest
def main():
try:
input_list = input("Enter a list of numbers separated by spaces: ")
numbers = list(map(int, input_list.split()))
largest, smallest = find_largest_and_smallest(numbers)
if largest is not None and smallest is not None:
print("Largest number in the list is:", largest)
print("Smallest number in the list is:", smallest)
else:
print("The list is empty.")
except ValueError:
print("Please enter a valid list of integers.")
if __name__ == "__main__":
main()
OUTPUT :
Enter a list of numbers separated by spaces: 10 20 50 30 40
Largest number in the list is: 50
Smallest number in the list is: 10
Ques 27: develop a python program to develop a calculator and perform the basic calculation based
on the user input and menu should be continuity available
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
Mahesh Singh Parihar BCA section-B Roll No-2271176
def divide(x, y):
if y == 0:
return "Error! Division by zero."
else:
return x / y
def menu():
print("\nSelect operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Exit")
def main():
while True:
menu()
try:
choice = input("Enter choice (1/2/3/4/5): ")
if choice == '5':
print("Exiting the calculator. Goodbye!")
break
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(f"The result of addition is: {add(num1, num2)}")
elif choice == '2':
print(f"The result of subtraction is: {subtract(num1, num2)}")
Mahesh Singh Parihar BCA section-B Roll No-2271176
elif choice == '3':
print(f"The result of multiplication is: {multiply(num1, num2)}")
elif choice == '4':
print(f"The result of division is: {divide(num1, num2)}")
else:
print("Invalid Input. Please choose a valid operation.")
except ValueError:
print("Invalid input. Please enter numeric values.")
if __name__ == "__main__":
main()
OUTPUT :
Select operation:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter choice (1/2/3/4/5): 1
Enter first number: 2
Enter second number: 3
The result of addition is: 5.0
Select operation:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter choice (1/2/3/4/5): 2
Enter first number: 5
Enter second number: 3
The result of subtraction is: 2.0
Select operation:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter choice (1/2/3/4/5): 5
Exiting the calculator. Goodbye!
Ques 28: wap to show all the arguments of a function
def show_arguments(*args, **kwargs):
Mahesh Singh Parihar BCA section-B Roll No-2271176
# Display positional arguments
print("Positional arguments:")
for i, arg in enumerate(args):
print(f"arg{i + 1}: {arg}")
# Display keyword arguments
print("\nKeyword arguments:")
for key, value in kwargs.items():
print(f"{key}: {value}")
def main():
# Example usage of the function with different arguments
show_arguments(1, "hello", True, name="Alice", age=30, city="Wonderland")
if __name__ == "__main__":
main()
OUTPUT :
Positional arguments:
arg1: 1
arg2: hello
arg3: True
Keyword arguments:
name: Alice
age: 30
city: Wonderland
[ ]:
Ques 29: wap to create a function for simple calculator
def simple_calculator(num1, num2, operator):
if operator == '+':
return num1 + num2
elif operator == '-':
return num1 - num2
elif operator == '*':
return num1 * num2
Mahesh Singh Parihar BCA section-B Roll No-2271176
elif operator == '/':
if num2 == 0:
return "Error! Division by zero."
else:
return num1 / num2
else:
return "Invalid operator!"
def main():
while True:
try:
# Take input from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
operator = input("Enter an operator (+, -, *, /): ")
# Calculate the result using the simple_calculator function
result = simple_calculator(num1, num2, operator)
# Print the result
print(f"The result is: {result}")
# Ask the user if they want to perform another calculation
again = input("Do you want to perform another calculation? (yes/no): ").strip().lower()
if again != 'yes':
print("Exiting the calculator. Goodbye!")
break
except ValueError:
print("Invalid input. Please enter numeric values for the numbers.")
if __name__ == "__main__":
main()
Mahesh Singh Parihar BCA section-B Roll No-2271176
OUTPUT :
Enter the first number: 10
Enter the second number: 5
Enter an operator (+, -, *, /): *
The result is: 50.0
Do you want to perform another calculation? (yes/no): YES
Enter the first number: 10
Enter the second number: 5
Enter an operator (+, -, *, /): -
The result is: 5.0
Do you want to perform another calculation? (yes/no): no
Exiting the calculator. Goodbye!
Ques 30: wap to find the middle element of the string passed and id middle element is not therir
than return nothing
def find_middle_element(s):
length = len(s)
# Check if the length of the string is odd
if length % 2 != 0:
middle_index = length // 2
return s[middle_index]
else:
return "Nothing"
def main():
# Take input from the user
user_input = input("Enter a string: ")
# Find the middle element
result = find_middle_element(user_input)
# Print the result
print("The middle element is:", result)
if __name__ == "__main__":
main()
OUTPUT :
Enter a string: Hello
The middle element is: l
Mahesh Singh Parihar BCA section-B Roll No-2271176
Ques 31: wap by define a function to calculate mean median of array of the number
def calculate_mean(numbers):
if not numbers:
return None # Return None if the list is empty
return sum(numbers) / len(numbers)
def calculate_median(numbers):
if not numbers:
return None # Return None if the list is empty
sorted_numbers = sorted(numbers)
length = len(sorted_numbers)
middle_index = length // 2
if length % 2 == 0:
# If even, return the average of the middle two elements
median = (sorted_numbers[middle_index - 1] + sorted_numbers[middle_index]) / 2
else:
# If odd, return the middle element
median = sorted_numbers[middle_index]
return median
def main():
try:
# Take input from the user for the list of numbers
input_list = input("Enter a list of numbers separated by spaces: ")
numbers = list(map(float, input_list.split()))
# Calculate mean and median
mean = calculate_mean(numbers)
median = calculate_median(numbers)
# Print the results
Mahesh Singh Parihar BCA section-B Roll No-2271176
if mean is not None and median is not None:
print(f"The mean of the numbers is: {mean}")
print(f"The median of the numbers is: {median}")
else:
print("The list is empty.")
except ValueError:
print("Please enter a valid list of numbers.")
if __name__ == "__main__":
main()
OUTPUT :
Enter a list of numbers separated by spaces: 1 2 3 4 5
The mean of the numbers is: 3.0
The median of the numbers is: 3.0
Ques 32: wap to change the string to the new string where the first and the last character has been
existed
def swap_first_last_characters(s):
# Check if the string is empty or has only one character
if len(s) <= 1:
return s
# Swap the first and last characters
new_string = s[-1] + s[1:-1] + s[0]
return new_string
def main():
# Take input from the user
user_input = input("Enter a string: ")
# Get the new string with the first and last characters swapped
result = swap_first_last_characters(user_input)
# Print the result
print("The new string is:", result)
Mahesh Singh Parihar BCA section-B Roll No-2271176
if __name__ == "__main__":
main()
OUTPUT :
Enter a string: HELLO
The new string is: OELLH
Ques 33:create a function to print the length of the string
def print_string_length(s):
# Calculate the length of the string
length = len(s)
# Print the length of the string
print(f"The length of the string is: {length}")
def main():
# Take input from the user
user_input = input("Enter a string: ")
# Call the function to print the length of the string
print_string_length(user_input)
if __name__ == "__main__":
main()
OUTPUT :
Enter a string: HELLO
The length of the string is: 5
Ques 34: create a function to print the square of the number using the function
def print_square_of_number(n):
# Calculate the square of the number
square = n * n
# Print the square of the number
print(f"The square of {n} is: {square}")
def main():
try:
Mahesh Singh Parihar BCA section-B Roll No-2271176
# Take input from the user
user_input = float(input("Enter a number: "))
# Call the function to print the square of the number
print_square_of_number(user_input)
except ValueError:
print("Invalid input. Please enter a valid number.")
if __name__ == "__main__":
main()
OUTPUT :
Enter a number: 5
The square of 5.0 is: 25.0
Ques 35: write a function to take name as a function as input
def print_name():
# Take name input from the user
name = input("Enter your name: ")
# Print the name
print(f"Hello, {name}!")
def main():
# Call the function to take name input and print it
print_name()
if __name__ == "__main__":
main()
OUTPUT :
Enter your name: SAURABH
Hello, SAURABH!
Ques 36: wap to find the factorial of a no
def factorial(n):
if n < 0:
return "Factorial is not defined for negative numbers."
Mahesh Singh Parihar BCA section-B Roll No-2271176
elif n == 0 or n == 1:
return 1
else:
result = 1
for i in range(2, n + 1):
result *= i
return result
def main():
try:
# Take input from the user
user_input = int(input("Enter a number to find its factorial: "))
# Calculate the factorial using the factorial function
result = factorial(user_input)
# Print the result
print(f"The factorial of {user_input} is: {result}")
except ValueError:
print("Invalid input. Please enter a valid integer.")
if __name__ == "__main__":
main()
OUTPUT :
Enter a number to find its factorial: 5
The factorial of 5 is: 120
Ques 37:write a pandas program to create and display array using pandas model
import pandas as pd
import numpy as np
def create_and_display_array():
# Create a NumPy array
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
Mahesh Singh Parihar BCA section-B Roll No-2271176
# Create a DataFrame from the NumPy array
df = pd.DataFrame(data, columns=['Column1', 'Column2', 'Column3'])
# Display the DataFrame
print("DataFrame created from NumPy array:")
print(df)
def main():
create_and_display_array()
if __name__ == "__main__":
main()
OUTPUT :
DataFrame created from NumPy array:
Column1 Column2 Column3
0 1 2 3
1 4 5 6
2 7 8 9
Ques 38: wap to convert pandas series to python list
import pandas as pd
def convert_series_to_list():
# Create a Pandas Series
data = pd.Series([10, 20, 30, 40, 50])
# Convert the Pandas Series to a Python list
data_list = data.tolist()
# Display the original Series and the converted list
print("Original Pandas Series:")
print(data)
print("\nConverted Python list:")
print(data_list)
def main():
convert_series_to_list()
Mahesh Singh Parihar BCA section-B Roll No-2271176
if __name__ == "__main__":
main()
OUTPUT :
Original Pandas Series:
0 10
1 20
2 30
3 40
4 50
dtype: int64
Converted Python list:
[10, 20, 30, 40, 50]
Ques 39: wap to add,sub,mul and div of 2 series
import pandas as pd
def perform_operations(series1, series2):
addition = series1 + series2
subtraction = series1 - series2
multiplication = series1 * series2
division = series1 / series2
print("Series 1:")
print(series1)
print("\nSeries 2:")
print(series2)
print("\nAddition of Series:")
print(addition)
print("\nSubtraction of Series:")
print(subtraction)
print("\nMultiplication of Series:")
print(multiplication)
print("\nDivision of Series:")
print(division)
Mahesh Singh Parihar BCA section-B Roll No-2271176
def main():
series1 = pd.Series([10, 20, 30, 40, 50])
series2 = pd.Series([5, 4, 3, 2, 1])
perform_operations(series1, series2)
if __name__ == "__main__":
main()
OUTPUT :
Series 1:
0 10
1 20
2 30
3 40
4 50
dtype: int64
Series 2:
0 5
1 4
2 3
3 2
4 1
dtype: int64
Addition of Series:
0 15
1 24
2 33
3 42
4 51
dtype: int64
Subtraction of Series:
0 5
1 16
2 27
3 38
4 49
dtype: int64
Multiplication of Series:
0 50
1 80
2 90
3 80
4 50
dtype: int64
Division of Series:
0 2.0
Mahesh Singh Parihar BCA section-B Roll No-2271176
1 5.0
2 10.0
3 20.0
4 50.0
dtype: float64
Ques 40: program to convert numpy array to pandas series
import numpy as np
import pandas as pd
def convert_array_to_series(array):
series = pd.Series(array)
print("Original NumPy array:")
print(array)
print("\nConverted Pandas Series:")
print(series)
def main():
array = np.array([10, 20, 30, 40, 50])
convert_array_to_series(array)
if __name__ == "__main__":
main()
OUTPUT :
Original NumPy array:
[10 20 30 40 50]
Converted Pandas Series:
0 10
1 20
2 30
3 40
4 50
dtype: int32
Ques 41: wap to create a display a dataframe from dic which has index label
import pandas as pd
# Example dictionary
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
Mahesh Singh Parihar BCA section-B Roll No-2271176
index_labels = ['Person1', 'Person2', 'Person3']
df = pd.DataFrame(data, index=index_labels)
print(df)
Output:
Name Age City
Person1 Alice 25 New York
Person2 Bob 30 Los Angeles
Person3 Charlie 35 Chicago
Ques 42: Using the dirtydata csv fix the bad data set( bad data could be : empty cell ,data in wrong
format ,duplicate data and wrong data)
import pandas as pd
df = pd.read_csv('dirtydata.csv')
# Display the initial DataFrame
print("Initial DataFrame:")
print(df)
df.dropna(inplace=True)
df['date_column'] = pd.to_datetime(df['date_column'], errors='coerce')
df['numeric_column'] = pd.to_numeric(df['numeric_column'], errors='coerce')
df.drop_duplicates(inplace=True)
df['age'] = df['age'].apply(lambda x: df['age'].mean() if x < 0 else x)
df.loc[df['score'] > 100, 'score'] = 100 # assuming scores should be between 0 and 100
print("Cleaned DataFrame:")
print(df)
df.to_csv('cleaneddata.csv', index=False)
Ques 44:using pandas remove the duplicate data (file used for the operation is dirtydata.csv)
import pandas as pd
df = pd.read_csv('dirtydata.csv')
print("Initial DataFrame:")
print(df)
df.drop_duplicates(inplace=True)
print("DataFrame after removing duplicates:")
Mahesh Singh Parihar BCA section-B Roll No-2271176
print(df)
df.to_csv('cleaneddata.csv', index=False)
ques 45: wap to find the sum of all elements in a list
numbers = [1, 2, 3, 4, 5]
total_sum = sum(numbers)
print("The sum of all elements in the list is:", total_sum)
Ques 46: wap to remove the duplicate from a list
numbers = [1, 2, 3, 4, 5, 2, 3, 1]
unique_numbers = list(set(numbers))
print("List after removing duplicates (order not preserved):", unique_numbers)
Ques 47: create a program to reverse a li8st without using build in function
numbers = [1, 2, 3, 4, 5]
reversed_numbers = []
for i in range(len(numbers) - 1, -1, -1):
reversed_numbers.append(numbers[i])
print("Reversed list:", reversed_numbers)
Ques 48: wap to find the max and min elements in the list
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
if len(numbers) == 0:
raise ValueError("The list is empty, cannot find maximum and minimum values.")
max_element = numbers[0]
min_element = numbers[0]
for num in numbers:
if num > max_element:
max_element = num
if num < min_element:
min_element = num
Mahesh Singh Parihar BCA section-B Roll No-2271176
print("The maximum element in the list is:", max_element)
print("The minimum element in the list is:", min_element)
Ques 49: implement a program to sort the list of integer in asc order without using build in function
numbers = [64, 34, 25, 12, 22, 11, 90]
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
bubble_sort(numbers)
Ques 50:wap a python program to find the length of the tuple
my_tuple = (10, 20, 30, 40, 50)
length = len(my_tuple)
print("The length of the tuple is:", length)
Ques 51: implement a function to concatenate the two tuples
def concatenate_tuples(tuple1, tuple2):
concatenated_tuple = tuple1 + tuple2
return concatenated_tuple
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
result_tuple = concatenate_tuples(tuple1, tuple2)
print("Concatenated tuple:", result_tuple)
Ques 52: wap to find the index of an element in the tuple
def find_index(tuple, element):
for i in range(len(tuple)):
if tuple[i] == element:
Mahesh Singh Parihar BCA section-B Roll No-2271176
return i
return -1
my_tuple = (10, 20, 30, 40, 50)
element_to_find = 30
index = find_index(my_tuple, element_to_find)
if index != -1:
print("Index of", element_to_find, "in the tuple is:", index)
else:
print("Element", element_to_find, "not found in the tuple.")
Ques 53: create a program to count the occurrence of an element in the tuple
def count_occurrence(tuple, element):
count = 0
for item in tuple:
if item == element:
count += 1
return count
my_tuple = (1, 2, 3, 1, 4, 1, 5)
element_to_count = 1
occurrence_count = count_occurrence(my_tuple, element_to_count)
print("The occurrence count of", element_to_count, "in the tuple is:", occurrence_count)
Ques 54: write a function to check if two tuples have any element in common
def have_common_element(tuple1, tuple2):
for element in tuple1:
if element in tuple2:
return True
return False
tuple1 = (1, 2, 3, 4, 5)
Mahesh Singh Parihar BCA section-B Roll No-2271176
tuple2 = (6, 7, 8, 9, 10)
if have_common_element(tuple1, tuple2):
print("The tuples have at least one common element.")
else:
print("The tuples do not have any common element.")
Ques 55: wap to illiterate over a dic and print key values pair
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
for key in my_dict:
print(key, ":", my_dict[key])
Ques 56: implement a function to merge two dic
def merge_dicts(dict1, dict2):
merged_dict = dict1.copy() # Make a copy of the first dictionary
merged_dict.update(dict2) # Update the copy with the second dictionary
return merged_dict
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = merge_dicts(dict1, dict2)
print("Merged dictionary:", merged_dict)
Ques 57: wap to find the keys corresponding to the max and min value in the dic
def find_max_min_keys(dictionary):
if not dictionary:
return None, None
max_key, min_key = None, None
max_value = float('-inf') # Initialize to negative infinity
min_value = float('inf') # Initialize to positive infinity
for key, value in dictionary.items():
if value > max_value:
Mahesh Singh Parihar BCA section-B Roll No-2271176
max_value = value
max_key = key
if value < min_value:
min_value = value
min_key = key
return max_key, min_key
my_dict = {'a': 10, 'b': 20, 'c': 5, 'd': 15}
max_key, min_key = find_max_min_keys(my_dict)
print("Key corresponding to the maximum value:", max_key)
print("Key corresponding to the minimum value:", min_key)
Ques 58: create a function to check if a key exists in the dic
def key_exists(dictionary, key):
return key in dictionary
my_dict = {'a': 10, 'b': 20, 'c': 30}
key_to_check = 'b'
if key_exists(my_dict, key_to_check):
print("Key", key_to_check, "exists in the dictionary.")
else:
print("Key", key_to_check, "does not exist in the dictionary.")
Ques 59: wap to sort a dic by its value in asc order
def sort_dict_by_value_asc(dictionary):
sorted_dict = dict(sorted(dictionary.items(), key=lambda item: item[1]))
return sorted_dict
my_dict = {'a': 10, 'b': 5, 'c': 20, 'd': 15}
sorted_dict = sort_dict_by_value_asc(my_dict)
print("Sorted dictionary by value in ascending order:", sorted_dict)
Ques 60: wap to create a set and perform basic set operation (union, intersection and difference)
Mahesh Singh Parihar BCA section-B Roll No-2271176
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print("Set 1:", set1)
print("Set 2:", set2)
union_set = set1.union(set2)
print("Union of set 1 and set 2:", union_set)
intersection_set = set1.intersection(set2)
print("Intersection of set 1 and set 2:", intersection_set)
difference_set1 = set1.difference(set2)
print("Difference of set 1 and set 2:", difference_set1)
difference_set2 = set2.difference(set1)
print("Difference of set 2 and set 1:", difference_set2)
Ques 62: wap to check if two sets have any elements in common
def have_common_elements(set1, set2):
return len(set1.intersection(set2)) > 0
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Check if the sets have any common elements using the have_common_elements function
if have_common_elements(set1, set2):
print("The sets have common elements”)
Ques 63: draw pattern:
n=int (input("Enter the number of rows:"))
for i in range(1,n+1):
print(" "*(n-i),end="")
Mahesh Singh Parihar BCA section-B Roll No-2271176
for j in range(1,i+1):
print(chr(64+j),end=" ")
print()
Ques 64: draw pattern:
num=int(input("Enter the number of rows: "))
for i in range(1,num+1):
print(" "*(i-1),end="")
for j in range(1,num+2-i):
print(chr(65+num-i),end=" ")
for k in range(2,num+2-i):
print(chr(65+num-i),end=" ")
print()
Ques 65: draw pattern :
num=int(input("Enter a number:"))
for i in range(1,num+1):
print(" "*(num-i),end="")
for j in range(1,i+1):
print(num-j,end=" ")
Mahesh Singh Parihar BCA section-B Roll No-2271176
print()
for k in range(1,num):
print(" "*k,end="")
for l in range(1,num+1-k):
print(num-1,end=" ")
print()
Ques 66: draw pattern :
num=int(input("Enter a number:"))
for i in range(1,num+1):
for j in range(1,i+1):
print(num-i+j-1,end="")
print()
for a in range(1,num+1):
for k in range(0,num-a):
print(k+a,end="")
print()
Ques 67: draw pattern :
Mahesh Singh Parihar BCA section-B Roll No-2271176
num=int(input("Enter a number:"))
for i in range(1,num+1):
print(" "*(num-i),end="")
for j in range(0,i):
print(chr(65+num+j-i),end=" ")
print()
for k in range(1,num):
print(" "*k,end="")
for l in range(0,num-k):
print(chr(65+k+1),end=" ")
print()
Ques 68: draw pattern :
num=int(input("Enter a number:"))
for i in range(1,num+1):
print(" "*(num-i),end="")
for j in range(1,i+1):
print("*",end=" ")
print(" "*(num-i),end="")
for k in range(1,i+1):
print("*",end=" ")
print()
Mahesh Singh Parihar BCA section-B Roll No-2271176