Python Programs
Python Programs
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)
def is_armstrong_number(number):
# Convert the number to a string to find its length
num_str = str(number)
num_digits = len(num_str)
except FileNotFoundError:
print(f"The file '{filename}' was not found.")
def fibonacci_series(n):
fib_series = [0, 1] # Initialize the series with the
first two terms
return fib_series
# Check if n is non-negative
if n <= 0:
print("Please enter a positive integer.")
else:
result = fibonacci_series(n)
print(f"The Fibonacci series up to {n} terms is:
{result}")
PROGRAM -5 : Write a python
program to print factors of a
given number excluding 1 &
itself..
def print_factors_excluding_ends(number):
factors = []
return factors
# Input from the user
num = int(input("Enter a number: "))
def count_characters(file_path):
vowels = "aeiouAEIOU"
consonants =
"bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVW
XYZ"
# Initialize counters
vowel_count = 0
consonant_count = 0
uppercase_count = 0
lowercase_count = 0
try:
with open(file_path, 'r') as file:
content = file.read()
if char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1
except FileNotFoundError:
print(f"The file '{file_path}' was not found.")
return
print("Character counts:")
print(f"Vowels: {vowel_count}")
print(f"Consonants: {consonant_count}")
print(f"Uppercase characters:
{uppercase_count}")
print(f"Lowercase characters:
{lowercase_count}")
def roll_dice():
return random.randint(1, 6)
class Stack:
def _init_(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def pop(self):
if not self.is_empty():
return self.items.pop()
def peek(self):
if not self.is_empty():
return self.items[-1]
def is_palindrome(input_string):
stack = Stack()
except FileNotFoundError:
print(f"The file '{input_file}' was not found.")
except FileNotFoundError:
print(f"The file '{input_file}' was not found.")
# Input file and output file names from the user
input_file_name = input("Enter the name of the
input file: ")
output_file_name = input("Enter the name of
the output file: ")
class Stack:
def _init_(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def pop(self):
if not self.is_empty():
return self.items.pop()
def peek(self):
if not self.is_empty():
return self.items[-1]
def size(self):
return len(self.items)
# Example usage of the stack
stack = Stack()
class Stack:
def _init_(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def pop(self):
if not self.is_empty():
return self.items.pop()
def peek(self):
if not self.is_empty():
return self.items[-1]
def is_palindrome(input_string):
stack = Stack()
def is_palindrome(input_string):
# Convert the input string to lowercase and
remove spaces
cleaned_string =
''.join(input_string.lower().split())
import csv
# Write header
csv_writer.writerow(['user_id', 'password'])
# Write data
csv_writer.writerows(data)
if user_id == target_user_id:
return password
import struct
def update_marks(file_name,
target_roll_number, new_marks):
with open(file_name, 'rb+') as file:
record_size = struct.calcsize('I20s f')
while True:
data = file.read(record_size)
if not data:
break # End of file reached
current_roll_number, current_name,
current_marks = struct.unpack('I20s f', data)
decoded_name =
current_name.decode('utf-8').rstrip('\x00') #
Decode and remove null characters
if current_roll_number ==
target_roll_number:
# Move the file pointer back to update
the marks
file.seek(-record_size, 1)
updated_data = struct.pack('I20s f',
current_roll_number, current_name, new_marks)
file.write(updated_data)
break # Exit the loop after updating
import pymysql
# Query data
cursor.execute('SELECT * FROM users')
rows = cursor.fetchall()
for row in rows:
print(row)
import pymysql
try:
# Connect to MySQL database
connection = pymysql.connect(
host=host,
user=user,
password=password,
database=database
)
except Exception as e:
print(f"Error: {e}")
finally:
# Close the connection
if connection:
connection.close()
PROGRAM -22 :Write a
program to insert data given
below in TEACHER table with
MySQL-Python
connectivity.
import pymysql
try:
# Connect to MySQL database
connection = pymysql.connect(
host=host,
user=user,
password=password,
database=database
)
except Exception as e:
print(f"Error: {e}")
finally:
# Close the connection
if connection:
connection.close()
PROGRAM -23 :Write a
program to fetch all the records
from STUDENT table &
TEACHER table with
MySQL-Python connectivity
import pymysql
try:
# Connect to MySQL database
connection = pymysql.connect(
host=host,
user=user,
password=password,
database=database
)
print("\n---------------------------\n")
except Exception as e:
print(f"Error: {e}")
finally:
# Close the connection
if connection:
connection.close()
PROGRAM -24 :Write a
program to fetch all the records
from STUDENT table who are
reading either XI or XII with
MySQL-Python connectivity.
import pymysql
try:
# Connect to MySQL database
connection = pymysql.connect(
host=host,
user=user,
password=password,
database=database
)
# Create a cursor object
cursor = connection.cursor()
except Exception as e:
print(f"Error: {e}")
finally:
# Close the connection
if connection:
connection.close()
PROGRAM -25 :Write a
program to fetch all the records
from TEACHER table who are
teaching either XI or XII with
MySQL-Python connectivity..
import pymysql
try:
# Connect to MySQL database
connection = pymysql.connect(
host=host,
user=user,
password=password,
database=database
)
# Create a cursor object
cursor = connection.cursor()
except Exception as e:
print(f"Error: {e}")
finally:
# Close the connection
if connection:
connection.close()