First time here, hello everyone! In Recitation 1, why did the TA use print 'Cube root of ' + str(x) + ' is ' + str(ans) instead of something more straightforward like print 'Cube root of', x, 'is', ans ? IINM, he basically made every part of it a string then concatenated them? If so, I'm not sure what the purpose of it is... Here's a screenshot of his entire code for context. http://i852.photobucket.com/albums/ab84/kurisuto/rec1-cuberootprogram.jpg
I tried both your version and the TA's. Both work. The variation that does not work is: print 'cube root of' + x + 'is' + ans, where the error is cannot concatenate int and str. For the problem sets too, there seem to be alternatives that do the same thing (with similar amount of code so it's not more convoluted), but the solution sets or recitation just don't include all the correct possibilities.
I suspect, Kizolk, that he is using this form because they just recently taught concatenation. I don't think they have introduced the other format yet.
Thank you both fo your answers! I guess what really confused me was that, seeing how some programmers (including him during this very recitation) like to joke about how they're the laziest people in the world, I found it strange that he'd use this syntax when there were slightly simpler and quicker solutions. But as you said, maybe it was indeed just to show us how to concatenate strings and convert objects. Now that I think of it, I think they had used the comma in other contexts, but not exactly like that, so I guess at this point we haven't "learned" how to do that yet. Thanks again for your answer!
Hi - Brian is correct, that is why we did things this way. Using commas as "glue" glosses over the typing issue; when you write [1] print 'The number is', x there's an implicit typecasting of x to a string, regardless of what type x is. So in fact example [1] is a convenient shorthand for [2] print 'The number is ' + str(x) It's important to understand that variables of one type can be casted to another type if/when you need it; without example [2], you wouldn't actually understand that in example [1], a typecasting is even occurring. I hope that is helpful!
Join our real-time social learning platform and learn together with your friends!