Python 19 | Calculating Average Exercise
Just got another simple exercise from ChatGPT today where A user can add numbers to a list and then an average is calculated ๐
# This Python program calculates the average of list of numbers
def get_user_numbers(list):
counter = 1
print('Add as many numbers as you want. type "done" when finished')
while True:
user_input = input(f'Number {counter}: ')
if user_input == 'done':
print('you finished adding numbers.')
break
try:
list.append(float(user_input))
counter += 1
except ValueError:
print('Please enter a Number.')
def sum_up(list):
sum = 0
for number in list:
sum = sum + int(number)
return sum
def average(list):
# Calculate the sum of all the numbers in the list.
sum = sum_up(list)
number_of_elements = len(list)
average = sum/number_of_elements
return average
def main():
# Create a list of numbers (you can define it in your code).
numbers_list = []
get_user_numbers(numbers_list)
# Calculate the average by dividing the sum by the number of elements in the list.
result = average(numbers_list)
# Print the calculated average.
print(f'the average is {result}.')
if __name__ == '__main__':
main()
ย