Hannan
Hannan

Reputation: 1191

What is value of 'if not' in the code?

I'm learning Python and a bit confused what if not doing in the below code? I presume if not is like else statement. But it turns out I'm wrong. What is the value of if not exists in this code? Also another naive question, the variable exists is defined within a for loop, why is it available globally?

import scrabble
import string

for letter in string.ascii_lowercase:
    for word in scrabble.wordlist:
        exists = False
        if letter * 2 in word:
            exists = True
            break
    if not exists:
        print(letter)

print(exists) # Globally exists = True

Upvotes: 0

Views: 60

Answers (2)

Anton vBR
Anton vBR

Reputation: 18916

Here are some explanations:

import string

# let's create our own wordlist
wordlist = ["cat","moose"]

# Loop all letters from a-z
for letter in string.ascii_lowercase:
    # Inner-loop all words in wordlist
    for word in wordlist:
        # Start with exists = False
        exists = False
        # If letter is repeated break the inner loop and set exists = True
        if letter * 2 in word:
            exists = True
            break
    # Check if exists is False (which it is if double letter didn't exist in any word)
    if not exists:
        print(letter)

# This will print the last exists value (True if 'z' is doubled in any word else false)
print(exists)

Since the only letter that is repeated in any of the words in wordlist is 'o': All letters except 'o' is printed out followed by a False

a
b
c
d
...
False

BTW, you can get the same result with this code snippet:

import string

doubleletters = []
wordlist = ["cat","moose"]

# Loop through wordlist and extend the doubleletters list
for word in wordlist:
    doubleletters.extend(i[0] for i in zip(word,word[1:]) if len(set(i)) == 1)

print('\n'.join(i for i in string.ascii_lowercase if i not in doubleletters))

Upvotes: 1

A.J. Uppal
A.J. Uppal

Reputation: 19264

In python not flips the value of a boolean (true or false) expression. if not x can be read as "if x is false", so the statements inside the if block will execute if exists is equal to False, that is, if no repeat letters have been found.

Upvotes: 0

Related Questions