In: Computer Science
The attached numberpairs.csv file contains lines of comma-separated number pairs, e.g.
2.0,1
5.5,2
10,0
5.1,9.6
Expected Output:
2.0 divided by 1.0 is 2.0
5.5 divided by 2.0 is 2.75
10.0 divided by 0.0 error: denominator is zero!
5.1 divided by 9.6 is 0.53125
What is the file name I should save this under for the CSV file to run properly I keep getting an error when trying to run the code?
check out the solution.
-------------------------------------------------------
CODE :
# Python program - readCSVDemo.py
import csv
# divide function implementation
def divide(n1, n2):
# raise an exception
if(n2 == 0):
raise ZeroDivisionError("denominator is zero!")
# perform division and return result
result = n1/n2
return result
def read():
lst = [] # initialize a list
# open csv file with read mode
with open('numberpairs.csv','r')as f:
data = csv.reader(f) # read file contents
for row in data:
lst.append(row) # append each row to list
return lst # return the list
# main function
def main():
# function call
lst = read()
for line in lst:
# as divide function raise an exception, use try-except block
try:
# get each number from each line and convert it into float
n1 = float(line[0])
n2 = float(line[1])
result = divide(n1, n2) # function call
print(f'{n1} is divided by {n2} is {result}') # print result
except ZeroDivisionError as z: # exceptions are handled here
print(f'{n1} is divided by {n2} error: {z}') # print
accordingly
# main calls
if __name__ == "__main__":
main()
-------------------------------------------------------------------------
---------------------
OUTPUT :
================================