(Python 3 only) Code a program that contains a 4 element list, where each elemen
ID: 3576556 • Letter: #
Question
(Python 3 only)
Code a program that contains a 4 element list, where each element is a float value that represents gpa in a class. Populate each element from user input. Print out the elements of the list and display the average gpa to 2 places after the decimal point.
Additional specifications are as follows:
Do not use global variables
Your program should contain 2 functions:
main
Declare the 4 element float list in main
Populate each element of the list by invoking the get_gpa function.
Print out each element of the list
Calculate average of the values maintained in the list and display to 2 places after the decimal point
get_gpa
Ask the user to enter gpa
Ensure that it is:
Numeric
Is numeric and within the range 0-4 (Both 0 and 4 are valid values)
Return gpa from this function
(Python 3 only)
Code a program that contains a 4 element list, where each element is a float value that represents gpa in a class. Populate each element from user input. Print out the elements of the list and display the average gpa to 2 places after the decimal point.
Additional specifications are as follows:
Do not use global variables
Your program should contain 2 functions:
main
Declare the 4 element float list in main
Populate each element of the list by invoking the get_gpa function.
Print out each element of the list
Calculate average of the values maintained in the list and display to 2 places after the decimal point
get_gpa
Ask the user to enter gpa
Ensure that it is:
Numeric
Is numeric and within the range 0-4 (Both 0 and 4 are valid values)
Return gpa from this function
Explanation / Answer
def get_gpa():
n = input("Enter gpa:")
try:
n = float(n)
#break
except ValueError:
print("You should only enter a float value.")
return get_gpa()
#return -1
if(n<0 or n > 4):
print("You can only enter value between 0 and 4.")
return get_gpa()
#return -1
#print n
return n
def main():
lt = [0,0,0,0]
s = ""
sm=0
for i in range(0,4):
#print i
lt[i] = get_gpa()
#print i
s = s + str(lt[i])+" "
sm+=lt[i]
print(s)
sm = sm/4
print("%.2f" %sm)
main()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.