Python loop - help me understand -


i have python generate random code, in case, "lucy", , prints follows:

l lu luc lucy 

i don't understand how works, can explain?

import sys mysterystring = sys.argv[1] print("~ testing mysterystring = {} ~".format(mysterystring))  #above code provided me  charcount = "" mysterychar in mysterystring:     charcount = charcount + mysterychar     print(charcount) 

why charcount initialized outside loop? why print characters way does?

the reason why charcount initialized outside of loop because of scope.

a variable defined in main part of body belongs "global" scope. means can accessed else throughout file.

but variable defined inside function/loop "local" function. means exists , accessible point @ defined until end of function.

when use assignment operator (=) inside function, default behavior create new local variable – unless variable same name defined in local scope.

so essentially, when declare inside of loop demonstrated below. re-initalizing variable = "" each time loops through why prints out 1 character @ time.

i.e.

"" + "l" reintialize charcount = "" "" + "u" etc 

variable declared outside loop:

enter image description here

variable declared inside loop:

enter image description here


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -