Da Python Module 7
Da Python Module 7
December 6, 2024
[ ]: # 2. What is programming?
# -> Programming is the process of creating a set of instructions that a␣
↪computer can follow to perform specific tasks. These instructions, written␣
↪in a programming language, tell the computer how to process data, make␣
[ ]: # 3. What is Python?
# -> Python is a high-level, interpreted programming language known for its␣
↪simplicity and readability. It was created by Guido van Rossum and first␣
↪released in 1991. Python is designed to be easy to learn and use, making it␣
↪a popular choice for beginners and experienced developers alike. and Pyhton␣
1
elif num < 0:
return "The number is negative"
else:
return "The number is zero"
# Output Result
result = check_number(number)
print(result)
Enter a Number: 5
The number is positve
[17]: # 5. Write a Python program to get the Factorial number of given numbers.
Enter a number: 13
6227020800
[14]: # 6. Write a Python program to get the Fibonacci series of given range.
2
a,b = b, a + b
return fib_sequence
Enter a number: 13
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
↪encountered, the remaining code inside the loop for that specific iteration␣
↪ignored, and the loop proceeds with the next iteration based on the loop's␣
↪condition.
3
# - Code Clarity: It can help improve code readability by clearly␣
↪indicating that certain conditions should lead to skipping the remainder of␣
↪the loop for that iteration, rather than using nested␣
↪conditionals.
[24]: # 9. Write python program that swap two number with temp variable and without␣
↪temp variable.
print("Original numbers:")
print(f"num1 = {num1}, num2 = {num2}")
if __name__ == "__main__":
main()
4
Original numbers:
num1 = 5, num2 = 10
After swapping with temp variable:
num1 = 10, num2 = 5
After swapping without temp variable:
num1 = 10, num2 = 5
[13]: # 10. Write a Python program to find whether a given number is even or odd,␣
↪print out an appropriate message to the user.
Enter a number: 4
4 is even number.
[12]: # 11. Write a Python program to test whether a passed letter is a vowel or not.
Enter a letter: A
A is a vowel.
5
[11]: # 12. Write a Python program to sum of three given integers. However, if two␣
↪values are equal sum will be zero.
[10]: # 13. Write a Python program that will return true if the two giveninteger␣
↪values are equal or their sum or difference is 5.
6
[9]: # 14. Write a python program to sum of the first n positive integers.
def sum_of_integers(n):
# Using the formula: sum = n*(n + 1) // 2
return n*(n + 1) // 2
[38]: # 16. Write a Python program to count the number of characters (character␣
↪frequency) in a string
7
# Output: Display the character frequency
print("Character frequency in the string:")
for char, frequency in char_frequency.items():
print(f"'{char}': {frequency}", end = " | ")
[ ]: # 17. What are negative indexes and why are they used?
# -> Negative indexes in Python allow you to access elements from the end of a␣
↪sequence (like lists, strings, or tuples). Instead of starting at 0 for the ␣
↪ first element, negative indexes start at -1 for the last element. For␣
↪example, in a list my_list, my_list[-1] gives you the last element, and ␣
↪ my_list[-2] gives you the second-to-last element.
# - Clarity: They make code more readable. For example, my_list[-1] clearly␣
↪indicates you want the last item, compared to calculating its index with ␣
↪ len(my_list) - 1.
# - Slicing: They can be used in slicing to extract portions of a sequence␣
↪from the end, such as my_list[-3:], which returns the last three elements.
# Input: Get the main string and the substring from the user
main_string = input("Enter the main string: ")
substring = input("Enter the substring to count: ")
8
[1]: # 19. Write a Python program to count the occurrences of each word in a
[3]: # 20. 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.
9
# Output: Display the final combined string
print("Result:", result)
[4]: # 21. Write a Python program to add 'in' 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.
def modify_string(s):
if len(s) < 3:
return s
elif s.endswith('ing'):
return s + 'ly'
else:
return s + 'in'
# Test cases
print(modify_string("run"))
print(modify_string("playing"))
print(modify_string("go"))
runin
playingly
go
[24]: # 22. Write a Python function to reverses a string if its length is a multiple␣
↪of 4.
def reverse_str(s):
if len(s) % 4 == 0:
return s[::-1]
else:
return s
# Test cases
print("len of str is 4:",reverse_str("abcd"))
print("len of str is 5:",reverse_str("hello"))
print("len of str if 6:",reverse_str("python"))
10
len of str if 6: python
[43]: # 23. Write a Python program to get a string made of the first 2 and the last 2␣
↪chars from a given a string. If the string length is less than 2, return␣
def first_last_chars(s):
if len(s) < 2:
return ''
else:
return s[:2] + s[-2:]
# Test cases
print(first_last_chars("spring"))
print(first_last_chars("hello"))
print(first_last_chars("a"))
print(first_last_chars("abcd"))
spng
helo
abcd
[9]: # 24. Write a Python function to insert a string in the middle of a string.
# Example usage:
original_string = "HelloWorld"
string_to_insert = "Python"
result = insert_string_middle(original_string, string_to_insert)
print(result)
# Example:
# Input: my_list = [1, 2, 3, 4, 5]
# my_list.reverse()
11
# print(my_list)
# Output: [5, 4, 3, 2, 1]
# Example:
# Input: my_list = [1, 2, 3, 4, 5]
# reversed_list = my_list[::-1]
# print(reversed_list)
# Output: [5, 4, 3, 2, 1]
# 3. Use the reversed() function to get an iterator and convert it to a list if␣
↪needed.
# Example:
# Input: my_list = [1, 2, 3, 4, 5]
# reversed_list = list(reversed(my_list))
# print(reversed_list)
# Output: [5, 4, 3, 2, 1]
# Example:
# Input: my_list = [1, 2, 3, 4, 5]
# my_list.pop()
# print(my_list)
# Output: [1, 2, 3, 4]
[ ]: # 27. Suppose list1 is [2, 33, 222, 14, and 25], what is list1 [-1]?
# -> In Python, using a negative index accesses elements from the end of the␣
↪list. Specifically, list1[-1] refers to the last element of the list.
# Example:
# Input: list1 = [2, 33, 222, 14, 25]
# list[-1]
# Output: 25
# -> append()
# 1. Purpose: Adds a single element to the end of a list.
# 2. Behavior: The element added can be of any data type(including another␣
↪list), but it is treated as a single entity.
# 3. Example:
12
# Input: my_list = [1, 2, 3]
# my_list.append(4)
# my_list.append([5, 6])
# print(my_list)
# Output: [1, 2, 3, 4, [5, 6]]
# -> extend()
# 1. Purpose: Adds multiple elements to the end of a list.
# 2. Behavior: The elements from the iterable (e.g., another list) are␣
↪unpacked and added individually to the list.
# 3. Example:
# Input: my_list = [1, 2, 3]
# my_list.extend(4)
# my_list.extend([4, 5])
# print(my_list)
# Output: [1, 2, 3, 4, 5]
# -> Summary
# :- Use append() to add a single item, which could be a list itself.
# :- Use extend() to add multiple items from an iterable, expanding the list.
[24]: # 29. Write a Python function to get the largest number, smallest num and sum␣
↪of all from a list.
def get_list_stats(numbers):
if not numbers: # Check if the list is empty
return None, None, 0
# Example usage
numbers = [10, 20, 5, 40, 15]
print("Largest number:", largest)
print("Smallest number:", smallest)
print("Sum of all numbers:", total_sum)
Largest number: 40
Smallest number: 5
Sum of all numbers: 90
13
# 1. Equality Comparison (==): Checks if two lists have the same elements in␣
the same order.
↪
# 3. Unordered Comparison with set(): Checks if two lists contain the same␣
↪unique elements, regardless of order.
# -> These methods allow you to check for equality, size, and order of elements␣
↪in lists effectively.
[1]: # 31. Write a Python program to count the number of strings where the string␣
↪length is 2 or more and the first and last character are same from a given␣
↪list of strings.
def count_strings(strings):
count = 0
for string in strings:
if len(string) >= 2 and string[0] == string[-1]:
count += 1
return count
# Example usage:
strings_list = ['abc', 'xyz', 'aba', '1221', 'aa', 'abba', 'defed']
result = count_strings(strings_list)
print(f"The number of strings with matching first and last characters is:␣
↪{result}")
The number of strings with matching first and last characters is: 5
def remove_duplicates(input_list):
return list(set(input_list))
# Example usage:
my_list = [1, 2, 2, 3, 4, 4, 5, 6, 6, 7]
result = remove_duplicates(my_list)
print(f"List after removing duplicates: {result}")
14
List after removing duplicates: [1, 2, 3, 4, 5, 6, 7]
def is_list_empty(input_list):
return len(input_list) == 0
# Example usage:
my_list = []
if is_list_empty(my_list):
print("The list is empty.")
else:
print("The list is not empty.")
[18]: # 34. Write a Python function that takes two lists and returns true if they␣
↪have at least one common member.
# Example usage:
list1 = [1, 2, 3, 4]
list2 = [4, 5, 6, 7]
True
[19]: # 35. Write a Python program to generate and print a list of first and last 5␣
↪elements where the values are square of numbers between 1 and 30.
def generate_squares():
# Generate the list of squares of numbers between 1 and 30
squares = [x**2 for x in range(1, 31)]
# Example usage
print(generate_squares())
15
[23]: # 36. Write a Python function that takes a list and returns a new list with␣
↪unique elements of the first list.
def get_unique_elements(input_list):
return list(set(input_list))
# Example usage
original_list = [1, 2, 2, 3, 4, 4, 5, 5, 5]
unique_list = get_unique_elements(original_list)
print(unique_list)
[1, 2, 3, 4, 5]
[1]: # 37. Write a Python program to convert a list of characters into a string.
[4]: # 38. Write a Python program to select an item randomly from a list.
import random
[5]: # 39. Write a Python program to find the second smallest number in a list.
16
# Remove duplicates by converting the list to a set, then convert back to a␣
↪sorted list
unique_numbers = sorted(set(numbers))
[8]: # 40. Write a Python program to get unique values from a list
[13]: # 41. Write a Python program to check whether a list contains a sub list
# Loop through the main list and check for the sublist
for i in range(len_main - len_sub + 1):
if main_list[i:i + len_sub] == sub_list:
return True
return False
17
print("The main list contains the sublist.")
else:
print("The main list does not contain the sublist.")
[15]: # 42. Write a Python program to split a list into different variables
a = 1
b = 2
c = 3
d = 4
e = 5
# -> A tuple is a built-in data structure in Python that allows you to store a␣
↪collection of items. It is similar to a list, but it has some important ␣
↪ characteristics that set it apart.
18
# Mutability Mutable (can be modified after creation) ␣
↪
# Feature Tuple
# Syntax Created using parentheses ()
# Mutability Immutable (cannot be modified after creation)
# Methods Supports fewer methods (mostly accessing elements)
# Performance Typically faster because of immutability
# Use Case Ideal for fixed collections that should not change
[2]: # 44. Write a Python program to create a tuple with different data types.
# Tuple length
print("\nLength of the tuple:", len(my_tuple))
Accessing elements:
Integer: 1
String: Hello
Float: 3.14
Boolean: True
NoneType: None
19
[3]: # 45. Write a Python program to unzip a list of tuples into individual lists.
# List of tuples
tuple_list = [(1, 'apple'), (2, 'banana'), (3, 'cherry'), (4, 'date')]
List 1: [1, 2, 3, 4]
List 2: ['apple', 'banana', 'cherry', 'date']
[4]: # 46. Write a Python program to convert a list of tuples into a dictionary.
# List of tuples
tuple_list = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
↪the first element will be the key and the second element will be the␣
↪value.
# Input:
# # Step 1: Define a list of tuples
# tuple_list = [('apple', 1), ('banana', 2), ('cherry', 3)]
20
# # Step 3: Print the dictionary
# print("Fruit Dictionary:", fruit_dict)
# Output:
# Fruit Dictionary: {'apple': 1, 'banana': 2, 'cherry': 3}
# Input:
# # Step 1: Define a list of tuples
# tuple_list = [('apple', 1), ('banana', 2), ('cherry', 3)]
# -> Conclusion:
# -> Both methods are effective for creating a dictionary from tuples. The␣
↪dict() function is more concise, while the loop method provides more ␣
↪ control and can be modified easily for additional logic if needed. Use␣
↪the method that best suits your assignment requirements!
[5]: # 48. Write a Python script to sort (ascending and descending) a dictionary by␣
↪value.
# Sample dictionary
my_dict = {'apple': 5, 'banana': 2, 'cherry': 7, 'date': 1}
21
Sorted Dictionary (Ascending): {'date': 1, 'banana': 2, 'apple': 5, 'cherry': 7}
Sorted Dictionary (Descending): {'cherry': 7, 'apple': 5, 'banana': 2, 'date':
1}
# Dictionaries to concatenate
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict3 = {'e': 5, 'f': 6}
# Concatenate dictionaries
new_dict = {**dict1, **dict2, **dict3}
[8]: # 50. Write a Python script to check if a given key already exists in a␣
↪dictionary.
# Sample dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Key to check
key_to_check = 'b'
22
# 'Tirth', 22, and 'Ahmedabda' are values
# -> Summary
# Keys only: for key in my_dict
# Values only: for value in my_dict.values()
# Both keys and values: for key, value in my_dict.items()
↪ assignment.
23
# -> How to Check if a Key Exists
# -> The easiest way to check for a key in a dictionary is to use the in␣
↪keyword.
# -> Example
# -> # Sample dictionary
# my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# # Key to check
# key_to_check = 'age'
# -> Explanation
# -> in keyword:
# :- key_to_check in my_dict checks if the key ('age' in this case)␣
↪exists in my_dict.
# -> Summary
# -> To check for a key:
# :- Use if key in dictionary for a quick check.
# :- Output will tell you if the key is there or not.
[2]: # 53. Write a Python script to print a dictionary where the keys are numbers␣
↪between 1 and 15.
# Creating the dictionary with keys from 1 to 15 and values as the square of␣
↪each key
24
[10]: # 54. Write a Python program to check multiple keys exists in a dictionary.
# Sample dictionary
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# Keys to check
keys_to_check = ['name', 'age']
[13]: # 56. Write a Python program to map two lists into a dictionary - Sample output:
↪ Counter ({'a': 400, 'b': 400,’d’: 400, 'c': 300}).
Mapped dictionary: {'a': 400, 'b': 400, 'c': 300, 'd': 400}
25
[3]: # 57. Write a Python program to find the highest 3 values in a dictionary.
def find_highest_three_values(input_dict):
# Check if the dictionary has less than 3 items
if len(input_dict) < 3:
return "The dictionary must have at least three items."
# Example usage
sample_dict = {
'a': 10,
'b': 20,
'c': 30,
'd': 25,
'e': 15
}
result = find_highest_three_values(sample_dict)
print("The highest three values are:", result)
[4]: # 58. Write a Python program to combine values in python list of dictionaries.
# Sample data: [{'item': 'item1', 'amount': 400}, {'item': 'item2',␣
↪'amount':300}, {'item': 'item1', 'amount': 750}]
def combine_values(data):
# Initialize a Counter to hold the combined amounts
combined = Counter()
return combined
# Sample data
sample_data = [
{'item': 'item1', 'amount': 400},
26
{'item': 'item2', 'amount': 300},
{'item': 'item1', 'amount': 750}
]
[6]: # 59. Write a Python program to create a dictionary from a string. Note: Track␣
↪the count of the letters from the string.
def count_letters(input_string):
# Initialize an empty dictionary to store the counts
letter_count = {}
return letter_count
# Example usage
sample_string = "Hello, World!"
result = count_letters(sample_string)
print("Letter count:", result)
[18]: # 60. Sample string: 'w3resource' Expected output: {'3': 1,’s’: 1, 'r': 2, 'u':␣
↪1, 'w': 1, 'c': 1, 'e': 2, 'o': 1}
# Sample string
input_string = 'w3resource'
27
# Iterate through each character in the string
for char in input_string:
# Increment the count for the character
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
Character count: {'w': 1, '3': 1, 'r': 2, 'e': 2, 's': 1, 'o': 1, 'u': 1, 'c':
1}
[23]: # 61. Write a Python function to calculate the factorial of a number (a non␣
↪negative integer)
def factorial(n):
# Check if the input is a non-negative integer
if n < 0:
raise ValueError("Input must be a non-negative integer.")
if n == 0 or n == 1:
return 1
result = 1
for i in range(2, n + 1):
result *= i
return result
# Example usage
number = int(input("Enter a number:"))
print(f"The factorial of {number} is {factorial(number)}.")
Enter a number: 5
The factorial of 5 is 120.
[28]: # 62. Write a Python function to check whether a number is in a given range.
# Example usage
number = 10
range_start = 5
range_end = 15
28
print(f"{number} is in the range [{range_start}, {range_end}].")
else:
print(f"{number} is not in the range [{range_start}, {range_end}].")
[33]: # 63. Write a Python function to check whether a number is perfect or not.
def is_perfect(number):
# A number must be greater than 1 to be considered perfect
if number < 1:
return False
# Example usage:
num = 6
if is_perfect(num):
print(f"{num} is a perfect number.")
else:
print(f"{num} is not a perfect number.")
6 is a perfect number.
[38]: # 64. Write a Python function that checks whether a passed string is palindrome␣
↪or not.
def is_palindrome(string):
# Convert string to lowercase to ignore case sensitivity
string = string.lower()
# Remove any spaces from the string
string = string.replace(" ", "")
# Check if the string is equal to its reverse
return string == string[::-1]
True
29
# 1. Built-in Functions
# -> These are functions that are already defined in Python and can be␣
↪used directly without needing to write any code for them.
# -> Example:
# -> Input: print("Hello, World!") # 'print()' is a built-in function
# length = len("Python") # 'len()' gives the length of the␣
↪string
# 2. User-defined Functions
# -> These are functions that you create yourself to perform specific␣
↪tasks.
# -> You define these functions using the def keyword, followed by the␣
↪function name and any parameters it needs.
# -> User-defined functions are useful when you need to repeat certain␣
↪operations multiple times in your code.
# -> Example:
# -> Input: def greet(name):
# return f"Hello, {name}!"
# print(greet("Alice"))
# -> Summary
# -> Built-in Functions: Ready-made functions provided by Python (like␣
↪print() and len()).
[ ]: # 66. How can you pick a random item from a list or tuple?
# -> To pick a random item from a list or tuple in Python, you can use the␣
↪choice() function from the random module. This is a built-in function in␣
↪Python that helps you choose a random element from a sequence (like a␣
↪list or tuple).
# -> Use random.choice() and pass the list or tuple you want to choose from␣
↪as an argument. This function will then pick one item randomly from that ␣
↪ list or tuple.
# -> Example:
# -> Input: import random
30
# # Example list and tuple
# my_list = [10, 20, 30, 40, 50]
# my_tuple = ('apple', 'banana', 'cherry', 'date')
# -> Summary
# -> Using random.choice() is an easy way to pick a random item from any␣
↪list or tuple in Python. Just remember to import the random module first!
# -> Example:
# -> Input: import random
# -> Summary
# -> To pick a random item from a range:
# -> Use random.randrange(start, stop) after importing the random module.
31
# -> Remember, the stop value is not included, so it picks a random␣
number from start to stop - 1.
↪
# -> Example
# -> Input: import random
# random_number = random.randint(1, 10)
# print(random_number)
# -> Explanation: This will give you a random integer between 1␣
↪and 10, including both 1 and 10.
# -> Example
# -> Input: import random
# random_decimal = random.random()
# print(random_decimal)
# -> Explanation: This will give you a random decimal number␣
↪between 0 and 1. Each time you run it, you'll get a different decimal.
# -> Example
# -> Input: import random
# random_decimal_range = random.uniform(5.5, 10.5)
# print(random_decimal_range)
# -> Explanation: This will give you a random decimal number␣
↪between 5.5 and 10.5, including both 5.5 and 10.5.
# -> Summary
# -> randint(a, b) for a random integer between a and b.
# -> random() for a random decimal between 0 and 1.
# -> uniform(a, b) for a random decimal between a and b.
# -> Using any of these methods is simple and will give you different␣
↪random numbers each time you run them!
[ ]: # 69. How will you set the starting value in generating random numbers?
32
# -> To set the starting value (or seed) when generating random numbers in␣
↪Python, you can use the seed function from the random module. Setting a seed␣
↪ ensures that you get the same "random" numbers each time you run your␣
↪code, which is helpful for testing and debugging.
# -> Example
# -> Input: import random
# # Set the seed to a specific value, e.g., 42
# random.seed(42)
# -> Without setting a seed, the numbers generated by random will be different␣
↪each time you run the program, which is usually the default and desired ␣
↪ behavior for most applications.
↪function changes the order of the list items randomly "in place," which␣
↪means the original list itself is modified and no new list is created.
# -> Example
# -> Here’s an example to shuffle a list of numbers:
# -> Input: import random
# # Original list
# my_list = [1, 2, 3, 4, 5]
# print(my_list)
# -> Explanation:
# -> random.shuffle(my_list) will rearrange the items in my_list randomly.
33
# -> Since shuffle works "in place," it modifies my_list directly instead␣
of creating a new list.
↪
# -> Each time you run this code, my_list will have a different random␣
↪order.
# -> Random order: Each time you shuffle, the order will be different.
# -> This is useful when you need to randomize data, like shuffling a deck of␣
↪cards or creating random quizzes.
[ ]: # 71. What is File function in python? What are keywords to create and write␣
↪file.
# -> In Python, the "File" function usually refers to working with files using␣
↪built-in functions that allow you to create, read, write, and close files. ␣
↪ Here’s an easy explanation of how it works:
# -> "w" (write mode): Creates a new file if it doesn’t exist, or␣
↪overwrites the file if it does exist.
# -> "a" (append mode): Creates a new file if it doesn’t exist, or adds␣
↪data to the end of an existing file.
# -> Example
# -> Input: # Creating a new file in write mode
# file = open("example.txt", "w")
# 2. Writing to a File
# -> Use the write() method to add text to the file.
# -> If you use "w" mode, it will overwrite any existing content. If␣
↪you use "a" mode, it will add (append) to the existing content.
# -> Example
# -> Input: # Writing text to the file
# file.write("Hello, this is a test.")
34
# -> After performing all operations, close the file using close().␣
This ensures all data is saved and frees up system resources.
↪
# -> Example
# -> Input: # Closing the file
# file.close()
[5]: # 73. Write a Python program to append text to a file and display the text.
35
print(content)
# Example usage
file_name = 'Tirth_append.txt'
text_to_append = "My favourite game is Volleyball."
append_and_display(file_name, text_to_append)
if not line:
break
print(line.strip()) # Print each line without extra newline
# Example usage
file_name = 'Tirth_append.txt'
n = 5 # Number of lines to read
read_first_n_lines(file_name, n)
36
# Use deque to keep only the last n lines in memory
last_n_lines = deque(file, maxlen=n)
# Example usage
file_name = 'Tirth_append.txt'
n = 5 # Number of lines to read from the end
read_last_n_lines(file_name, n)
[8]: # 76. Write a Python program to read a file line by line and store it into a␣
↪list
except FileNotFoundError:
print(f"The file '{filename}' was not found.")
return lines
# Example usage
filename = 'Tirth_append.txt' # Replace with your file name
lines_list = read_file_to_list(filename)
print(lines_list)
[9]: # 77. Write a Python program to read a file line by line store it into a␣
↪variable.
37
content = ""
try:
with open(filename, 'r') as file:
content = file.read() # Read all lines at once
except FileNotFoundError:
print(f"The file '{filename}' was not found.")
return content
# Example usage
filename = 'Tirth_append.txt' # Replace with your file name
file_content = read_file_to_variable(filename)
print(file_content)
# Example usage
filename = 'Tirth_append.txt' # Replace with your file name
print("Longest word:", find_longest_word(filename))
[12]: # 79. Write a Python program to count the number of lines in a text file.
# Example usage
filename = 'Tirth_append.txt' # Replace with your file name
print("Number of lines:", count_lines(filename))
Number of lines: 5
38
[13]: # 80. Write a Python program to count the frequency of words in a file.
def count_word_frequency(filename):
with open(filename, 'r') as file:
words = file.read().lower().split() # Convert to lowercase and split␣
↪into words
word_count = Counter(words)
return word_count
# Example usage
filename = 'Tirth_append.txt' # Replace with your file name
word_frequencies = count_word_frequency(filename)
print("Word frequencies:", word_frequencies)
# Example usage
filename = 'Tirth_append.txt' # Replace with your desired file name
my_list = ["apple", "banana", "cherry", "date"]
write_list_to_file(filename, my_list)
print(f"List written to {filename}")
[15]: # 82. Write a Python program to copy the contents of a file to another file.
# Example usage
39
source_file = 'Tirth_append.txt' # Replace with your source file name
destination_file = 'Tirth_append1.txt' # Replace with your destination file␣
↪name
copy_file(source_file, destination_file)
print(f"Contents copied from {source_file} to {destination_file}")
# -> try block: Code that might cause an exception is placed here. Python␣
↪will try to execute this code.
# -> except block: If an exception occurs in the try block, the code in the␣
↪except block executes. This helps to handle errors without crashing the ␣
↪ program.
# -> else block: Code in the else block runs if no exception was raised in␣
↪the try block.
# -> finally block: This block always runs, regardless of whether an␣
↪exception occurred, and is commonly used for cleanup actions. ␣
↪ (e.g., closing files).
# -> Example
# -> Input: try:
# result = 10 / 0
# except ZeroDivisionError:
# print("Cannot divide by zero!")
# else:
# print("Division successful:", result)
# finally:
# print("Execution completed.")
# -> In this example:
# -> If there’s a division by zero, the except block will handle the␣
↪ZeroDivisionError.
# -> Syntax Errors: Errors in the syntax of the code, such as missing␣
↪colons or incorrect indentation. These are detected before execution.
40
# -> Exceptions: Errors that occur during execution. Python provides␣
various built-in exceptions, such as ZeroDivisionError, ValueError, and
↪ ␣
↪ FileNotFoundError.
# -> Example: Dividing by zero or trying to access a file that doesn’t␣
↪exist
[ ]: # 84. How many except statements can a try-except block have? Name Some␣
↪built-in exception classes:
# -> A try-except block in Python can have multiple except statements to handle␣
↪different types of exceptions. Each except statement can specify a ␣
↪ different exception type to catch specific errors. There’s technically no␣
↪limit to the number of except blocks you can have in a single try-except ␣
↪ block.
# -> Example
# -> Input: try:
# result = 10 / 2 # This will succeed
# except ZeroDivisionError:
# print("Cannot divide by zero!")
# else:
# print("Division successful, result is:", result) # This␣
↪will run if no exception occurs
# -> Explanation:
41
# -> In the above example, since 10 / 2 does not raise any exceptions,␣
the code in the else block executes, printing the result.
↪ ␣
↪ -> If there had been an exception (for example, if we tried to divide␣
↪by zero), the except block would have executed, and the else block would ␣
↪ be skipped.
# -> Key Points:
# -> The else block is useful for code that should run only after the try␣
↪block executes successfully without errors.
# -> It helps in separating the error handling (in except) from the␣
↪successful execution code, improving code readability.
# -> You can still access the caught exception using the as keyword,␣
↪allowing you to print or log specific details about the error.
↪try block.
42
# 3. Exception Raised but Not Caught: If an exception occurs that is not␣
↪caught by an except block, the finally block will execute before the program␣
↪ terminates.
# 4. Program Exit: If the program exits via a sys.exit() call or due to an␣
↪unhandled exception, the finally block will execute just before the program ␣
↪ exits.
# 1. Data Types: The left side of the expression is a string ("1"), and the␣
↪right side is an integer (1). In Python, the equality operator (==) checks ␣
↪ for both value and type equality.
# 2. Type Mismatch: Since the two operands are of different types (string␣
↪vs integer), Python determines that they cannot be equal.
# -> In Python, you can handle exceptions using the try, except, and finally␣
↪blocks. This structure allows you to manage errors gracefully while ensuring␣
# 1. try Block
# -> The try block contains code that might raise an exception. If an␣
↪exception occurs, the control is passed to the corresponding except block.
# 2. except Block
# -> The except block is used to handle specific exceptions that might␣
↪be raised in the try block. You can have multiple except blocks to handle ␣
↪ different types of exceptions.
# 3. finally Block
# -> The finally block contains code that will execute regardless of␣
↪whether an exception occurred or was caught. This is useful for cleanup ␣
↪ actions, such as closing files or releasing resources.
# -> Explanation:
# -> try Block: The code attempts to divide num1 by num2.
43
# -> except ZeroDivisionError: If num2 is 0, this block will execute,␣
printing an error message.
↪
# -> else Block: If no exceptions occur, this block will print the␣
↪successful division result.
# -> finally Block: This block executes no matter what, ensuring that any␣
↪cleanup actions are performed. It always runs after the try and except ␣
↪ blocks.
# -> Summary:
# -> Use the try block to enclose code that might raise an exception.
# -> Handle specific exceptions in except blocks.
# -> Use the finally block for cleanup code that should always execute.
# -> Example: The example is write down above shell.
[16]: # 89. How Do You Handle Exceptions with Try/Except/Finally in Python? Explain␣
↪with coding snippets
# Example usage
print("Example 1:")
divide_numbers(10, 2) # Valid division
print("\nExample 2:")
divide_numbers(10, 0) # Division by zero
print("\nExample 3:")
44
divide_numbers(10, "a") # Invalid input type
Example 1:
Division successful. Result: 5.0
Execution of finally block.
Example 2:
Error: Cannot divide by zero.
Execution of finally block.
Example 3:
Error: Both inputs must be numbers.
Execution of finally block.
[18]: # 90. Write python program that user to enter only odd numbers, else will raise␣
↪an exception.
def get_odd_number():
while True:
try:
# Prompt the user for input
number = int(input("Enter an odd number: "))
# Check if the number is odd
if number % 2 == 0:
raise ValueError("The number entered is even. Please enter an␣
↪odd number.")
else:
print(f"Thank you! You entered the odd number: {number}")
break # Exit the loop if an odd number is entered
except ValueError as e:
print(e) # Print the error message
# Example usage
get_odd_number()
[ ]:
45