Reputation: 3
I run the code it works fine to the point it decrements the counter
for the first time but after that the value of counter
remain the same.
Can someone point what could be the cause of this? I looked at the code more than 10 times. Tried some different approaches, still nothing.
Code:
import random
import time
# GLOBAL VARIABLES
word_bank = ["january", "border", "image", "film", "promise", "kids", "lungs", "doll", "rhyme", "damage", "plants"]
guessed = []
word = random.choice(word_bank)
display = '_' * len(word)
counter = len(word)
secret_word = word
run = True
def welcome():
print('\t\t\t\t\t\t\t\t\t\t\tHello welcome to HangMan Game')
time.sleep(1)
print("The game is about to start")
print(f" Secret Word : {display}\n")
print('Start Guessing \n')
time.sleep(1)
def guessing(counter=counter):
print(secret_word)
guess = input('Enter your guess : ')
if guess in secret_word:
print(guess)
print('You Guessed it Right!')
guessed.append(guess)
elif guess not in secret_word:
print('You Guessed Wrong!')
counter -= 1
print(f'You Remaining guesses are {counter}')
return counter
for j in guessed:
if j[:] == secret_word and counter > 0:
print('You Won!')
elif counter == 0:
print('Your out of moves. You Lost!')
if __name__ == '__main__':
welcome()
while run:
guessing()
Upvotes: 0
Views: 140
Reputation: 45750
counter=counter
doesn't mean that the value of counter
will be automatically maintained. It means that if you don't pass an argument to guessing
, it will use the original value of counter
that you set at the top.
Since you're returning counter
anyways, just use the return value:
if __name__ == '__main__':
welcome()
current_counter = counter
while run:
# Reassign the new counter value, then use it the next time
current_counter = guessing(current_counter)
Note though, this will only work if guessing
always returns a counter
value. Currently though, some of your branches don't (like everything in for j in guessed:
). Failing to return a counter
value will lead to an error similar to:
TypeError: unsupported operand type(s) for -=: 'NoneType' and 'int'
Upvotes: 1