Just as we have had to convert numbers to strings we also need to convert strings to numbers. The the float() function will convert a string to a floating-point value and the int() function will convert a string to an integer value. Try the code below.
x="12" print(x+","+format(type(x))) y=int(x) print(format(y)+","+format(type(y)))
Note that the x value looks exactly like the y value when printed. This can cause you to think that you have a numeric value when you really have a string! Try the code below.
x="1" y="2" z=x+y print(z)
The result that prints is 12! What's happening is pretty obvious with the code above, the x variable has a string with "1" in it and the y value has a string with "2" in it and we are concatenating the strings instead of adding two numbers. In the near future, you'll call a function that returns strings and you'll think the function returns numbers. Then you'll try to perform math on the values and you'll start to believe your computer has lost it's ability to do math. Stop and check the type of each variable to make sure you have the correct type and then convert the values to the correct type if needed.
Python Documentation: String functions
Python Documentation: Defining Functions
© Copyright 2018 HSU - All rights reserved.