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 trialA X
12,842 PointsIs 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
Treehouse Moderator 68,423 PointsThe 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.
A X
12,842 PointsA X
12,842 PointsAh! 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
Treehouse Moderator 68,423 PointsChris Freeman
Treehouse Moderator 68,423 PointsThe functions
int()
andfloat()
convert objects to integers and floating point numbers.