0

I cannot figure out why the following statements dont work.

randomKey = random.choice(list(topic.keys()))
randomValue = random.choice(topic[randomKey])

current = "-" * len(randomValue) 
while current != randomValue: 
   (statements)
else:
   (statements)

However, if i alter the 1st line to

while current == randomValue:

the statement after 'else' executes correctly. Otherwise, the statement after 'else' does not execute. Any idea why what may be causing the strange behaviour? Full code has been excluded for it will run through this entire page.

3
  • There's no way we can do better than just wild guessing if you don't boil this down to a simple working example. Either the while condition is never true, or you have a break in there somewhere... Commented Nov 3, 2012 at 18:30
  • thank you, but i looked thru the entire code & there was no break keyword :( Commented Nov 3, 2012 at 18:43
  • do kindly view my edit. Was wondering if 'random' causes that strange behaviour ? Commented Nov 3, 2012 at 18:47

2 Answers 2

1

It is part of the Python grammar. From the documentation:

This [a while statement] repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates.

So in the first case, it must be that the while condition never evaluates to false, while in the second it eventually does. Note that explicitly breaking out of the loop will not execute the else clause.

Sign up to request clarification or add additional context in comments.

3 Comments

thank you, but i looked thru the entire code & there was no break keyword :(
do kindly view my edit. Was wondering if 'random' causes that strange behaviour ?
@brainsfrying: The answer is still the same. It is possible that your random choices are causing the condition to evaluate false in one situation and not in the other. Instead of using random, can you provide a deterministic example with a fixed value that always fails/succeeds?
0

else, when used with while, runs after the while expression evaluates to a falsy value if the while loop finishes by the expression being false, instead of being broken out of by a break statement (or execution leaving the function via a return or raise-ing an exception). Your while condition in your second example must fail, so there's no opportunity for a break to occur, the function to return or an exception to be thrown, so the else statements will always run.

docs for while

2 Comments

thank you, but i looked thru the entire code & there was no break keyword :(
do kindly view my edit. Was wondering if 'random' causes that strange behaviour ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.