Reputation: 3
I'm using Python and am trying to make a small game for a college assignment. I am trying to print a randomly selected word from a few external text files (with harder words in each one) and have it displayed for 2 seconds, the word then disappears and the user has to spell it. At the moment my program just displays a random letter from the text file and no whole words.
print ("""Welcome to the Spelling Game
What difficulty do you want to play?
Easy, Medium or Hard?""")
strDifficulty = input().upper
if strDifficulty is ("EASY"):
with open ('EASY.txt', 'r') as f:
(chosen) = f.readlines()
if strDifficulty is ("MEDIUM"):
with open ('MEDIUM.txt', 'r') as f:
(chosen) = f.readlines()
if strDifficulty is ("HARD"):
with open ('HARD.txt', 'r') as f:
(chosen) = f.readlines()
import random
x = ('chosen')
print (random.choice (x))
Upvotes: 0
Views: 63
Reputation: 2019
I have made some modifications to your code.
print ("""Welcome to the Spelling Game
What difficulty do you want to play?
Easy, Medium or Hard?""")
strDifficulty = input().upper()
if strDifficulty=="EASY":
with open ('EASY.txt', 'r') as f:
chosen = f.readlines()
if strDifficulty=="MEDIUM":
with open ('MEDIUM.txt', 'r') as f:
chosen = f.readlines()
if strDifficulty=="HARD":
with open ('HARD.txt', 'r') as f:
chosen = f.readlines()
import random
print (random.choice (chosen))
Upvotes: 0
Reputation: 9231
There's multiple issues with your code why it would print out a single character:
strDifficulty = input().upper
does not uppercase input from the command line. It will read something you type, which is a string (str
in python) and assign the method upper
of that string to strDifficulty
. What you're likely looking for is strDifficulty = input().upper()
(the extra parentheses will call the method upper, returning an uppercased version of what is read from standard in.
x = ('chosen')
is assigning the string 'chosen'
to x, not the value of the variable chosen
. You might have meant x = chosen
, assigning the value of chosen
to x
.
print (random.choice(x))
isn't far off, but will choose a random element from x
. As x
is always the string 'chosen'
, you'll likely get one of those letters. You could simply remove the line x = ('chosen')
and call print(random.choice(chosen))
.
There's plenty more to be said about your piece of code, but let's start here :)
Upvotes: 2