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 Object-Oriented Python Instant Objects Methods

Kevin S
Kevin S
15,615 Points

I changed kenneth.sneaky to an integer and this happened...Why

I was messing around, and instead of changing kenneth.sneaky to False, i changed it to an integer of 333. I called kenneth.sneaky() again a couple more times and got True False True True meaning that the program was running normally. Why did that work? is it because any other value other than False is True?

2 Answers

andren
andren
28,521 Points

is it because any other value other than False is True?

Not quite, but you are not too far off.

When you use a Non-Boolean (string, int, etc) in a place that expects a Boolean Python will automatically convert it to a Boolean value. 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 "Truthy" 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.

Since 333 is not on the above list it is considered "Truthy" and is therefore treated the same as True.

I'm surprised and confused that OP got that one instance of False. Do you know why that happened?

Kevin S
Kevin S
15,615 Points

Thanks for answering. That answers my question completely!