#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    66
    Rep Power
    3

    Explain some code


    Hi again so I have this bit of code and it doesn't work but thats not my question what I am wondering is could somebody explain what the code is saying section by section

    Code:
    sentance = "the quick brown fox jumped over the lazy dog"
    
    characters = {}
    
    for characters in sentance:
        characters[character] = characters.get(character,0) +1
    thanks
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,929
    Rep Power
    481
    Code:
    # create a string and assign it to the variable   sentance
    sentance = "the quick brown fox jumped over the lazy dog"
    
    # create a new dictionary object, and assign it to the variable  characters
    # Why is {} a dictionary and not a set?  That's the rule.
    characters = {}
    
    #I've rewritten the for loop, fixing the spelling error.
    # a string is iterable.
    #This is a loop.  The code nested under the `for'
    #statement executes with the variable `character' assigned to each
    #item of the iterable in turn.
    for character in sentance:  #### was  for characters in sentance:
        print(character) # this "debugging" statement might help understand my prior explanation
        # expression + 1   adds one to the value of expression
        # get is a method of the dictionary class.
        # dictionaries have keys and values.
        # dictionary.get(key) returns the value associated with the key.
        # If the dictionary hasn't got an entry for the key, get(key,value) returns
        # value.  In this case the value 0 is an integer to which can be incremented.
        # OBJECT.ATTRIBUTE  is a python syntax to recover an attribute from an object.
        # dictionary[key] is a python syntax to access the value associated with the key.
        # In particular, on the left hand side of an assignment statement it sets the
        # the value of the key.
        characters[character] = characters.get(character,0) + 1
    
        # you got it!  Your code counts the occurrences of each letter in the string.
    
    print(characters) # display the result!
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    66
    Rep Power
    3
    thanks

IMN logo majestic logo threadwatch logo seochat tools logo