[Tutor] Shorten Code.
Dave Angel
d at davea.name
Fri Nov 18 15:39:05 CET 2011
On 11/18/2011 04:01 AM, Alan Gauld wrote:
> 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"
Um, that won't work. You typed that example too quickly.
....
Mic, the problem is not "shortening code," but making it more readable,
and easier to maintain. If you have a series of variables that hold
similar or identical values, or which are treated in consistent ways,
then you should probably make a list out of them. And that will
naturally shorten code like this.
student0 = 4
student1 = 3
student2 = 12
student3 = 11
Replace with
students = list((4,3,12,11))
Then if you want to deal with a particular student, you might do
student[2] = 5
But if you want to deal with the ith student, you could do
student[i] =
and if you want to do something with all of them:
for index, student in enumerate(students):
students[indes] += 65
There are plenty of more advanced methods that would make even that
simpler, but I'm trying to keep it simple.
--
DaveA
More information about the Tutor
mailing list