Having both if() and for() statements in one liner

Ferrous Cranus nikos.gr33k at gmail.com
Tue Sep 17 09:21:01 EDT 2013


Στις 17/9/2013 4:00 μμ, ο/η Roy Smith έγραψε:
> In article <l19gdf$psh$1 at dont-email.me>,
>   Ferrous Cranus <nikos.gr33k at gmail.com> wrote:
>
>> o want to avoid having to type somehting like this:
>>
>> if person="George":
>> 	times in range(0, 5):
>>
>>
>> Why it gives me an error when i'm trying to write it like this:
>>
>>
>> if person="George" for times in range(0, 5):
>
> Step One when reporting a problem is don't just tell us you got an
> error.  Tell us what the error is.  Cut and paste the exact text of the
> full error message.
>
> Although, in this case, it's pretty easy to guess that it was a syntax
> error :-)
>
> I'm not sure where to start.  First, the '=' in 'person="George"' should
> be '=='.  In Python, '=' is used for assignment, '==' is used for
> equality testing.
>
> Next, if you want to use the 1-line version of 'if', you need a ':'
> after the condition.  Something like:
>
>      if person == 'George': print 'foo'
>
> but it's generally considered poor style to use 1-line if statements.
> Just write it on two lines:
>
>      if person == 'George':
>          print 'foo'
>
> They just discovered a huge newline vein in Montana and they're mining
> the things like crazy.  There's no shortage of them so feel free to use
> as many as you like.  They even get recycled.
>
> But, I'm not even sure you can put a 'for' statement as the body of a
> 1-line 'if'.  I've never tried it before, and my one experiment now got
> me a syntax error.  Even if it turns out to be legal and I just haven't
> got the details right, it's just The Wrong Thing To Do.
>


I just want to say tot he program that

that only run the for statement if and only if person=='George'

I dont see nay reason as to why this fails

perhaps like:

for times in range(0, 5) if person=='George':

but that fails too...
there must be written on soem way.





More information about the Python-list mailing list