# MeanvalueFunction.py Copyright (c) 2006 Kari Laitinen
# http://www.naturalprogramming.com
# 2006-05-23 File created.
# 2006-05-23 Last modification.
# This program stores the given numbers in a list.
# The corresponding Java/C++/C# programs (e.g. MeanvalueMethod.java)
# use an array to store the given numbers. This program uses
# a list because lists are standard Python data structures for
# storing a set of similar data items.
# The following two functions use a variable which tells how
# many numbers are stored in the list. This is redundant information
# as a list always 'knows' the number of its list items.
# In file pythonfilesextra\MeanvalueFunctionAlternative.py
# you find another version of this program where this variable is
# not in use.
def ask_numbers_to_list( list_of_numbers ) :
number_of_given_numbers = 0
keyboard_input_is_numerical = True
while keyboard_input_is_numerical == True :
try :
print " Enter a number:",
number_from_keyboard = float( raw_input() )
list_of_numbers.append( number_from_keyboard )
number_of_given_numbers += 1
except :
keyboard_input_is_numerical = False
return number_of_given_numbers
def calculate_mean_value( list_of_numbers,
number_of_numbers_in_list ) :
calculated_mean_value = 0
sum_of_numbers = 0
for number_index in range( number_of_numbers_in_list ) :
sum_of_numbers = sum_of_numbers + \
list_of_numbers[ number_index ]
if number_of_numbers_in_list > 0 :
calculated_mean_value = sum_of_numbers / number_of_numbers_in_list
return calculated_mean_value
# The main program begins.
list_of_numbers = []
print "\n This program calculates the mean value of" \
"\n the numbers you enter from the keyboard." \
"\n The program stops when you enter a letter.\n"
number_of_numbers_read = ask_numbers_to_list( list_of_numbers )
mean_value = calculate_mean_value( list_of_numbers,
number_of_numbers_read )
print "\n The mean value is: %f" % mean_value