Rize S. answered 03/23/23
Senior IT Certified Trainer, IT Developer & DBA Administrator
# Solution
#i. Writing a function to read the input file
def read_input_file():
try:
file = open('input.txt', 'r')
line = file.readlines()
v0 = float(line[0].split(' ')[1])
t_list = []
for i in range(2, len(line)):
t_list.append(float(line[i]))
file.close()
return v0, t_list
except FileNotFoundError:
print('File not found!')
# ii. Writing a function to create a file with two nicely formatted columns
def create_file(v0, t_list):
try:
file = open('output.txt', 'w')
t_list.sort()
for t in t_list:
y = v0*t - 0.5*9.81*t*t
file.write(str(t) + "\t\t" + str(y) + "\n")
file.close()
return
except FileNotFoundError:
print('File not found!')
# iii. Writing a test function
def test_function():
v0 = 3.0
t_list = [0.15592, 0.28075, 0.36807889, 0.35, 0.57681501876, 0.21342619, 0.0519085, 0.042, 0.27, 0.50620017, 0.528, 0.2094294, 0.1117, 0.53012, 0.3729850, 0.39325246, 0.21385894, 0.3464815, 0.57982969, 0.10262264, 0.29584013, 0.17383923]
v0_read, t_list_read = read_input_file()
if (v0 == v0_read) and (t_list == t_list_read):
print('Test Passed!')
else:
print('Test Failed!')
# iv. Writing a function for handling exceptions
def exception_handling():
try:
file = open('input.txt', 'r')
except FileNotFoundError:
print('File not found!')
# Calling the test function
test_function()