Here is a simple program that can average a list of numbers. I wrote this to introduce someone to the language that we all use and love. :D The program may be simple, but it shows how easily a simple but useful program can turn out to be.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | def main():
while True:
try:
string = raw_input('What numbers should I average? ')
words = string.split()
numbers = map(float, words)
average = sum(numbers) / len(numbers)
print 'The average is', average
raw_input('Press enter to quit.\n')
return
except:
print 'ERROR: I can only take numbers!'
if __name__ == '__main__':
main()
|
Want to introduce someone to Python? You might want to try this program. It is simple and should not be that difficult to understand. It might be a bit more than a "Hello World" program, but at least this one will do something useful.
split's default seperator is whilespace.
So little simplification can be done after try block (assuming this is easy to explain in an introduction).
Question. Are there tab requirements when I type this into the compiler?
Answer. The source must have the general tabbing as seen. Try downloading the source and executing it that way.
Version 2.
About. Version 2 may seem to be somewhat more complicated but is also a good introduction to what can be done in Python. The recipe should probably be used only with more advanced programmers.
Thanks for your post. I am measuring ambient light with a Raspberry Pi and would like to execute only on the last say 10 samples. I am controlling a chicken door that will open and close with the sun, but do not want to move door when say something blocks the sensor briefly. How would you average the the last 10 samples taken instead of using input from a keyboard as in your example? I am fairly new to python. I was thinking of loading realtime samples into some sort of FIFO or FILO stack or array, then averaging. Thanks.