Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialYosef Fastow
18,526 PointsHow I answered the Extra credit for the letter game app.
Instead of putting every word on a different line in the text file I put it on one line and than made it into a list in the program. Is there a reason to loop through the list instead of how I did it or are both of them good options?
def pick_fruit():
""" Picks a fruit for our secret word from a outside file. """
txt_list = open('hangman.txt', 'r')
fruits = txt_list.read()
fruits = fruits.split(', ')
fruit = random.choice(fruits)
txt_list.closed
return fruit
3 Answers
Chris Freeman
Treehouse Moderator 68,441 PointsNice solution! Creating a Comma Separated Value (CSV) file for your data is a valid alternative way to go.
There is a Python package for reading and writing CSV files. Check out CSV.
Iain Simmons
Treehouse Moderator 32,305 PointsShiny!
Here's mine:
I made it so the user has the option of specifying the file with the words (either on the command line or after importing the script into the Python shell/REPL).
Also varies the number of allowed guesses based on the word length.
Freda Wan
6,391 PointsHere is my code for using the open() function.
with open('words.txt') as f:
words = f.readlines()
words = [x.strip() for x in words]
words = [y.strip(',') for y in words]
f.close()
I realized that there are 2 approaches: 1) we could open the file, read the list, use random.choice() to pick a secret_word, and close the file. 2) we could open the file, read the list, load the whole list as a variable in the program, close the file, and then use random.choice() to pick a word from that list.
I assume that the first approach is better when dealing with a larger list of words. Any views welcome. Thanks!
Yosef Fastow
18,526 PointsYosef Fastow
18,526 PointsThanks. I will.