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

Anjali Python Practical File

Uploaded by

imkauramrit
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)
18 views

Anjali Python Practical File

Uploaded by

imkauramrit
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/ 35

Practical File

Class XII - Computer Science with Python(083)


Program 1: Program to enter two numbers and print the arithmetic operations like +,-,*,
/, // and %.

Solution:

OUTPUT :
Program 2: Write a program to find whether an inputted number is perfect or not.

Solution:

# Function to check if a number is perfect


def is_perfect(number):
# Initialize the sum of divisors
sum_of_divisors = 0

# Find all divisors of the number


for i in range(1, number):
if number % i == 0:
sum_of_divisors += i

# Check if the sum of divisors equals the number


if sum_of_divisors == number:
return True
else:
return False

# Input a number from the user


num = int(input("Enter a number: "))

# Check if the number is perfect and print the result


if is_perfect(num):
print(f"{num} is a perfect number!")
else:
print(f"{num} is not a perfect number.")

OUTPUT:
Program 3: Write a Program to check if the entered number is Armstrong or not.

Solution:

# Function to check if a number is an Armstrong number


def is_armstrong(number):
# Convert the number to a string to easily iterate over digits
num_str = str(number)
num_digits = len(num_str)

# Calculate the sum of each digit raised to the power of the number of digits
sum_of_powers = sum(int(digit) ** num_digits for digit in num_str)

# Check if the sum of powers is equal to the original number


return sum_of_powers == number

# Input a number from the user


num = int(input("Enter a number: "))

# Check if the number is an Armstrong number and print the result


if is_armstrong(num):
print(f"{num} is an Armstrong number!")
else:
print(f"{num} is not an Armstrong number.")

OUTPUT:
Program 4: Write a Program to find factorial of the entered number.

Solution:

# Function to calculate the factorial of a number


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

# Input a number from the user


num = int(input("Enter a number: "))

# Check if the number is non-negative


if num < 0:
print("Factorial is not defined for negative numbers.")
else:
# Calculate and print the factorial
result = factorial(num)
print(f"The factorial of {num} is {result}.")

OUTPUT :
Program 5: Write a Program to enter the number of terms and to print the Fibonacci
Series.

Solution:

# Function to generate and print the Fibonacci Series

def fibonacci_series(n):

# Initialize the first two terms

a, b = 0, 1

count = 0

# Print Fibonacci series up to n terms

while count < n:

print(a, end=" ")

# Update the values of a and b

a, b = b, a + b

count += 1

# Input the number of terms from the user

num_terms = int(input("Enter the number of terms: "))

# Check if the number of terms is valid

if num_terms <= 0:

print("Please enter a positive integer.")

else:

print("Fibonacci Series:")

fibonacci_series(num_terms)

OUTPUT:
Program 6: Write a Program to enter the string and to check if it’s palindrome or not using loop.

Solution :
# Function to check if a string is a palindrome
def is_palindrome(s):
# Initialize pointers at the start and end of the string
left = 0
right = len(s) - 1

# Loop to compare characters from both ends


while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True

# Input a string from the user


string = input("Enter a string: ")

# Check if the string is a palindrome and print the result


if is_palindrome(string):
print(f'"{string}" is a palindrome!')
else:
print(f'"{string}" is not a palindrome.')

Output :
Program 7: Write a Program to show the outputs based on entered list.

Solution:
# Function to calculate various outputs based on the entered list
def list_operations(numbers):
# Calculate the sum of the numbers
total_sum = sum(numbers)

# Find the largest number


largest_number = max(numbers)

# Find the smallest number


smallest_number = min(numbers)

# Calculate the average of the numbers


average = total_sum / len(numbers) if numbers else 0

# Print the results


print("Sum of the numbers:", total_sum)
print("Largest number:", largest_number)
print("Smallest number:", smallest_number)
print("Average of the numbers:", average)

# Input the list of numbers from the user


numbers_input = input("Enter a list of numbers separated by spaces: ")
numbers_list = [float(num) for num in numbers_input.split()]

# Perform operations on the list and display the results


list_operations(numbers_list)

Output :
Program 8: Write a Program to enter the numbers in a list using split () and to use all the functions
related to list.

Solution:

# Function to demonstrate various list operations


def list_operations(numbers):
# Append a number to the list
numbers.append(100)
print("After appending 100:", numbers)

# Insert a number at a specific position


numbers.insert(1, 50)
print("After inserting 50 at index 1:", numbers)

# Remove a specific number from the list


numbers.remove(50)
print("After removing 50:", numbers)

# Pop a number from the list


popped_number = numbers.pop()
print(f"After popping the last number ({popped_number}):", numbers)

# Sort the list


numbers.sort()
print("After sorting:", numbers)

# Reverse the list


numbers.reverse()
print("After reversing:", numbers)

# Find the index of a specific number


if 100 in numbers:
index_of_100 = numbers.index(100)
print("Index of 100:", index_of_100)

# Count the occurrences of a specific number


count_of_100 = numbers.count(100)
print("Count of 100:", count_of_100)

# Copy the list


copied_list = numbers.copy()
print("Copied list:", copied_list)

# Clear the list


numbers.clear()
print("After clearing the list:", numbers)

# Input the list of numbers from the user


numbers_input = input("Enter a list of numbers separated by spaces: ")
numbers_list = [int(num) for num in numbers_input.split()]
# Perform operations on the list and display the results
list_operations(numbers_list)

Output :
Program 9: Write a Program to enter the number and print the Floyd’s Triangle in
decreasing order.

Solution:

# Function to print Floyd's Triangle in decreasing order


def floyds_triangle_decreasing(n):
# Calculate the total number of elements in the triangle
total_numbers = n * (n + 1) // 2

# Initialize the current number to the total number of elements


current_number = total_numbers

# Print the triangle row by row


for i in range(1, n + 1):
for j in range(i):
print(current_number, end=" ")
current_number -= 1
print()

# Input the number of rows for Floyd's Triangle


num_rows = int(input("Enter the number of rows: "))

# Print Floyd's Triangle in decreasing order


floyds_triangle_decreasing(num_rows)

Output :
Program 10: Write a Program to find factorial of entered number using user-defined modulefact().

Solution:

Step 1:
# fact_module.py

# Function to calculate the factorial of a number


def fact(n):
if n == 0 or n == 1:
return 1
else:
return n * fact(n - 1)
Step 2 :
# main_program.py

# Import the user-defined module


import fact_module

# Input a number from the user


num = int(input("Enter a number: "))

# Check if the number is non-negative


if num < 0:
print("Factorial is not defined for negative numbers.")
else:
# Calculate and print the factorial using the user-defined module
result = fact_module.fact(num)
print(f"The factorial of {num} is {result}.")

Output :
Program 11: Write a Program to enter the numbers and find Linear Search, Binary Search,
Lowest Number and Selection Sort using list/array code.

Solution:

def linear_search(arr, x):


for i in range(len(arr)):
if arr[i] == x:
return i
return -1

def binary_search(arr, x):


low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1

def find_lowest_number(arr):
if len(arr) == 0:
return None
lowest = arr[0]
for num in arr:
if num < lowest:
lowest = num
return lowest

def selection_sort(arr):
for i in range(len(arr)):
min_idx = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]

# Input the list of numbers from the user


numbers_input = input("Enter a list of numbers separated by spaces: ")
numbers_list = [int(num) for num in numbers_input.split()]

# Perform Linear Search


search_num = int(input("Enter the number to search (Linear Search): "))
linear_result = linear_search(numbers_list, search_num)
if linear_result != -1:
print(f"{search_num} found at index {linear_result} using Linear Search.")
else:
print(f"{search_num} not found using Linear Search.")

# Perform Binary Search (requires sorted list)


numbers_list_sorted = sorted(numbers_list)
print("Sorted list for Binary Search:", numbers_list_sorted)
search_num = int(input("Enter the number to search (Binary Search): "))
binary_result = binary_search(numbers_list_sorted, search_num)
if binary_result != -1:
print(f"{search_num} found at index {binary_result} in the sorted list using Binary Search.")
else:
print(f"{search_num} not found in the sorted list using Binary Search.")

# Find the Lowest Number


lowest_number = find_lowest_number(numbers_list)
print("Lowest number in the list:", lowest_number)

# Perform Selection Sort


selection_sort(numbers_list)
print("List after Selection Sort:", numbers_list)

Output :
Program 12: Write a Program to read data from data file and show Data File Handlingrelated
functions utility in python.

Solution:

# Function to read data

from a file

def read_file(file_path):

try:

with open(file_path,

'r') as file:

data = file.read()

print("Data read

from file:")

print(data)

except

FileNotFoundError:

print("File not

found.")

# Function to write data to

a file

def write_file(file_path,

data):

with open(file_path, 'w')

as file:
file.write(data)

print("Data written to

file.")

# Function to append data

to a file

def append_file(file_path,

data):

with open(file_path, 'a')

as file:

file.write(data)

print("Data appended

to file.")

# Function to read data

from a file line by line

def

read_file_by_line(file_pat

h):

try:

with open(file_path,

'r') as file:

print("Reading file
line by line:")

for line in file:

print(line,

end="")

except

FileNotFoundError:

print("File not

found.")

# Specify the file path

file_path = 'data.txt'

# Read data from the file

read_file(file_path)

# Write data to the file

write_data = "This is a new

content written to the

file.\n"

write_file(file_path,

write_data)
# Append data to the file

append_data = "This is

appended text.\n"

append_file(file_path,

append_data)

# Read data from the file

line by line

read_file_by_line(file_pat

h)

Output :
Program 13: Write a Program to read data from data file in append mode and usewriteLines
function utility in python.

Solution:

# Function to read data from a file


def read_file(file_path):
try:
with open(file_path, 'r') as file:
data = file.read()
print("Data read from file:")
print(data)
except FileNotFoundError:
print("File not found.")

# Function to append data to a file using writelines


def append_to_file(file_path, lines):
with open(file_path, 'a') as file:
file.writelines(lines)
print("Data appended to file.")

# Specify the file path


file_path = 'data.txt'

# Read initial data from the file


read_file(file_path)

# Lines to be appended to the file


lines_to_append = [
"This is the fourth line.\n",
"This is the fifth line.\n",
"This is the sixth line.\n"
]

# Append data to the file using writelines


append_to_file(file_path, lines_to_append)

# Read data from the file again to show the appended content
read_file(file_path)
#Program to read data from data file in

append modeaf=open("test.txt",'a')

lines_of_text = ("One line of text

here”,\“and another

line here”,\

“and yet another here”, “and so on and so forth")

af.writelines('\n' +

lines_of_text)af.close()

Output :
Program 14: Write a Program to read data from data file in read mode and count the
particular word occurrences in given string, number of times in python.

Solution:

# Function to count the occurrences of a particular word in a file

def count_word_occurrences(file_path, word_to_count):

try:

with open(file_path, 'r') as file:

data = file.read()

# Convert the data to lowercase to make the search case-insensitive

data_lower = data.lower()

# Split the data into words

words = data_lower.split()

# Count the occurrences of the specified word

count = words.count(word_to_count.lower())

return count

except FileNotFoundError:

print("File not found.")

return 0

# Specify the file path

file_path = 'data.txt'

# Input the word to count

word = input("Enter the word to count: ")

# Count the occurrences of the word in the file

occurrences = count_word_occurrences(file_path, word)

# Print the result

print(f'The word "{word}" occurs {occurrences} times in the file.')


Output :
Program 15: Write a Program to read data from data file in read mode and append the
words starting with letter ‘T’ in a given file in python.

Solution:

# Function to read data and find words starting with 'T'


def find_words_starting_with_t(file_path):
try:
with open(file_path, 'r') as file:
data = file.read()
words = data.split()
t_words = [word for word in words if word.lower().startswith('t')]
return t_words
except FileNotFoundError:
print("File not found.")
return []

# Function to append words to another file


def append_words_to_file(file_path, words):
with open(file_path, 'a') as file:
for word in words:
file.write(word + '\n')
print("Words appended to file.")

# Specify the file paths


source_file_path = 'source.txt'
target_file_path = 'target.txt'

# Find words starting with 'T' from the source file


t_words = find_words_starting_with_t(source_file_path)

# Append these words to the target file


append_words_to_file(target_file_path, t_words)

# Optional: Read and print the content of the target file to verify
with open(target_file_path, 'r') as file:
print("Content of the target file:")
print(file.read())

Output :
Program 16: Write a Program to show MySQL database connectivity in python.

Solution:

import mysql.connector

con=mysql.connector.connect(host='localhost',user='root',password='',db='school')

stmt=con.cursor()

query='select * from student;'

stmt.execute(query)

data=stmt.fetchone()

print(data)
Program 17: Write a Python program to implement all basic operations of a stack, such as
adding element (PUSH operation), removing element (POP operation) and displaying the
stack elements (Traversal operation) using lists.

Solution:

# Define a class for the Stack


class Stack:
def __init__(self):
self.stack = []

# Method to add an element to the stack (PUSH operation)


def push(self, element):
self.stack.append(element)
print(f"Pushed {element} to the stack.")

# Method to remove an element from the stack (POP operation)


def pop(self):
if not self.is_empty():
element = self.stack.pop()
print(f"Popped {element} from the stack.")
return element
else:
print("Stack is empty. Cannot perform POP operation.")
return None

# Method to check if the stack is empty


def is_empty(self):
return len(self.stack) == 0

# Method to display the stack elements (Traversal operation)


def display(self):
if not self.is_empty():
print("Stack elements from top to bottom:")
for element in reversed(self.stack):
print(element)
else:
print("Stack is empty.")

# Create a stack object


my_stack = Stack()

# Perform stack operations


my_stack.push(10)
my_stack.push(20)
my_stack.push(30)
my_stack.display()

my_stack.pop()
my_stack.display()

my_stack.pop()
my_stack.pop()
my_stack.pop() # This will show the stack is empty

Output :
Program 18: Write a program to display unique vowels present in the given word using
Stack.

Solution:

# Define a function to get unique vowels using a stack

def unique_vowels(word):

# Define the set of vowels

vowels = {'a', 'e', 'i', 'o', 'u'}

# Initialize an empty stack and a set to track unique vowels

stack = []

unique_vowels_set = set()

# Iterate through each character in the word

for char in word.lower():

if char in vowels:

# If the character is a vowel and not already in the set, add it to the stack

if char not in unique_vowels_set:

unique_vowels_set.add(char)

stack.append(char)

# Display unique vowels

print("Unique vowels in the word:", end=" ")

while stack:

print(stack.pop(), end=" ")

print()

# Input a word from the user

word = input("Enter a word: ")


# Call the function to display unique vowels

unique_vowels(word)

Output :
Program 19: Write a program in Python to add, delete and display elements from a queue
using list.

Solution:

# Define a class for the Queue


class Queue:
def __init__(self):
self.queue = []

# Method to add an element to the queue (Enqueue operation)


def enqueue(self, element):
self.queue.append(element)
print(f"Enqueued {element} to the queue.")

# Method to remove an element from the queue (Dequeue operation)


def dequeue(self):
if not self.is_empty():
element = self.queue.pop(0)
print(f"Dequeued {element} from the queue.")
return element
else:
print("Queue is empty. Cannot perform Dequeue operation.")
return None

# Method to check if the queue is empty


def is_empty(self):
return len(self.queue) == 0

# Method to display the queue elements (Traversal operation)


def display(self):
if not self.is_empty():
print("Queue elements from front to rear:")
for element in self.queue:
print(element, end=" ")
print()
else:
print("Queue is empty.")

# Create a queue object


my_queue = Queue()

# Perform queue operations


my_queue.enqueue(10)
my_queue.enqueue(20)
my_queue.enqueue(30)
my_queue.display()

my_queue.dequeue()
my_queue.display()

my_queue.dequeue()
my_queue.dequeue()
my_queue.dequeue() # This will show the queue is empty

Output :
Program 20: Perform all the operations with reference to table ‘Employee’ through
MySQL-Python connectivity.

Solution:

import MySQLdb

# Using connect method to connect database

db1 = MySQLdb.connect("localhost","root","","TESTDB" )

# using cursor() method for preparing cursor

cursor = db1.cursor()

# Preparing SQL statement to create EMP table

sql = "CREATE TABLE EMP(empno integer primary key,ename varchar(25) not null,salary
float);"

cursor.execute(sql)

# disconnect from server

db1.close()
Inserting a record in ‘emp’

import MySQLdb

db1 = MySQLdb.connect("localhost","root","","TESTDB" )

cursor = db1.cursor()

# Prepareing SQL statement to insert one record with the given values

sql = "INSERT INTO EMP VALUES (1,'ANIL KUMAR',86000);"

try:

cursor.execute(sql)

db1.commit()
except:

db1.rollback()

db1.close()

Fetching all the records from EMP table having salary more than 70000.

import MySQLdb

db1 = MySQLdb.connect("localhost","root","","TESTDB" )

cursor = db1.cursor()

sql = "SELECT * FROM EMP WHERE SALARY > 70000;"

try:

cursor.execute(sql)

#using fetchall() function to fetch all records from the table EMP and store in
resultset

resultset = cursor.fetchall()

for row in resultset:

print (row)

except:

print ("Error: unable to fetch data")

db1.close()
Updating record(s) of the table using UPDATE

import MySQLdb

db1 = MySQLdb.connect("localhost","root","","TESTDB" )

cursor = db1.cursor()

#Preparing SQL statement to increase salary of all employees whose salary is less than
80000

sql = "UPDATE EMP SET salary = salary +1000 WHERE salary<80000;"

try:

cursor.execute(sql)

db1.commit()

except:

db1.rollback()

db1.close()
Deleting record(s) from table using DELETE

import MySQLdb

db1 = MySQLdb.connect("localhost","root","","TESTDB" )

cursor = db1.cursor()

sal=int(input("Enter salary whose record to be deleted : "))

#Preparing SQL statement to delete records as per given condition

sql = "DELETE FROM EMP WHERE salary =sal”

try:

cursor.execute(sql)

print(cursor.rowcount, end=" record(s) deleted ")

db1.commit()

except:

db1.rollback()

db1.close()

Output:

>>> Enter salary whose record to be deleted: 80000

1 record(s) deleted

>>>

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