I don't know if you are required to used the array
library, but I don't see a use for it here. Do you want to use it to be more efficient? If that's the case then also see 2 In python you can set a variable's values as an empty list
, so you can use it as one, further in your code. For example:
l = []
for i in range(3):
l.append(i)
print(l) # prints [0, 1, 2]
So in your case you can do this:
1)
print("\t\t\tEnter Marks of the following subjects out of 100 :\n")
marks = []
for x in range(5):
marks.append(float(input("Enter marks of {0} subject : ".format(x+1))))
print("Calculating...")
sum = 0
for mark in marks:
sum += x # if x is a float in any of the loops then the sum will be a float.
print("Total Marks (Out Of 500) = ", sum)
Or if you are required to use the array
package:
2)
import array
marks = array.array("f")
for i in range(5):
marks.append(float(input("Enter marks of {0} subject : ".format(i+1))))
sum = 0
for mark in marks:
sum += mark
print("Total Marks (Out Of 500) =", float(sum)) # prints the float value of the sum
This doesn't seem like it needs to be that efficient and you probably wont be getting the program any faster by using the array
library. Use the timeit
module to see which program runs faster.
import timeit
timeit.timeit(stmt="""import array
in_marks = [80, 80.2, 80, 80, 80]
marks = array.array("f")
for i in range(5):
marks.append(float(in_marks[i]))
sum = 0
for mark in marks:
sum += mark
# print("Total Marks (Out Of 500) =", float(sum)) # prints the float value of the sum""", number=1000000)
# This took 1.7964587999999821 seconds to run 1.000.000 times
# And 0.19057900000007066 to run 100.000 times
And this is without the library:
import timeit
timeit.timeit(stmt="""
in_marks = [80, 80.2, 80, 80, 80]
marks = []
for i in range(5):
marks.append(float(in_marks[i]))
sum = 0
for mark in marks:
sum += mark
# print("Total Marks (Out Of 500) =", float(sum)) # prints the float value of the sum""", number=100000)
# This took 1.271052900000086 seconds to run 1.000.000 times
# And 0.12818579999998292 seconds to run 100.000 times
Python seems to be faster without it, because the program doesn't do any heavy calculations, so by importing the library you lose some time and don't gain any in the long run.
To remove the ending numbers in you code you can round()
the float to 2 decimal points like @Laurent Bristiel suggested.