Python Noob Alert


#1

https://www.codecademy.com/courses/learn-python/lessons/strings--console-output/exercises/explicit-string-conversion?action=resume_content_item

I have just started to learn Python (no prior experience in programming) and I was wondering why I would want to key print “The value of pi is around” + str(3.14) RATHER THAN print “The value of pi is around 3.14” ? Isn’t this creating extra steps??

I also wonder why I would key concatenations rather than just type out the full sentence? I’m assuming this will become clear later but right now it seems like this is just making things more complicated.

Thank you in advance!


#2

i answered exactly the same question yesterday:

I Have a Question About Strings


#3

You are correct in noticing that this is an extra step.
This is a lesson of TYPECASTING.

here is a useful link that explains typecasting in python
https://www.programiz.com/python-programming/type-conversion-and-casting

For example, if you would tell python to print(“the value of pi is around” + 3.14 ), it would throw you an error because a string and an float or int or any numeric data types are not compatible types that can be concatenated together the way a string + a_string can be concatenated. Therefor you must explicitly tell python to first convert the numeric data into string data using the str() function.

The correct way to write this is print(“The value of pi is around” + str(3.14) )

The purpose of using the function str(3.14) is to tell the python interpreter that we explicitly want this “3.14” to be represented as a string of characters Litterally { ‘3’ , ‘.’ , ‘1’ , ‘4’ } , and not as a floating point object representing the value of 3.14


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.