[Tutor] Understanding what the code does behind the scenes

Alan Gauld alan.gauld at btinternet.com
Fri Oct 16 15:04:47 CEST 2009


"Katt" <the_only_katala at verizon.net> wrote


>> def colorPrint(strings):
>>    for string in strings:
>>         textcolor(string[1])
>>         print string[0],
>>
>
> In the above function please let me know if I am correct in my 
> interpretation.
> The first line of course would be the defining of the function and puting 
> something in the parenthesis indicates that you will be passing a value 
> to this function.

Correct

> The second line says that for each string in the colorPrint statement 
> check to see what the color code is.

no, it assigns each item in the input value strings to a local
variable string

> The third line says that if it detects a ",#" to change it to a color 
> based on the textcolor function in the WConio module.

no, it pulls out the second value from the string tuple passed in and
applies it via the wconio function textcolor().

> The fourth line puzzles me though.  I think it says that when the 
> textcolor returns the zero that it doesn't print the None?  I am not sure 
> though.

No it selects the first item from the string tuple and prints it.

So for

colorPrint(("here is a ",15), ("warning", 5))

the loop first of all sets string to the tuple ("here is a ",15)
it then extracts the color, 15, by using string[1] and applies it via 
textcolor()
it then extracts the first tuple element "here is a " and prints it.
the loop then sets string to the second tuple ("warning", 5)
it then extracts the color, 5, by using string[1] and applies it via 
textcolor()
it then extracts the first tuple element "warning" and prints it.

So for this example we could replace the function call with

textcolor(15)
print "here is a ",
textcolor(5)
print "warning",

> Could you let me know if I have the right idea?

Not quite, you need to revise on tuples and how to index
their contents and for loops. In my tutorial you will find the
tuple info in the Raw Materials topic and the for loops in
the Loops topic.

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




More information about the Tutor mailing list