Knowledge Base‎ > ‎Programming‎ > ‎Python‎ > ‎Python Reference‎ > ‎

Types and Conversion


Related:

 Examples

 
 
n = 10
type(n)
s = str(n)
n = int(s)

 Description        

 
Python is a dynamically typed language - which means you don't need to declare the type of the variable when you create it. Instead Python decides on the type using some basic rules when examining your variable.

At times you will need to convert variables and data between different types. Or you will need to check what kind of type you are working with.

int() converts a value into an integer, if there is a decimal portion to a numeric value it will simply drop the decimal. If the value isn't numeric then using int() will throw and error.

str() converts a value into a string.

type() will inspect a variable and return the type of the variable

 Syntax

 
 

 Parameters

 

 Interpreter

 Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>> n = 10

>>> n

10

>>> type(n)

<type 'int'>

>>> n = str(n)

>>> n

'10'

>>> type(n)

<type 'str'>

>>> n = 10.0

>>> type(n)

<type 'float'>

>>> n = 10.5

>>> type(n)

<type 'float'>

>>> n = int(n)

>>> n

10

>>> type(n)

<type 'int'>

>>> n = "hello"

>>> int(n)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

ValueError: invalid literal for int() with base 10: 'hello'

>>>




Comments