[Tutor] Alternative to for/while loop

Bryon Adams bryonadams at openmailbox.org
Tue Oct 25 15:43:21 EDT 2016


On 10/25/2016 4:19 AM, Alan Gauld via Tutor wrote:
> 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.
>

     I had done a little bash, C, and Visual Basic so I figured a for 
loop would be a good way to do this (that's how I came to the idea of 
using 'for' anyway). This is my first effort since college to try and 
really learn some programming, was a hodge podge networking program and 
I didn't realise how useful or in demand some programming would be. If I 
remember correctly I was looking for how to do a for loop in python3 but 
I don't remember the terms I threw into DuckDuckGo (it definitely wasn't 
list comprehension). I believe I bookmarked it though. I ended up at a 
Stack Overflow page with instructions on how to do this.

     I'll have to skim through the chapter and see if I can find list 
comprehension, if not I'll check the back of the book for where it's 
mentioned. Wolfgang was on the money when suggesting the book was python2.

Regards,
   Bryon




More information about the Tutor mailing list