Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics (2015) Logic in Python Around and Around

why when I use while loop , the variable in it can't be 0?

start=10 while start: print(start) start-=1

I know only start is true, than the loop will continue, but why when the start=0 the loop will stop? I think even start =0 it's true

why it's false ?

2 Answers

28,538 Points

When you give Python a Non-Boolean (string, int, etc) and it tries to convert it to a Boolean (True or False) it does so by checking if the value is on a list of values it considers to be a "Falsey" value. If that is the case it converts it to False, if the value is not on that list then it is treated as "Truethy" by default and converted to True.

Here is the list of values that Python considers "Falsey":

  • None
  • False
  • Zero of any numeric type, for example, 0, 0L, 0.0, 0j.
  • Any empty sequence, for example, '', (), [].
  • Any empty mapping, for example, {}.
  • Instances of user-defined classes, if the class defines a nonzero() or len() method, when that method returns the integer zero or bool value False.

So When start is any number other than 0 it is treated as True since that is not found on the above list. Once it becomes 0 it is considers False since 0 is on the above list.

Josh Bennett
Josh Bennett
15,258 Points

Because when the var decrements to 0, while = 0 and if while = 0 it is falsey.


I known ,but the video didn't express this concept , I still can't understand =0 is falsely

Although I know it might has a error when 1/x