[Tutor] Shorten Code.

Alan Gauld alan.gauld at btinternet.com
Fri Nov 18 10:01:41 CET 2011


On 18/11/11 08:16, Mic wrote:

> What if I don’t write the same line of code more than once, but I write
> similiar lines more than once. Is that okay? Ler
> For example:
> value="green”
> value_1=”green”

If you had a lot of these you could shorten it with a loop (BTW the 
English term in programming terminology is "loop" not "sling" ;-)

for var in [value,value_1]:
     var = "green"

But you need to have already created the variables somewhere and unless 
there is a big list its not usually worth while.

One other trick you can use for this specific type of assignment is

value = value_1 = "green"

But it gets a bit unreadable for long lists of names.

> click=-1
> click1=-1
> click2=-1

Same here, but imagine it had been:

click=-1
click1= 2
click2=-1


And here you are changing both name and value.
The best abbreviation here is probably tuple
expansion:

click, click1, click2 = -1,2,-1

 > Do you have any general tips on how to make
> your code shorter?

Shorter is not necessarily better. Clarity is far more important and you 
should always consider whether tricks like those above are helping or 
hindering clarity. Only use them if they make your code easier to read. 
(Also they all make debugging slightly harder so you should think about 
that too)

HTH,
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list