Friday, 18 March 2016

Built-in Object types in Python with examples

Built-in Object types in Python with examples

Python also has built-in object types that are closely related to the data types mentioned above. Once you are familiar with these two sets of tables, you will know how to code almost anything!

Type
Description
list
Mutable sequence, always in square brackets: [1, 2, 3]
tuple
Immutable sequence, always in parentheses: (a, b, c)
dict
Dictionary - key, value storage. Uses curly braces: {key:value}
set
Collection of unique elements – unordered, no duplicates
str
String - sequence of characters, immutable
unicode
Sequence of Unicode encoded characters

Python Operators:

The following table lists Python’s common operators:
Operator
Action
Example
+
Adds items together; for strings and sequences concatenates
1 + 1 -> 2
“one” + “one” ->
“oneone”
-
Subtraction
1 – 1 -> 0
*
multiplication, with strings, repeats string
2 * 3 -> 6
“one” * 2 -> “oneone”
/ (//)
division, division of integers results in an integer with truncation in Python 2.x, a float in Python 3.x (// is integer division in Python 3.x)
3/4  -> 0 (2.x)
3/4  -> 0.75 (3.x)
3//4 -> 0 (3.x)
**
Exponent – raises a number to the given exponent

Data Objects in python

Variables and their Types

Python is a dynamically typed language, but it is also a fairly strongly typed language.So a variable could end up referring to different types of objects, but the object that it's referring to at any given moment is strongly typed.

The below are the few examples
Variable1 = 1      # Variable1 points to an integer object
y = 2      # Variable2 also points to an integer object
Variable3 = Variable1 + Variable2 # Variable3 points to an integer object  3
a = Variable2      # a points to the same int object as Variable2
Variable2 = "2"   # Variable2 now points to a different object, a string
Variable3 = Variable1 + Variable2 # throws a type mismatch (TypeError) exception since an integer and a string are different types and can't be added.
Variable3 = Variable1 + a  # Variable3 now points to an int (3), since a is pointing to an int

Python Data Types

Type
Description
int
An integer of the same size as a long in C on the current platform.
long
An integer of unlimited precision (In Python 3.x this becomes an int).
float
A floating point number , usually a double in C on the current platform.
complex
Complex numbers have a real and an imaginary component, each is a float.
boolean
True or False

No comments: