[Tutor] Alternative to for/while loop
Alan Gauld
alan.gauld at yahoo.co.uk
Tue Oct 25 04:19:53 EDT 2016
On 25/10/16 02:38, Bryon Adams wrote:
> question. The book I'm working through hasn't covered using flow control
> yet so I'm thinking there should be a way to do this without the for
> loop I used, but I'm at a loss here.
Thee are ways to do it without using a for loop but they are
all more advanced rather than simpler. (And they are less
"good" than the simple program you have written in that they
are unnecessarily complicated)
> So far the book has covered: lists,
> strings, numerical types (float, integer, etc), methods, tuples,
> importing modules, boolean logic, and mathematical operators.
You used a list comprehension in your solution, was that
covered as part of lists? If not how did you find it?
> nums = input('Enter some numbers separated by commas: ')
> nums = [float(i) for i in nums.split(', ')]
> print((sum(nums)) / len(nums))
That's about as simple as it gets except for the surplus
of parens in the last line:
print(sum(nums) / len(nums))
is sufficient.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list