Wednesday, April 24, 2013

A Quick Tip - Changing Types of Numbers

     I am going to tell you some functions that might be useful, float(), int(), and str().

number="33.33"
number
'33.33'
float(number)
33.33

     When you printed "number" (the second line worked as a print statement), it took 33.33 as a string, and put those apostrophes around it. When you used float(), it turned it into a float, or decimal. What if you want to do this with an integer, or whole number? Well, try this:

number="33"
number
'33'
int(number)
33

     Worked just like the float. Here's a question you might have: What if you did this?

number="33.33"
int(number)

     Well, here is what happens:


Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    int(number)
ValueError: invalid literal for int() with base 10: '33.33'

     We get an error. What if we try it the other way around?

number="33"
float(number)
33.0

     We just get a ".0" added to the end of it. But, we can do something else rather than altering numbers. Let's try this:

number=33 + 2
number
35
str(number)
'35'

     Here, we went the opposite way. We changed the answer of the problem into a string.
     Here, you learned how to convert numbers to strings and strings to numbers. But, before the article ends, let's do some experimenting:

number=3
number
3
number=str(number)
number
'3'

number="33 + 2"
number
'33 + 2'
int(number)

Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    int(number)
ValueError: invalid literal for int() with base 10: '33 + 2'

     I think that's all I wanted to try out. So... Yeah.

No comments:

Post a Comment