Abstraction
Abstraction lets the programmer group a bunch of statements together into functions.
text = 'This is a string'
result = 0
text = text.replace(' ','')#get rid of spaces
for char in text:# now count the characters
result += 1
>>>result
13
Now instead of typing all this code out again the next time we need to count the number of characters in a string we could put it in a function like this.
#countChars.py
def countchars(string):
'''This is a program that counts the number of characters in a sentence
and returns the result'''
result = 0
string = string.replace(' ','')
for char in string:
result += 1
return result
Now when we need to count the number of chars in a string we do this.
text = “Your mother was a hamster and your father smelt of elderberry”
print countChars(text)
51
By putting your comments directly after the def statement you automatically create a doc string which can be accessed like this.
>>> countChars.__doc__
'This is a program counts the number of characters in a sentence and returns the result'
>>>