Contents
This notebook is based on "Think Python, 2Ed" by Allen B. Downey
https://greenteapress.com/wp/think-python-2e/
In [4]:
input_file = open( 'data/short-words.txt' )
print( input_file )
fin
is an acceptable name, but I opt for a more descriptive nameread( size )
Reads size
bytes of data. If size
is omitted or negative, the entire file is readn and return. Returns an empty string if the end of the file (EOF
) is reached.readline()
Reads a single line from the filewrite( a_string )
Writes a string to the fileclose()
Closes the file object and frees up any system resourcesfor
loop to read each line of the file
In [6]:
for line in input_file:
word = line.strip()
print( word )
strip
method removes whitespace at the beginning and end of a string
In [8]:
def has_no_e( word ):
result = True
for letter in word:
if( 'e' == letter ):
result = False
return result
input_file = open( 'data/short-words.txt' )
for line in input_file:
word = line.strip()
if( has_no_e( word ) ):
print( 'No `e`: ', word )
for
loop traverses each letter in the word looking for an e
uses_all
and uses_only
functions in the book are the samefor ... in
loop was usedfor
loop across the range of the length of the stringwhile
loop and maintain the current indexfor
loop maintain the indexwhile
loop can be used, but isn't as well suited since we know exactly how many times we need to run through the loop
In [3]:
fruit = 'banana'
# For loop
for i in range( len( fruit ) ):
print( 'For: [',i,']=[',fruit[i],']' )
# Recursive function
def recurse_through_string( word, i ):
print( 'Recursive: [',i,']=[',fruit[i],']' )
if( (i + 1) < len( word ) ):
recurse_through_string( word, i + 1 )
recurse_through_string( fruit, 0 )
# While loop
i = 0
while( i < len( fruit ) ):
print( 'While: [',i,']=[',fruit[i],']' )
i = i + 1
e
function, test using words that have an e
at the beginning, middle and end. Test long and short words (including the empty string).words.txt
and prints only the words with more than 20 characters (not counting whitespace). (Ex. 9.1 on pg. 84)has_no_e
function to a function called avoids
that takes a word and a string of forbidden letters. It should return True
if the word does not contain any of the forbidden letters and False
if it does. (Ex. 9.3 on pg. 84)uses_only
that takes a word and a string of letters, and returns True
if the word contains only letters in the list. (Ex. 9.4 on pg. 84)