Type Conversion Functions

Python provides built-in functions that convert values from one type to another. The int functions converts any value to an integer, if it can, or complains otherwise:
>>> value = raw_input("Enter a value: ")
Enter a value: 5
>>> type(value)

>>> x=int(value)
>>> type(x)

If the entered value is a string the Python interpreter will give us an error.
>>> value = raw_input("Enter a value: ")
Enter a value: Hello
>>> type(value)

>>> x=int(value)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: invalid literal for int() with base 10: 'Hello'
Int can convert floating point numbers to integers although it doesn’t round off, it chops off the fraction part:
>>> x = 4.975
>>> y = int(x)
>>> print x
4.975
>>> print y
4
Float converts integers and strings to floating-point numbers:
>>> x = 32
>>> y = float(32)
>>> print y
32.0
>>> x='32.453'
>>> type(x)

>>> y=float(x)
>>> y
32.453
>>> type(y)

Str function converts its argument to a string:
>>> x = 32
>>> type(x)

>>> y=str(x)
>>> type(y)

Nema komentara:

Objavi komentar