0% found this document useful (0 votes)
26 views2 pages

Python Code for Summation and File Handling

The document contains several Python code snippets demonstrating basic operations such as summing elements in a list and dictionary, writing to and reading from a file, handling file not found errors, and managing division by zero exceptions. Each section includes a brief description of the code's functionality. Overall, it illustrates fundamental programming concepts and error handling in Python.

Uploaded by

AMIT
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views2 pages

Python Code for Summation and File Handling

The document contains several Python code snippets demonstrating basic operations such as summing elements in a list and dictionary, writing to and reading from a file, handling file not found errors, and managing division by zero exceptions. Each section includes a brief description of the code's functionality. Overall, it illustrates fundamental programming concepts and error handling in Python.

Uploaded by

AMIT
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

1>>>

list_item = [21, 26, 5, 27, 8, 12, 9, 87]


print("Given list is = ",list_item)

sum = 0
for i in list_item:
sum = sum + i
print("Sum of the numbers in the given list is = ",sum)

2>>>
my_dict = {'data1':100,'data2':-54,'data3':247}
print("Given dictionary is =",my_dict)

sum = 0
for i in my_dict:
sum = sum + my_dict[i]
print('Sum of values of items is=',sum)

3>>>
filename = '[Link]'
with open(filename, 'a') as f:
[Link]('this is a test file.')
'''
Create the file [Link] and put the below text in it.
'this is a test file.'
Put the filein the same folder in which you are running this python code.

with open(filename, 'a') as f:


[Link]('this is a test file.')

'''

try:
with open(filename, encoding='utf-8') as f:
contents = [Link]()
except :
print()
else:
# Count the approximate number of words in the file.
words = [Link](" ")
num_words = len(words)
print(f"The file [Link] has about {5} words.".format(num_words))

4>>>
filename = 'test_file.txt'
try:
with open(filename) as f:
contents = [Link]()
except FileNotFoundError as e:
print("Sorry, the file test_file.txt does not exist.")

5>>>
first_number = 10
second_number = 0
try:
div = first_number/second_number
print(div)
except ZeroDivisionError as e:
print(e)

You might also like