0

I am trying to learn Python and can't get my head around why this while loop I found breaks:

while string:
    print("Test")
    string = string[3:]

With for example

string = "123456789"

The output is:

Test
Test
Test

The way I understood the while function is, that it breaks only when the expression following the while command is False. But how can string = string[3:] be False, I mean it just changes string form being "123456789" to being "456789"?

Thanks for any tips!

4
  • 3
    Python, like JavaScript and PHP has "falsy" values. An empty-string is "falsy", for example. Your string starts off as "123456789", then it's "456789", then it's "789", and then it's "", which is considered false and the while loop breaks. Commented Oct 21, 2020 at 4:31
  • If you don't understand how a program works by looking at it, grab a sheet of grid-lined paper and execute it by-hand. You don't need a computer to do computations :) Commented Oct 21, 2020 at 4:32
  • 1
    Empty strings are Falsy. freecodecamp.org/news/truthy-and-falsy-values-in-python Commented Oct 21, 2020 at 4:37
  • Thank you guys very much. That makes sense! Commented Oct 21, 2020 at 13:07

2 Answers 2

1

after the first iteration, we've

string = 456789

after the second iteration

string = 789

after that when we assign string[3:] (now this becomes '' empty string) which is falsy value and loop exits

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

1 Comment

Thank you! I forgot that it removes parts of the string every iteration.
0

Since you have put String = string[3:] In the iteration, every time the loop executes it will remove the first 3 digits making it [4,5,6,7,8,9] after first iteration Then [7,8,9] after second iteration And finally [] after third iteration Which makes it false

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.