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

javascript - Confirm a form & display message if form is valid with JQuery -

Retrieving ETA (estimated time of arrival) with Google Distance Matrix API and public transit as transport mode -

ionic framework - Meteor - Error: Failed to execute 'insertBefore' on 'Node' -