Python_Programming_Exercises_with_Solutions
Python_Programming_Exercises_with_Solutions
Index
1. 1. Fibonacci Series using Function
15. 15. Finding Most Common Words in Text File (Phishing Emails)
Solution 1
# Task 1: Fibonacci Series using Function
def fibonacci_series(n):
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
Solution 3
# Task 3: Random Number Generator (Dice Simulator)
import random
def roll_dice():
return random.randint(1, 6)
Solution 4
# Task 4: Creating and Importing a Library
# library.py
def add(a, b):
return a + b
# main.py
import library
print(library.add(5, 3))
print(library.subtract(5, 3))
Solution 5
# Task 5: Reading Text File Line by Line and Separating Words
with open('sample.txt', 'r') as file:
for line in file:
words = line.split()
print('#'.join(words))
Solution 6
# Task 6: Removing Lines Containing 'a' and Writing to Another File
with open('input.txt', 'r') as infile, open('output.txt', 'w') as outfile:
for line in infile:
if 'a' not in line:
outfile.write(line)
Solution 7
# Task 7: Counting Vowels, Consonants, Uppercase, and Lowercase Characters
def count_chars(file_path):
vowels = 'aeiouAEIOU'
vowel_count = consonant_count = uppercase_count = lowercase_count = 0
print(count_chars('sample.txt'))
Solution 8
# Task 8: Adding 'ing' to Words Ending with 't', 'p', 'd'
with open('input.txt', 'r') as infile, open('output.txt', 'w') as outfile:
for line in infile:
words = line.split()
updated_words = [word + 'ing' if word[-1] in 'tpd' else word for word in words]
outfile.write(' '.join(updated_words) + '\n')
Solution 9
# Task 9: Binary File Operations with Name and Roll Number
import pickle
def read_data(file_name):
with open(file_name, 'rb') as file:
return pickle.load(file)