What happens when we try to print text and numbers? Consider the example below:
You will receive a TypeError message because you can only add numbers to numbers or add strings to strings. To be able to print my message properly, I need to convert the number to a string using the string function str( ). Consider the above example again:
We can also convert floats to strings:
Similarly, we can convert strings into numbers. To change a string to an integer, you can use the int() function. The below example will receive another TypeError.
If I change num1 to an integer, then I will be able to complete the addition:
We can also convert strings into floats using the float( ) function:
Converting a string into a number only works if there is only a number contained in the string:
The above code will produce a ValueError because Python cannot figure out which part of the string is the number.