[Tutor] Alternative to for/while loop

Bryon Adams bryonadams at openmailbox.org
Tue Oct 25 15:29:54 EDT 2016


On 10/25/2016 4:31 AM, Wolfgang Maier wrote:
> On 25.10.2016 10:10, Ben Finney wrote:
>> Bryon Adams <bryonadams at openmailbox.org> writes:
>>
>>>     I'm very new to python so please forgive what may be a beginner
>>> question.
>>
>> Welcome! You are in the right place for asking beginner Python questions
>> :-)
>>
>>> I'm thinking there should be a way to do this without the for loop I
>>> used, but I'm at a loss here.
>>
>> Thank you for posting your code, and a specific question about it.
>>
>> Why do you think there “should be a way to do this without the for
>> loop”? If you want to do something with a collection of items, a ‘for’
>> loop is quite a normal way to do that.
>>
>> (In fact you have not used a for loop, you have used a different syntax
>> called a “list comprehension”. But the main question remains unchanged:
>> Why would you expect to not need some kind of iteration like a ‘for’?)
>>
>
> You cut off a relevant part of the orignal question:
>
>> The book I'm working through hasn't covered using flow control yet ...
>
> and I agree that it would be a strange book that requires you to use for
> loops or comprehensions before they got introduced.
>
> A possible explanation is that, as you are saying, the book uses
> python2. In python2, input does not return a string, but evaluates the
> input from the user to produce different types of objects. So in Python2:
>
>>>> nums = input('Enter some numbers separated by commas: ')
> Enter some numbers separated by commas: 1,2,3,4
>>>> nums
> (1,2,3,4)
>>>> type(nums)
> <type 'tuple'>
>
> So the task is actually easier in Python2, BUT:
> there is a good reason (safety) why that behavior of input got removed
> in Python3. In general, it is a really bad idea to evaluate arbitrary
> input as python code. Your solution using a comprehension (or a for
> loop) to convert string parts to float explicitly is far better and the
> recommended approach nowadays.
>
> Best,
> Wolfgang
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

I should have mentioned, yes the book does use python2. I've been using 
python3 however when I do the exercises, range() was another function 
that changed but I was able to figure that one out =).

Thanks for the detailed explanation everyone, I appreciate it. I'll have 
to look up list comprehension, I'm not sure it was actually covered in 
the chapter to be honest and it sounds like the difference in python 
versions is why the author may not have covered it. I've got a bit of 
extra reading to do tonight!

Regards,
   Bryon


More information about the Tutor mailing list