'if random.choice(x) = input(y)' doesn't execute the code below it
I'm new to coding and was having difficulty with a part of a program I made, here it is:
import random with open ("sowpods.txt") as txt: words = txt.readlines() word = random.choice(words) print(word) user_word = input("Word : ") if user_word == word: print("You guessed correctly")
"sowpods.txt" is a file with words in it. I want the program to print "You guessed correctly" when the user guesses "word" correctly. However, nothing is printed. How can I fix this?
Thank you. :)
If this is the content of
Then this code:
with open ("sowpods.txt") as txt: words = txt.readlines()
will fill the list
words like this:
['fakher \n', 'mokadem\n', '\n']
Because even if you don't see them, '\n' and '[[space]]' are characters saved in the file, just like any other characters. When you use
print(word) (or any other command or file reader to view the file content), print will interpret the new line and you will not distinguish the trailing spaces in the commandline.
strip removes whitespaces (leading and trailing) from the string, and the comparisons will not fail because of extra white spaces.
words = [word.strip() for word in txt]
Update: No need to call readlines in the list comprehension.
import random with open('sowpods.txt') as txt: for line in txt: print(line) word = random.choice(line.split()) user_word = input('guess a word from above line: ') if user_word == word: print('You guessed correctly') else: print('better luck next line')
This might work:
import random with open("sowpods.txt", "r") as fp: words = set(word.strip() for word in fp.readlines()) word = random.choice(words) guess = "Bork" while guess != word: guess = input("word: ") print("you guessed correctly")
- it sounds like you've guessed incorrectly every time
readlines()returns a list of strings with trailing newline characters, the input won’t match.
- I think
readlinesreturns all the lines with a trailing newline character
\n(except the last line if the file doesn't end with a newline) and
- change it to
if user_word.strip() == word.strip():the first strip isn't strictly necessary, but if the user accidentally typed a space and the start or end of their input, you probably don't want to disqualify them immediately for that
- in your code, you were reading all lines i.e list of lines .....so you could not select an individual 'word' .... hence use split()