TAGS :Viewed: 15 - Published at: a few seconds ago

[ turning variables that use 'str()' into numbers ]

I have searched and didn't come up with anything particularly useful, but I'm very new to programming so please bare with me.

I'm trying to apply the math.floor function to a some variables that use the str() function... what is the proper way to do this?

Here's my code:

import math
x = str(10.3)
y = str(22)
z = str(2020)

print "x equals " + x
print "y equals " + y
print "z equals " + z

#playing around with the math module here. The confusion begins...
#how do I turn my str() functions back into integers and apply the floor      function of the math module?
xfloor = math.floor(x)
zsqrt = math.sqrt(z)
print "When we print the variable \"xfloor\" it rounds " + x + "down into " + xfloor + "."
print "When we print the variable \"zsqrt\" it finds the sqareroot of " + z + "which is " + zsqrt + "."

raw_input("Press the enter key to continue.")

Any and all assistance is welcome.

Answer 1


Cast them back :

xfloor = math.floor(float(x))
zsqrt = math.sqrt(float(z))

But this is not a recommended practice as you are converting it to str unnecessarily. To print use str.format

print "x equals {}".format(x)

For this you do not need to cast to str.