On 25.10.2016 10:10, Ben Finney wrote:
Bryon Adams <bryonad...@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@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to