Types in Python

 Introduction to Types in Python


In general, the structure of a Python program is as follows:


  • Programs are composed of modules.
  • Modules contain statements.
  • Statements contain expressions.
  • Expressions create and process objects.

In Python, everything is an object. Including values. Even simple numbers qualify, with values (e.g., 99), and supported operations (addition, subtraction, and so on). In Python, data takes the form of objects—either built-in objects that Python provides, or objects we create using Python classes or external language tools such as C extension libraries.

Following table shows fundamental Python’s built-in object types and some of the syntax used to code their literals—that is, the expressions that generate these objects:

Object Type Examples 
Numbers12, 2.67, 6+8j, 0b1011
Strings‘hai’, “hello”, “Python’s Features”, str(‘Python’)
Lists[1,2,3], [1,2,’three’], list(range(10)), list(‘hai’)
Tuples(1,2,3), (1,2,’three’), tuple(range(10)), tuple(‘hai’)
Sets{1,2,3}, set(‘hai’)
Dictionaries{‘Mon’:1, ‘Tue’:2, ‘Wed’:3}, dict(hours=10)

Following are some more types available in Python:

Object Type Examples 
Filesopen(‘abc.txt’)
Functionsdef, lambda
Modulesimport, __module__
Classesobjects, types, metaclasses
NoneNone
BooleansTrue, False

In this article we will learn about Number and Boolean types. We will learn about other types in other articles.

Numbers


Numbers include the following:
  • integers
  • floating-point numbers
  • complex numbers
  • decimals with fixed precision
  • rational numbers with numerator and denominator
  • sets

Using third party extensions we have more types like matrices, vectors, etc.

Following are examples of numeric literals and constructors:

Literal Description 
12, -887, 0, 999999999999999999999998Integers (unlimited size)
1.23, 1., 3.14e-10, 4E210, 4.0e+210Floating-point numbers
0o177, 0x9ff, 0b101010Octal, hex, and binary literals
6+4j, 2.0+9.0j, 7JComplex number literals
Decimal(‘13.0’), Fraction(4, 7)Decimal and fraction extension types
bool(X), True, FalseBoolean type and constants

Floating-point numbers are implemented as C doubles in standard Cpython. The functions hex, oct, and bin can be used to convert integers to hexadecimal, octal, and binary formats respectively.

Complex numbers are internally implemented as pairs of floating-point numbers. Complex numbers can be ended with j or J. Complex numbers can also be created with complex(real, imag) function call.
We can use built-in functions like: pow, abs, round, int, hex, bin, etc on numbers. We can also use utility modules like random, math as follows:

1 comment

  1. Very nice.
    Please upload more information about Python with practical examples.

    ReplyDelete

JavaFX Scene Builder

  This is an article about the JavaFX Scene Builder. You will get a short introduction about the installation and usage of the software. The...