Stack Overflow Asked by SH12030 on November 24, 2021
I am new to stackoverflow so I apologise if I have not formatted my code correctly. In my hangman game, the while loop is supposed to stop when count==0. However, it stops when count=-2. What have I done wrong and how can I solve it?
Thanks!
word = 'hello'
dict1 = {}
import time
def words(words):
count = len(words) + 3
lines = []
for i in words:
lines.append('_')
print('It is a', len(word), 'letter wordn',
'You have ', count, 'guesses!')
time.sleep(1)
print('The first word is: ', words[0])
while count > 0:
for i in words:
count -= 1
time.sleep(1)
answer = input('please input a letter')
if answer=='':
print('This is incorrect. You have ',count,' goes left')
elif answer == '{}'.format(answer) in word:
dict1.setdefault(answer, 0)
dict1[answer] = dict1[answer] + 1
for k, v in dict1.items():
if dict1[answer] > 1:
print('No duplicates! You have ', count, 'goes left')
else:
for i in range(0, len(word)):
if word[i] == answer:
lines[i] = answer
print( 'n Well done! You have ', count, 'goes left!')
hangwords = ''.join(map(str, lines))
print(hangwords)
if hangwords == words:
print('You have won! You had', count, 'goes left!')
return hangwords
else:
print('This is incorrect! You have', count, 'goes left')
if count==0:
print('You have failed. The word was '+word)
exit()
print(words(word))
You have a two layer loop going on, that's causing the issue.
Check out your word to guess : "hello". It's length is 5. You have set the limit to 8. The loop is running 10 time & does not have any if conditions or a break statement.
8 - 10 = -2.
Answered by Samridh Tuladhar on November 24, 2021
a) use break
and not exit()
b) the if statement needs to be inside the for loop. as you have it now, it is checked after the for loop and it already got below 0 while the for loop is running
Answered by toydarian on November 24, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP