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

Is Python 'Inferring' more than other languages?

I've noticed that many languages require almost everything to be explicitly defined in order to run the program. I was surprised when Kenneth mentioned the following about using format: "Python understands that we're formatting a string, so everything that goes in needs to be a string when it goes in. This isn't Python making decisions for us, this is just Python doing what we've told it to do."

status_message = "Hey we have {} {} using the site right now."
print(status_message.format(6, "pokemon")) 

So it seems to me that Python is inferring a string from the int value 6. I don't know how we're "telling" Python that the 6 is part of the string here...or at least it doesn't seem to be an explicit "telling", like converting 6 into a string first.

Can someone explain to me if Python is doing "inference" on certain occasions, or if I'm completely misunderstanding what's happening here?

*Note: I'm a beginner, please answer in a simple, easy to follow format. Thanks!

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,166 Points

The status_message is a string object with the method format(). This method automatically calls the str() string converting function on each of its arguments. So the number 6 argument is first converted using str(6) to get the string "6". format then builds a new string based on the original status_message text and the two string values derived from its arguments.

There isn't an inference happening, format converts all arguments to strings.

Ah! That makes sense. So I assume that format only converts to the str type then, and we'd use some other keyword for say, converting everything to an int?

Chris Freeman
Chris Freeman
Treehouse Moderator 68,166 Points

The functions int() and float() convert objects to integers and floating point numbers.