Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python Instant Objects Methods

Kevin S
seal-mask
.a{fill-rule:evenodd;}techdegree
Kevin S
Data Analysis Techdegree Student 15,862 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,558 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?