Reputation: 31
Learning how to code in Python (again) for which I am working on this simple word guessing game. The code (written below) is from a YouTube video I have been following (freeCodeCamp's Learn Python - Full Course for Beginners [Tutorial]).
What I don't understand is how not(guesses_complete)
logically makes sense in this is code.
From my understanding, the code implies that the while
loop executes and continues as long as the player's guess is not the secret word and the boolean value of guesses_complete
is True (because the initial value of guesses_complete
is False, so not()
means the value has to be True to execute).
But the initial value of guesses_complete
is set to False, so the while
loop shouldn't execute at all.
# The player gets 3 chances to guess the secret word
# If guessed correctly within the given chances, the player wins
# If guessed incorrectly and there are no more chances, the player loses
secret_word = "Red"
guess = ""
counter = 0
guess_limit = 3
guesses_complete = False
while guess != secret_word and not(guesses_complete):
if counter < guess_limit:
guess = input("Enter guess: ")
counter += 1
else:
guesses_complete = True
if guesses_complete:
print("Loser")
else:
print("Winner")
The code works written as it is, but I don't know why. I'm pretty sure it's just that my understanding of the not()
operator is weak. I'd highly appreciate it if someone clears this up for me.
Upvotes: 2
Views: 9774
Reputation: 198
The way not()
works is indeed the contrary to what you are thinking. not(guesses_complete)
in this case would be the same as using guesses_complete == False
. If guesses_complete == False
, this statement would return True
, meaning the while loop should be executed. This same happens with not(guesses_complete)
when the value of guesses_complete
is set to False
.
Upvotes: 3
Reputation: 160
The not keyword is a logical operator. The return value will be True if the statement(s) is not True and the return value will be False if the statement(s) is not False. Source. In the code above, we want the user to play until he has some guesses remaining i.e., we want the loop to execute if guesses_complete
is False.
Upvotes: 1
Reputation: 301
The not
key word inverts a boolean (true or false value), turning True
into False
. What this means is that if you want a piece of code to run if a variable is false than by using not
you can make that run. Example to help:
finished_game = False
while not finished_game:#While the game isn't finished
#run game code
Does that make sense? In my experience the not
keyword means you can use False
as True
.
Hope that helps somewhat.
Upvotes: 0
Reputation: 315
I believe the not() operator evaluates to the opposite. So if it set to false it switches the variable too true, and if the initial variable value is true the not() sets it too false. I think of it as an opposite day function.
Upvotes: 1