0

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
Hannan
  • 1,171
  • 6
  • 20
  • 39
  • 3
    No, it is an `if` statement, where the condition is `not exists`. Also, Python doesn't have block scope, so for-loops do not have their own scope. Read more about Python scope-rules [here](https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules) – juanpa.arrivillaga Dec 04 '17 at 17:59

2 Answers2

1

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))
Anton vBR
  • 18,287
  • 5
  • 40
  • 46
0

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.

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
  • More precisely, `not` can work on *any* type of object in Python. So, `not obj` returns `True` if `obj` is *falsey*, and otherwise it returns `False`. – juanpa.arrivillaga Dec 04 '17 at 18:03