Reputation: 625
Instead of printing each sentence, i want to return it! But if i do return it will end the loop.
def printDeck(fileName):
infile = open(fileName,'r') # open file
contents = infile.readlines() # read file
infile.close() # close file
for sentence in contents: # for each line in contents
sentence = sentence.split() # eliminate spaces and turn into a list
sentence[0], sentence[1] = sentence[1], sentence[0] # reverse order
print('{0} of {1}'.format(sentence[0],sentence[1]))
This is the exercise im trying to solve:
Write a function called printDeck()which takes oneparameter, a file name. The function should read in the contents of the file and print it in the format shown below. For example: if 'Hearts 6' is read in from the file, the string should be printed as '6 of Hearts'. The function should return the contents of the file in list form.
Upvotes: 0
Views: 119
Reputation: 87134
Write printDeck()
as a generator that yields the strings. Then iterate over that generator to print.
You do not need to read the whole file into memory in one go with readlines()
. If you open the file in a context manager (using with
) then you do not need to worry about closing it - the context manager will ensure that that happens.
Reversal of the first 2 words of the sentence can be done with str.format()
without bothering to actually swap the order after splitting.
You can write your code as a generator and more clearly like this:
def read_deck(fileName):
with open(fileName) as f:
for sentence in f:
yield '{0[1]} of {0[0]}'.format(sentence.split())
>>> for s in read_deck('deck.txt'):
... print(s)
If you want all of the strings in one list, call list()
on the generator:
>>> deck = list(read_deck('deck.txt'))
Upvotes: 0
Reputation: 3489
You can only return a value in a function once. But you can append your generated strings to mylst
and then return mylst
after the loop is finished.
mylst = []
for sentence in contents: # for each line in contents
sentence = sentence.split() # eliminate spaces and turn into a list
sentence[0], sentence[1] = sentence[1], sentence[0] # reverse order
mylst.append('{0} of {1}'.format(sentence[0],sentence[1]))
return mylst
Upvotes: 1
Reputation: 7293
Maybe you want to create a generator:
def printDeck():
"""return contents of file as string"""
...
for sentence in contents: # for each line in contents
...
yield '{0} of {1}'.format(sentence[0],sentence[1])
Then use it as
deck = printDeck()
deck1 = next(deck)
deck2 = next(deck)
etc.
or
for deck in printDeck():
print(deck)
Upvotes: 4
Reputation: 77880
You cannot return a single sentence and stay in the loop. You can return a list of the swapped phrases like this:
mylst = []
for sentence in contents: # for each line in contents
sentence = sentence.split() # eliminate spaces and turn into a list
phrase = sentence[1] + " of " + sentence[0]
mylst.append(phrase)
return mylst
Upvotes: 0