Pythonupdate
Pythonupdate
# Addition
result1 = 2 + 3
print("2 + 3 =", result1)
# Multiplication
result2 = 5 * 3
print("5 * 3 =", result2)
# Subtraction
result3 = 7 - 2
print("7 - 2 =", result3)
# Division (floating-point)
result4 = 6 / 2
print("6 / 2 =", result4)
# Division (integer)
result5 = 6 // 4
print("6 // 4 =", result5)
3- 3. Write a program to read five integers from user and find the
average
# Initialize a variable to store the sum of the integers
sum_of_integers = 0
# Read five integers from the user and add them to the sum
for i in range(5):
num = int(input(f"Enter integer {i + 1}: "))
sum_of_integers += num
# Read five integers from the user and add them to the sum
for i in range(5):
num = int(input(f"Enter integer {i + 1}: "))
sum_of_integers += num
try:
except ValueError:
➢
7- Write a program to read the values of two integer variables and
use bitwise operators to exchange the values of the variables
(^ operator).
6# Read two integers from the user
try:
num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))
10-Write a program to read the values of two points on x-y plane and find
out the distance between two points.
➢ Use math functions (sqrt, pow)
import math
12-Write a program to check whether the integer is prime or find its first factor
# Read an integer from the user
try:
num = int(input("Enter an integer: "))
def factorial(n):
if n < 0:
elif n == 0:
return 1
else:
return n * factorial(n - 1)
try:
result = factorial(num)
except ValueError:
def sum_of_digits(n):
digit_sum = 0
n = abs(n)
while n > 0:
digit = n % 10
digit_sum += digit
n //= 10
return digit_sum
try:
result = sum_of_digits(num)
except ValueError:
16-Write a Python function to check whether a given number is a prime number or not
def is_prime(number):
if number <= 1:
return False
if number <= 3:
return True
if 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
# Example usage:
sum_result = add_integers(5, 10, 15, 20)
print(f"The sum is: {sum_result}")
18-Write a function to receive multiple strings and count total characters.
def count_total_characters(*args):
total_characters = 0
for string in args:
total_characters += len(string)
return total_characters
# Example usage:
strings = ["Hello", "World", "Python"]
total_chars = count_total_characters(*strings)
print(f"The total number of characters is: {total_chars}")
18-Write a function to receive multiple strings and count total characters.
def count_total_characters(*args):
total_characters = 0
for string in args:
total_characters += len(string)
return total_characters
# Example usage:
strings = ["Hello", "World", "Python"]
total_chars = count_total_characters(*strings)
print(f"The total number of characters is: {total_chars}")
19-Write a Python program that first accept a string and If the string length is less
than 2, return empty string. Then create a string made of the first 2 and the last
2 chars from the accepted string. Sample String : ‘Computer Science'
Expected Result : ‘Coce'
Sample String : ‘My'
Expected Result : ‘MyMy'
Sample String : ' w'
Expected Result : Empty String
def make_new_string(input_string):
if len(input_string) < 2:
return ""
new_string = input_string[:2] + input_string[-2:]
return new_string
def replace_first_char_occurrences(input_string):
if len(input_string) < 2:
return input_string
first_char = input_string[0]
return modified_string
result = replace_first_char_occurrences(input_string)
21-Write a Python program to get a single string from two given strings, separated by a space and swap the
first two characters of each string. Sample String : 'abc', 'xyz' Expected Result : 'xyc abz
def make_new_string(input_string):
if len(input_string) < 2:
return ""
22-Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given
string already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave it
unchanged. Sample String : ‘Giv' Expected Result : ‘Giving' Sample String : 'string' Expected Result : 'stringly’ •
Sample String : 'st’ Expected Result : ‘st
def modify_string(input_string):
if len(input_string) < 3:
return input_string
elif input_string.endswith('ing'):
return input_string + 'ly'
else:
return input_string + 'ing'
def add_numbers(numbers_list):
result = 0
result += item
return result
sum_of_numbers = add_numbers(mixed_list)
26-Python Program to Put Even and Odd elements in a List into Two Different Lists
# Function to separate even and odd elements into two lists
def separate_even_odd(input_list):
even_list = []
odd_list = []
if item % 2 == 0:
even_list.append(item)
else:
odd_list.append(item)
numbers_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
merged_list.sort()
return merged_list
# Example lists
list1 = [3, 1, 4, 1, 5, 9]
list2 = [2, 6, 5, 3, 5, 8]
28-Python Program to Find the Second Largest Number in a List Using Bubble Sort
# Function to find the second largest number using Bubble Sort
def find_second_largest(numbers):
n = len(numbers)
# Example lists
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
# Example lists
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
return max_length
def max_subarray(arr):
if not arr:
return 0
current_sum = arr[0]
return max_sum
max_sum = max_subarray(nums)
my_tuple = (1, 2, 3, 4, 5)
print("var1:", var1)
print("var2:", var2)
print("var3:", var3)
print("var4:", var4)
print("var5:", var5)
def find_repeated_items(input_tuple):
repeated_items = []
seen_items = set()
if item in seen_items:
if item not in repeated_items:
repeated_items.append(item)
else:
seen_items.add(item)
return repeated_items
my_tuple = (1, 2, 2, 3, 4, 4, 5, 5, 6)
repeated_items = find_repeated_items(my_tuple)
try:
index = input_tuple.index(item)
return index
except ValueError:
return None
# Example tuple
my_tuple = (1, 2, 3, 4, 5, 6, 7)
item_to_find = 4
else:
try:
index = input_tuple.index(item)
return index
except ValueError:
return None
# Example tuple
my_tuple = (1, 2, 3, 4, 5, 6, 7)
item_to_find = 4
else:
def remove_empty_tuples(tuple_list):
return non_empty_tuples
list_of_tuples = [(1, 2), (), (3, 4), (), (5, 6), ()]
result = remove_empty_tuples(list_of_tuples)
print(result)
my_set.add(1)
my_set.add(2)
my_set.add(3)
my_set.remove(2)
# Remove an item from the set using the discard() method (if it exists)
my_set.discard(4)
44-Write a Python program to remove an item from a set if it is present in the set.
# Create a set
my_set = {1, 2, 3, 4, 5}
item_to_remove = 3
my_set.discard(item_to_remove)
# Display the set after removal (no error if the item is not present)
set2 = {3, 4, 5, 6, 7}
intersection = set1.intersection(set2)
union = set1.union(set2)
difference = set1.difference(set2)
symmetric_difference = set1.symmetric_difference(set2)
# Create a set
original_set = {1, 2, 3, 4, 5}
shallow_copy_method = original_set.copy()
shallow_copy_constructor = set(original_set)
original_set.add(6)
# Create a set
original_set = {1, 2, 3, 4, 5}
shallow_copy_method = original_set.copy()
shallow_copy_constructor = set(original_set)
original_set.add(6)
import copy
original_dict = {
'set2': {4, 5, 6}
deep_copy_dict = copy.deepcopy(original_dict)
merged_dict1 = dict1.copy()
merged_dict1.update(dict2)
print(merged_dict1)
print(merged_dict2)
53-Write a Python script to create a dictionary where the keys are numbers between 1 and 15 (both included) and
the values are square of keys.
return unique_dict
if choice == '1':
add_student_info()
elif choice == '2':
display_student_info()
elif choice == '3':
print("Exiting the program.")
break
else:
print("Invalid choice. Please select a valid option.")
55-Write a Python program to replace dictionary values with their
sum
# Define a dictionary with numeric values
original_dict = {'a': 10, 'b': 20, 'c': 30, 'd': 40}
59-Write a Python program to replace dictionary values (integers) with their sum.
try:
for i in range(n):
line = file.readline()
if not line:
except FileNotFoundError:
except Exception as e:
read_first_n_lines(file_name, n)
61- Write a Python program to append text to a file and display the text.
# Function to append text to a file
def append_to_file(file_name, text_to_append):
try:
with open(file_name, 'a') as file:
file.write(text_to_append)
print("Text appended to the file successfully.")
except Exception as e:
print(f"An error occurred: {str(e)}")
63-Write a Python program to read a file line by line and store it in a list
def read_file_lines_to_list(file_name):
try:
with open(file_name, 'r') as file:
lines_list = file.readlines()
return lines_list
except FileNotFoundError:
print(f"File '{file_name}' not found.")
return []
except Exception as e:
print(f"An error occurred: {str(e)}")
return []
# Call the function to read the file lines and store them in a list
lines_list = read_file_lines_to_list(file_name)
# Display the list of lines
if lines_list:
print("Lines from the file:")
for line in lines_list:
print(line.strip()) # Print and strip newline characters
64-Write a Python program to read a file line by line and store it into a
Variable
def read_file_to_variable(file_name):
try:
with open(file_name, 'r') as file:
file_contents = ""
for line in file:
file_contents += line
return file_contents
except FileNotFoundError:
print(f"File '{file_name}' not found.")
return ""
except Exception as e:
print(f"An error occurred: {str(e)}")
return ""
# Call the function to read the file and store its contents in a variable
file_contents = read_file_to_variable(file_name)
# Example text
text = "This is a sample sentence. The longest words in this sentence are example
and sentence!"
# Example text
text = "This is a sample sentence. The longest words in this
sentence are example and sentence!"
import string
def count_word_frequency(file_name):
try:
with open(file_name, 'r') as file:
word_frequency = {}
for line in file:
# Remove punctuation and convert to lowercase
line = line.translate(str.maketrans('', '',
string.punctuation)).lower()
words = line.split()
for word in words:
if word in word_frequency:
word_frequency[word] += 1
else:
word_frequency[word] = 1
return word_frequency
except FileNotFoundError:
print(f"File '{file_name}' not found.")
return {}
except Exception as e:
print(f"An error occurred: {str(e)}")
return {}
# Specify the file name you want to read
file_name = 'sample.txt' # Replace with the actual file name
# Call the function to copy the contents of the source file to the
destination file
copy_file(source_file, destination_file)
69-Write a Python program to combine each line from the first
file with
the corresponding line in the second file
def combine_files(file1, file2, output_file):
try:
with open(file1, 'r') as f1, open(file2, 'r') as f2,
open(output_file, 'w') as output:
for line1, line2 in zip(f1, f2):
combined_line = f"{line1.strip()} {line2.strip()}\n"
output.write(combined_line)
print(f"Lines from '{file1}' and '{file2}' combined and written
to '{output_file}' successfully.")
except FileNotFoundError as e:
print(f"File not found: {str(e)}")
except Exception as e:
print(f"An error occurred: {str(e)}")
# Specify the names of the two source files and the output file
file1 = 'file1.txt' # Replace with the actual name of the first file
file2 = 'file2.txt' # Replace with the actual name of the second file
output_file = 'combined.txt' # Specify the name of the output file
# Call the function to combine lines from both files and write to
the output file
combine_files(file1, file2, output_file)
70-Write a program to read a text file and compute the frequency of each word, character, alphabet, and integer.
import string
def compute_frequencies(file_name):
try:
with open(file_name, 'r') as file:
word_frequency = {}
char_frequency = {}
alphabet_frequency = {}
integer_frequency = {}
# Display frequencies
if word_frequency:
print("Word Frequency:")
for word, count in word_frequency.items():
print(f"{word}: {count}")
if char_frequency:
print("Character Frequency:")
for char, count in char_frequency.items():
print(f"{char}: {count}")
if alphabet_frequency:
print("Alphabet Frequency:")
for char, count in alphabet_frequency.items():
print(f"{char}: {count}")
if integer_frequency:
print("Integer Frequency:")
for char, count in integer_frequency.items():
print(f"{char}: {count}")