0

I have a final exam coming up and this is the only question I am unable to answer correctly:

Question 4

word = 'off'
prev = ""
for letter in word:
    if prev == "";
        prev = letter
        out = ""
        continue
    elif letter == prev:
        prev = letter
        out = letter
        break
    else:
        prev = letter
        out = word[0]
print(out)

a) o
b) f
c) of
d) "" (the empty string)
e) none of the above

When I was trying to solve it I thought the answer was going to be "none of the above" because out is defined in local variable scope and would no longer exist out of each part of the if statement. When I ran the code in the compiler to check my answer I found that the correct answer is b. Can someone explain why the local variable scope allows this answer to be correct? Thank you in advance.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 3
    This problem is not related to variable scope: All variables live in the global scope, as there are no additional objects like functions or classes involved. (If the code was put in a function, names assigned within the function would have local scope.) I believe, the question is only about control flow and name bindings. – sammy Dec 07 '19 at 22:45
  • Read about [scopes-and-namespaces](https://docs.python.org/3/tutorial/classes.html#scopes-and-namespaces-example) – stovfl Dec 07 '19 at 22:53
  • 1
    Python doesn't have block scope; the `for` and `if` statements don't have their own scopes. – kaya3 Dec 07 '19 at 23:36

1 Answers1

0

Since the variable is not declared in a function or class, it is instead declared in the global scope.

You can read more about it here:

Daniel Jonsson
  • 3,261
  • 5
  • 45
  • 66
  • The code works just fine in a function or a class too. Python just doesn't have block scope at all. – kaya3 Dec 07 '19 at 23:34