Julian Lachniet Julian Lachniet - 4 months ago 9
Python Question

Adding while loop to script causes errors on input

I'm writing some code to play Hangman (Python 3.5.2). I wan't my code to run forever, e.g with

while 1 < 2:
, but I start getting syntax errors on statements that work fine without the
while
. Here is my code:

with open('dictionary.txt') as f:
words = f.read().splitlines()
alphabet = 'abcdefghijklmnopqrstuvwxyz'
words2 = ''
alphabetCount = []
guesses = []
input = input('Input: ')
for x in range(0, len(words)):
valid = True
if len(input) == len(words[x]):
for y in range(-1, len(input)-1):
if input[y] != words[x][y] and input[y] != '_':
valid = False
if valid:
words2 = words2 + (words[x])
for x in range(0, 26):
alphabetCount.append(0)
for x in range(0, len(words2)):
alphabetCount[alphabet.index(words2[x])] = alphabetCount[alphabet.index(words2[x])] + 1
for z in range(0, 26):
if max(alphabetCount) != 0 and (alphabet[alphabetCount.index(max(alphabetCount))]) not in input:
guesses.append(alphabet[alphabetCount.index(max(alphabetCount))])
alphabetCount[alphabetCount.index(max(alphabetCount))] = 0
print (guesses)


Essentially, I want to loop it like this:

while 1 < 2:
with open('dictionary.txt') as f:
words = f.read().splitlines()
alphabet = 'abcdefghijklmnopqrstuvwxyz'
words2 = ''
alphabetCount = []
guesses = []
input = input('Input: ')
for x in range(0, len(words)):
valid = True
if len(input) == len(words[x]):
for y in range(-1, len(input)-1):
if input[y] != words[x][y] and input[y] != '_':
valid = False
if valid:
words2 = words2 + (words[x])
for x in range(0, 26):
alphabetCount.append(0)
for x in range(0, len(words2)):
alphabetCount[alphabet.index(words2[x])] = alphabetCount[alphabet.index(words2[x])] + 1
for z in range(0, 26):
if max(alphabetCount) != 0 and (alphabet[alphabetCount.index(max(alphabetCount))]) not in input:
guesses.append(alphabet[alphabetCount.index(max(alphabetCount))])
alphabetCount[alphabetCount.index(max(alphabetCount))] = 0
print (guesses)

Jim Jim
Answer

The problem occurs because you mask the built-in function input() with the assignment:

input = input('Input: ')

For one iteration, this will work just fine because you're not calling input() again. Doing it more than once though will use a value of input that is masked, in your case with a value of type str; calling a str value will result in a TypeError.

Change the name to something different, like:

my_input = input('Input: ')

for the error to leave, make sure you change it throughout your code.

Remember to never mix user defined names with built-in function names because you'll get weird behavior.