Adp Unit1
Adp Unit1
PP unit-I
UNIT - I
Python Basics, Objects- Python Objects, Standard Types, Other Built-in Types,
Internal Types, Standard Type Operators, Standard Type Built-in Functions,
Categorizing the Standard Types, Unsupported Types
Numbers - Introduction to Numbers, Integers, Floating Point Real Numbers,
Complex Numbers, Operators, Built-in Functions, Related Modules
Sequences - Strings, Lists, and Tuples, Mapping and Set Types
Python Basics
Python is the world's most popular and fastest growing computer programming
language. It is a multi-purpose and high-level programming language. Python
was invented by Guido Van Rossum in the year 1989, but it was introduced
into the market on 20th February 1991.
The Python programming language has been using by many people like Software
Engineers, Data Analysts, Network Engineers, Mathematicians, Accountants,
Scientists, and many more. Using Python, one can solve complex problems in
less time with fewer lines of code.
Prerequisites
Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at
the National Research Institute for Mathematics and Computer Science in the
Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-
68, SmallTalk, and Unix shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the GNU
General Public License (GPL).
Python is now maintained by a core development team at the institute, although Guido
van Rossum still holds a vital role in directing its progress.
Python Features
Python's features include −
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax.
This allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
A broad standard library − Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
Extendable − You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
GUI Programming − Python supports GUI applications that can be created and ported to
many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the
X Window system of Unix.
Scalable − Python provides a better structure and support for large programs than shell
scripting.
Apart from the above-mentioned features, Python has a big list of good features, few
are listed below −
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for building large
applications.
It provides very high-level dynamic data types and supports dynamic type checking.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Python Install
Many PCs and Macs will have python already installed.
To check if you have python installed on a Windows PC, search in the start bar for Python or
run the following on the Command Line (cmd.exe):
To check if you have python installed on a Linux or Mac, then on linux open the command
line or on Mac open the Terminal and type:
python --version
If you find that you do not have python installed on your computer, then you can download
it for free from the following website: https://www.python.org/
Python Quickstart
Python is an interpreted programming language, this means that as a developer you write
Python (.py) files in a text editor and then put those files into the python interpreter to be
executed.
The way to run a python file is like this on the command line:
Let's write our first Python file, called helloworld.py, which can be done in any text editor.
helloworld.py
print("Hello, World!")
Simple as that. Save your file. Open your command line, navigate to the directory where
you saved your file, and run:
Hello, World!
Python Objects
Python uses the object model abstraction for data storage. Any construct that contains
any type of value is an object. Although Python is classified as an "object-oriented
programming (OOP) language," OOP is not required to create perfectly working Python
applications. You can certainly write a useful Python script without the use of classes and
instances. However, Python's object syntax and architecture encourage or "provoke" this
type of behavior. Let us now take a closer look at what a Python object is. All Python
objects have the following three characteristics: an identity, a type, and a value
IDENTITY Unique identifier that differentiates an object from all others. Any object's
identifier can be obtained using the id() built-in function (BIF). This value is as close as
you will get to a "memory address" in Python (probably much to the relief of some of
you). Even better is that you rarely, if ever, access this value, much less care what it is
at all.
TYPE An object's type indicates what kind of values an object can hold, what operations
can be applied to such objects, and what behavioral rules these objects are subject to.
You can use the type() BIF to reveal the type of a Python object. Since types are also
objects in Python (did we mention that Python was object-oriented?), type() actually
returns an object to you rather than a simple literal.
Object Attributes
The most familiar attributes are functions and methods, but some Python types have data
attributes associated with them. Objects with data attributes include (but are not limited to):
classes, class instances, modules, complex numbers, and files.
Standard Types
Python has five standard data types
• Numbers
• String
• List
• Tuple
• Dictionary
Python Numbers
Number data types store numeric values. Number objects are created when you assign
a value to them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The
syntax of the del statement is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For
example −
del var
del var_a, var_b
Python Numbers
Integers, floating point numbers and complex numbers falls under Python
numbers category. They are defined as int, float and complex class in Python. We can
use the type() function to know which class a variable or a value belongs to and
the isinstance() function to check if an object belongs to a particular class.
Example
a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
output
is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is complex number? True
Python Strings
Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows for either pairs of single or double quotes. Subsets of
strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in
the beginning of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator. For example −
Hello World!
H
llo
llo World!
Python List
Python offers a range of compound data types often referred to as sequences. List is one
of the most frequently used and very versatile datatype used in Python.
It can have any number of items and they may be of different types (integer, float,
string etc.).
1. # empty list
2. my_list=[]
3.
4. # list of integers
5. my_list=[1,2,3]
6.
7. # list with mixed datatypes
8. my_list=[1,"Hello",3.4]
Also, a list can even have another list as an item. This is called nested list.
# nested list
List Index
We can use the index operator [] to access an item in a list. Index starts from 0. So, a
list having 5 elements will have index from 0 to 4.
Trying to access an element other that this will raise an IndexError. The index must be an
integer. We can't use float or other types, this will result into TypeError.
1. my_list=['p','r','o','b','e']
2. # Output: p
3. print(my_list[0])
4.
5. # Output: o
6. print(my_list[2])
7.
8. # Output: e
9. print(my_list[4])
10.
11. # Error! Only integer can be used for indexing
12. # my_list[4.0]
13.
14. # Nested List
15. n_list=["Happy",[2,0,1,5]]
16.
17. # Nested indexing
18.
19. # Output: a
20. print(n_list[0][1])
21.
22. # Output: 5
23. print(n_list[1][3])
Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last
item, -2 to the second last item and so on.
1. my_list=['p','r','o','b','e']
2.
3. # Output: e
4. print(my_list[-1])
5.
6. # Output: p
7. print(my_list[-5])
1. my_list=['p','r','o','g','r','a','m','i','z']
2. # elements 3rd to 5th
3. print(my_list[2:5])
4.
5. # elements beginning to 4th
6. print(my_list[:-5])
7.
8. # elements 6th to end
9. print(my_list[5:])
10.
11. # elements beginning to end
12. print(my_list[:])
Slicing can be best visualized by considering the index to be between the elements as
shown below. So if we want to access a range, we need two indices that will slice that
portion from the list.
1. # mistake values
2. odd =[2,4,6,8]
3.
4. # change the 1st item
5. odd[0]=1
6.
7. # Output: [1, 4, 6, 8]
8. print(odd)
9.
10. # change 2nd to 4th items
11. odd[1:4]=[3,5,7]
12.
13. # Output: [1, 3, 5, 7]
14. print(odd)
We can add one item to a list using append() method or add several items
using extend()method.
1. odd =[1,3,5]
2.
3. odd.append(7)
4.
5. # Output: [1, 3, 5, 7]
6. print(odd)
7.
8. odd.extend([9,11,13])
9.
10. # Output: [1, 3, 5, 7, 9, 11, 13]
11. print(odd)
We can also use + operator to combine two lists. This is also called concatenation.
1. odd =[1,3,5]
2.
3. # Output: [1, 3, 5, 9, 7, 5]
4. print(odd +[9,7,5])
5.
6. #Output: ["re", "re", "re"]
7. print(["re"]*3)
Furthermore, we can insert one item at a desired location by using the method insert() or
insert multiple items by squeezing it into an empty slice of a list.
1. odd =[1,9]
2. odd.insert(1,3)
3.
4. # Output: [1, 3, 9]
5. print(odd)
6.
7. odd[2:2]=[5,7]
8.
9. # Output: [1, 3, 5, 7, 9]
10. print(odd)
7. print(my_list)
8.
9. # delete multiple items
10. delmy_list[1:5]
11.
12. # Output: ['p', 'm']
13. print(my_list)
14.
15. # delete entire list
16. delmy_list
17.
18. # Error: List not defined
19. print(my_list)
We can use remove() method to remove the given item or pop() method to remove an
item at the given index.
The pop() method removes and returns the last item if index is not provided. This helps
us implement lists as stacks (first in, last out data structure).
We can also use the clear() method to empty a list.
1. my_list=['p','r','o','b','l','e','m']
2. my_list.remove('p')
3.
4. # Output: ['r', 'o', 'b', 'l', 'e', 'm']
5. print(my_list)
6.
7. # Output: 'o'
8. print(my_list.pop(1))
9.
10. # Output: ['r', 'b', 'l', 'e', 'm']
11. print(my_list)
12.
13. # Output: 'm'
14. print(my_list.pop())
15.
16. # Output: ['r', 'b', 'l', 'e']
17. print(my_list)
18.
19. my_list.clear()
20.
21. # Output: []
22. print(my_list)
Finally, we can also delete items in a list by assigning an empty list to a slice of
elements.
1. >>>my_list=['p','r','o','b','l','e','m']
2. >>>my_list[2:3]=[]
3. >>>my_list
4. ['p','r','b','l','e','m']
5. >>>my_list[2:5]=[]
6. >>>my_list
7. ['p','r','m']
They are accessed as list.method(). Some of the methods have already been used above.
1. my_list=[3,8,1,6,0,8,4]
2.
3. # Output: 1
4. print(my_list.index(8))
5.
6. # Output: 2
7. print(my_list.count(8))
8.
9. my_list.sort()
10.
11. # Output: [0, 1, 3, 4, 6, 8, 8]
12. print(my_list)
13.
14. my_list.reverse()
15.
16. # Output: [8, 8, 6, 4, 3, 1, 0]
17. print(my_list)
Here is an example to make a list with each item being increasing power of 2.
1. pow2 =[]
2. for x in range(10):
3. pow2.append(2** x)
Python Tuple
A tuple in Python is similar to a list. The difference between the two is that we cannot
change the elements of a tuple once it is assigned whereas, in a list, elements can be
changed.
Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (), separated by
commas. The parentheses are optional, however, it is a good practice to use them.
A tuple can have any number of items and they may be of different types (integer, float,
list, string, etc.).
Empty tuple
my_tuple = ()
print(my_tuple) # Output: ()
my_tuple = (1, 2, 3)
# nested tuple
print(my_tuple)
A tuple can also be created without using parentheses. This is known as tuple packing.
a, b, c = my_tuple
print(a) #3
print(b) # 4.6
print(c) # dog
Having one element within parentheses is not enough. We will need a trailing comma to
indicate that it is, in fact, a tuple.
my_tuple = ("hello")
my_tuple = ("hello",)
# Parentheses is optional
my_tuple = "hello",
1. Indexing
We can use the index operator [] to access an item in a tuple where the index starts
from 0.
So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an element
outside of tuple (for example, 6, 7,...) will raise an IndexError.
The index must be an integer; so we cannot use float or other types. This will result
in TypeError.
Likewise, nested tuples are accessed using nested indexing, as shown in the example
below.
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
# print(my_tuple[6])
# my_tuple[2.0]
# nested tuple
# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) #4
2. Negative Indexing
The index of -1 refers to the last item, -2 to the second last item and so on.
my_tuple = ('p','e','r','m','i','t')
# Output: 't'
print(my_tuple[-1])
# Output: 'p'
print(my_tuple[-6])
3. Slicing
We can access a range of items in a tuple by using the slicing operator - colon ":".
my_tuple = ('p','r','o','g','r','a','m','i','z')
print(my_tuple[1:4])
print(my_tuple[:-7])
print(my_tuple[7:])
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple[:])
Slicing can be best visualized by considering the index to be between the elements as
shown below. So if we want to access a range, we need the index that will slice the
portion from the tuple.
Changing a Tuple
Unlike lists, tuples are immutable.
This means that elements of a tuple cannot be changed once it has been assigned. But,
if the element is itself a mutable datatype like list, its nested items can be changed.
# my_tuple[1] = 9
print(my_tuple)
my_tuple = ('p','r','o','g','r','a','m','i','z')
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)
We can use + operator to combine two tuples. This is also called concatenation.
We can also repeat the elements in a tuple for a given number of times using
the *operator.
Both + and * operations result in a new tuple.
Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4, 5, 6))
# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. That also means we
cannot delete or remove items from a tuple.
print(my_tuple)
Tuple Methods
Methods that add items or remove items are not available with tuple. Only the following
two methods are available.
Method Description
my_tuple = ('a','p','p','l','e',)
print(my_tuple.count('p')) # Output: 2
print(my_tuple.index('l')) # Output: 3
my_tuple = ('a','p','p','l','e',)
# In operation
# Output: True
print('a' in my_tuple)
# Output: False
print('b' in my_tuple)
# Not in operation
# Output: True
# Hello John
# Hello Kate
print("Hello",name)
Since tuples are quite similar to lists, both of them are used in similar situations as well.
However, there are certain advantages of implementing a tuple over a list. Below listed
are some of the main advantages:
We generally use tuple for heterogeneous (different) datatypes and list for homogeneous
(similar) datatypes.
Since tuples are immutable, iterating through tuple is faster than with list. So there is a slight
performance boost.
Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this is
not possible.
If you have data that doesn't change, implementing it as tuple will guarantee that it remains
write-protected.
Python Dictionary
What is dictionary in Python?
Python dictionary is an unordered collection of items. While other compound data types
have only value as an element, a dictionary has a key: value pair.
An item has a key and the corresponding value expressed as a pair, key: value.
While values can be of any data type and can repeat, keys must be of immutable type
(string, number or tuple with immutable elements) and must be unique.
1.
# empty dictionary
2. my_dict = {}
3.
4. # dictionary with integer keys
5. my_dict = {1: 'apple', 2: 'ball'}
6.
7. # dictionary with mixed keys
8. my_dict = {'name': 'John', 1: [2, 4, 3]}
9.
10. # using dict()
11. my_dict = dict({1:'apple', 2:'ball'})
12.
13. # from sequence having each item as a pair
14. my_dict = dict([(1,'apple'), (2,'ball')])
As you can see above, we can also create a dictionary using the built-in function dict().
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# my_dict.get('address')
# my_dict['address']
Jack
26
If the key is already present, value gets updated, else a new key: value pair is added to
the dictionary.
# update value
my_dict['age'] = 27
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
print(my_dict)
# Output: 16
print(squares.pop(4))
print(squares)
# Output: (1, 1)
print(squares.popitem())
print(squares)
del squares[5]
# Output: {2: 4, 3: 9}
print(squares)
squares.clear()
# Output: {}
print(squares)
del squares
# Throws Error
# print(squares)
16
{1: 1, 2: 4, 3: 9, 5: 25}
(1, 1)
{2: 4, 3: 9, 5: 25}
{2: 4, 3: 9}
{}
Method Description
Return a new dictionary with keys from seq and value equal to v(defaults
fromkeys(seq[, v]) to None).
get(key[,d]) Return the value of key. If key doesnot exit, return d (defaults to None).
Remove the item with key and return its value or d if key is not found.
pop(key[,d]) If d is not provided and key is not found, raises KeyError.
Remove and return an arbitary item (key, value). Raises KeyError if the
popitem() dictionary is empty.
If key is in the dictionary, return its value. If not, insert key with a value
setdefault(key[,d]) of d and return d (defaults to None).
Update the dictionary with the key/value pairs from other, overwriting
update([other]) existing keys.
marks = {}.fromkeys(['Math','English','Science'], 0)
print(marks)
print(item)
list(sorted(marks.keys()))
Here is an example to make a dictionary with each item being a pair of a number and its
square.
print(squares)
1. squares = {}
2. for x in range(6):
3. squares[x] = x*x
A dictionary comprehension can optionally contain more for or if statements.
An optional if statement can filter out items to form the new dictionary.
Here are some examples to make dictionary with only odd items.
print(odd_squares)
# Output: True
print(1 in squares)
# Output: True
# Output: False
print(49 in squares)
for i in squares:
print(squares[i])
Function Description
all() Return True if all keys of the dictionary are true (or if the dictionary is empty).
Return True if any key of the dictionary is true. If the dictionary is empty,
any() return False.
Here are some examples that uses built-in functions to work with dictionary.
# Output: 5
print(len(squares))
# Output: [1, 3, 5, 7, 9]
print(sorted(squares))
python have a built-in method called as type which generally come in handy while
figuring out the type of variable used in the program in the runtime.
If a single argument (object) is passed to type() built-in, it returns type of the given
object. If three arguments (name, bases and dict) are passed, it returns a new type
object.
Syntax:
type(object)
print(type(s))
print(type(y))
Output:
class 'int'
class 'str'
class 'list
Now you may ask yourself, so then what is the type of any type object? Well, let us find
out:
>>>type(type(42))
<type 'type'>
Yes, the type of all type objects is type. The type type object is also the mother of all
types and is the default metaclass for all standard Python classes.
NoneType
Python has a special type known as the Null object or NoneType. It has only one value,
None. The type of None is NoneType. It does not have any operators or BIFs. If you are
familiar with C, the closest analogy to the None type is void, while the None value is
similar to the C value of NULL.
obj = None
Let’s check the type of object variable ‘obj’.
1 obj = None
2 type(obj)
Output:
<type 'NoneType'>
It is the default return type of the function when the function does not return any value.
If the regular expression in re.search does not match, it returns NoneType object.
When you search key in the dictionary and key is not present, it
returns NoneType object.
The None keyword is also used for matching or to identify if the certain function
returns any value or not.
Internal Types
Code
Frame
Traceback
Slice
Ellipsis
Xrange
We will briefly introduce these internal types here. The general application programmer
would typically not interact with these objects directly, but we include them here for
completeness.
Code Objects
Code objects are executable pieces of Python source that are byte-compiled, usually as
return values from calling the compile() BIF. Such objects are appropriate for execution
by either exec or by the eval () BIF.
Frame objects
These are objects representing execution stack frames in Python. Frame objects contain
all the information the Python interpreter needs to know during a runtime execution
environment. Some of its attributes include a link to the previous stack frame, the code
object (see above) that is being executed, dictionaries for the local and global
namespaces, and the current instruction. Each function call results in a new frame
object, and for each frame object, a C stack frame is created as well. One place where
you can access a frame object is in a traceback object.
Traceback Objects
When you make an error in Python, an exception is raised. If exceptions are not caught
or "handled," the interpreter exits with some diagnostic information similar to the output
shown below:
Traceback (innermost last):
File "<stdin>", line N?, in ???
Slice Objects
Slice objects are created using the Python extended slice syntax. This extended syntax allows for
different types of indexing. These various types of indexing include stride indexing, multi-
dimensional indexing, and indexing using the Ellipsis type. The syntax for multi-dimensional
indexing is sequence [start1 : end1, start2 : end2], or using the ellipsis, sequence [..., start1 : end1].
Slice objects can alsobe generated by the slice() BIF.
Stride indexing for sequence types allows for a third slice element that allows for "step"-like
access with a syntax of sequence[starting_index : ending_index : stride].
Support for the stride element of the extended slice syntax have been in Python for a long time,
but until 2.3 was only available via the C API or Jython (and previously JPython). Here is an
example of stride indexing:
>>> foostr[::-1]
'edcba'
>>> foostr[::-2]
'eca'
>>> foolist = [123, 'xba', 342.23, 'abc']
>>> foolist[::-1]
Ellipsis Objects
Ellipsis objects are used in extended slice notations as demonstrated above. These objects are
used to represent the actual ellipses in the slice syntax (...). Like the Null object None, ellipsis
objects also have a single name, Ellipsis, and have a Boolean TRue value at all times.
XRange Objects
XRange objects are created by the BIF xrange(), a sibling of the range() BIF, and used when
memory is limited and when range() generates an unusually large data set.
Object Value Comparison Comparison operators are used to determine equality of two
data values between members of the same type. These comparison operators are
supported for all built-in types. Comparisons yield Boolean TRue or False values, based
on the validity of the comparison expression. (If you are using Python prior to 2.3 when
the Boolean type was introduced, you will see integer values 1 for TRue and 0 for False.)
A list of Python's value comparison operators is given below
Operator Function
Note that comparisons performed are those that are appropriate for each data type. In
other words, numeric types will be compared according to numeric value in sign and
magnitude, strings will compare lexicographically, etc.
>>> 2 == 2
True
>>> 2.46 <= 8.33
True
>>> 5+4j >= 2-3j
True
>>> 'abc' == 'xyz'
False
>>> 'abc' > 'xyz'
False
>>> 'abc' < 'xyz'
True
>>> [3, 'abc'] == ['abc', 3]
False
>>> [3, 'abc'] == [3, 'abc']
True
Also, unlike many other languages, multiple comparisons can be made on the same line,
evaluated in left-to-right order:
>>> 3 < 4 < 7 # same as ( 3 < 4 ) and ( 4 < 7 )
True
>>> 4 > 3 == 3 # same as ( 4 > 3 ) and ( 3 == 3 )
True
>>> 4 < 3 < 5 != 2 < 7
False
Object Identity Comparison
In addition to value comparisons, Python also supports the notion of directly comparing
objects themselves. Objects can be assigned to other variables (by reference). Because
each variable points to the same (shared) data object, any change effected through one
variable will change the object and hence be reflected through all references to the same
object. In order to understand this, you will have to think of variables as linking to
objects now and be less concerned with the values themselves.
When you look at this statement from the value point of view, it appears that you are
performing a multiple assignment and assigning the numeric value of 4.3 to both the
foo1 and foo2 variables. This is true to a certain degree, but upon lifting the covers, you
will find that a numeric object with the contents or value of 4.3 has been created. Then
that object's reference is assigned to both foo1 and foo2, resulting in both foo1 and foo2
aliased to the same object.
foo1 = 4.3
foo2 = foo1
This example is very much like the first: A numeric object with value 4.3 is created, then
assigned to one variable. When foo2 = foo1 occurs, foo2 is directed to the same object
as foo1 since Python deals with objects by passing references. foo2 then becomes a new
and additional reference for the original value. So both foo1 and foo2 now point to the
same object. The same figure above applies here as well.
foo1 = 4.3
This example is different. First, a numeric object is created, then assigned to foo1. Then
a second numeric object is created, and this time assigned to foo2. Although both
objects are storing the exact same value, there are indeed two distinct objects in the
system, with foo1 pointing to the first, and foo2 being a reference to the second. Figure
4-2 shows we now have two distinct objects even though both objects have the same
value.
id(foo1)
id(foo2)
Operator Function
In the example below, we create a variable, then another that points to the same object.
Boolean
Expressions may be linked together or negated using the Boolean logical operators and,
or, and not, all of which are Python keywords. These Boolean operations are in highest-
to-lowest order of precedence. The not operator has the highest precedence and is
immediately one level below all the comparison operators. The and and or operators
follow, respectively.
Operator Function
There are three different models we have come up with to help categorize the standard types,
with each model showing us the interrelationships between the types. These models help us
obtain a better understanding of how the types are related, as well as how they work.
Storage Model
The first way we can categorize the types is by how many objects can be stored in an object of
this type. Python's types, as well as types from most other languages, can hold either single or
multiple values. A type which holds a single literal object we will call atomic or scalar storage,
and those which can hold multiple objects we will refer to as container storage.
Types Categorized by the Storage Model
Although strings may seem like a container type since they "contain" characters (and usually
more than one character), they are not considered as such because Python does not have a
character type Thus strings are self-contained literals.
Update Model
Another way of categorizing the standard types is by asking the question, "Once created, can
objects be changed, or can their values be updated?" When we introduced Python types early
on, we indicated that certain types allow their values to be updated and others do not. Mutable
objects are those whose values can be changed, and immutable objects are those whose values
cannot be changed. Below one illustrates which types support updates and which do not.
>>> i = 0
>>> print id(i)
7749552
>>> i = i + 1
>>> print id(i)
7749600
On the flip side, lists can be modified without replacing the original object, as illustrated in the
code below:
>>> aList = ['ammonia', 83, 85, 'lady']
>>> aList
['ammonia', 83, 85, 'lady']
>>>
>>> aList[2]
85
>>>
>>> id(aList)
135443480
>>>
>>> aList[2] = aList[2] + 1
>>> aList[3] = 'stereo'
>>> aList
['ammonia', 83, 86, 'stereo']
>>>
>>> id(aList)
135443480
>>>
>>> aList.append('gaudy')
>>> aList.append(aList[2] + 1)
>>> aList
['ammonia', 83, 86, 'stereo', 'gaudy', 87]
>>>
>>> id(aList)
135443480
Notice how for each change, the ID for the list remained the same.
Access Model
Although the previous two models of categorizing the types are useful when being introduced to
Python, they are not the primary models for differentiating the types. For that purpose, we use
the access model. By this, we mean, how do we access the values of our stored data? There are
three categories under the access model: direct, sequence, and mapping. The different access
models and which types fall into each respective category are given below.
Mapping Dictionaries
We summarize by presenting a cross-reference chart (see Table ) that shows all the standard types,
the three different models we use for categorization, and where each type fits into these models.
Unsupported Types
Before we explore each standard type, we conclude this chapter by giving a list of types that are
not supported by Python.
char or byte
Python does not have a char or byte type to hold either single character or 8-bit integers. Use strings
of length one for characters and integers for 8-bit numbers.
pointer
Since Python manages memory for you, there is no need to access pointer addresses. The closest to
an address that you can get in Python is by looking at an object's identity using the id() BIF. Since you
have no control over this value, it's a moot point. However, under Python's covers, everything is a
pointer.
Type complex(x) to convert x to a complex number with real part x and imaginary part zero.
Type complex(x, y) to convert x and y to a complex number with real part x and imaginary
part y. x and y are numeric expressions
Operators
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called
operator.
Types of Operator
Python language supports the following types of operators.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Let us have a look on all operators one by one.
Arithmetic Operators
Assume variable a holds 10 and variable b holds 20, then −
[ Show Example ]
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
% Modulus Divides left hand operand by right hand operand and returns b%a=0
remainder
// Floor Division - The division of operands where the result is the 9//2 = 4 and
quotient in which the digits after the decimal point are removed. 9.0//2.0 = 4.0,
But if one of the operands is negative, the result is floored, i.e., -11//3 = -4, -
rounded away from zero (towards negative infinity) − 11.0//3 = -4.0
Comparison Operators
These operators compare the values on either sides of them and decide the relation
among them. They are also called Relational operators.
[ Show Example ]
== If the values of two operands are equal, then the condition (a == b) is not true.
becomes true.
<> If values of two operands are not equal, then condition (a <> b) is true. This is
becomes true. similar to != operator.
> If the value of left operand is greater than the value of right (a > b) is not true.
operand, then condition becomes true.
< If the value of left operand is less than the value of right (a < b) is true.
operand, then condition becomes true.
>= If the value of left operand is greater than or equal to the (a >= b) is not true.
value of right operand, then condition becomes true.
<= If the value of left operand is less than or equal to the value (a <= b) is true.
of right operand, then condition becomes true.
Assignment Operators
Assume variable a holds 10 and variable b holds 20, then −
[ Show Example ]
= Assigns values from right side operands to left side c = a + b assigns value of
operand a + b into c
+= Add AND It adds right operand to the left operand and assign c += a is equivalent to c
the result to left operand =c+a
-= Subtract It subtracts right operand from the left operand and c -= a is equivalent to c =
AND assign the result to left operand c–a
*= Multiply It multiplies right operand with the left operand and c *= a is equivalent to c =
AND assign the result to left operand c*a
/= Divide AND It divides left operand with the right operand and c /= a is equivalent to c =
assign the result to left operand c / ac /= a is equivalent to
c=c/a
%= Modulus It takes modulus using two operands and assign the c %= a is equivalent to c
AND result to left operand =c%a
//= Floor It performs floor division on operators and assign c //= a is equivalent to c
Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and
b = 13; Now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
~a = 1100 0011
& Binary AND Operator copies a bit to the result if it exists in (a & b) (means 0000
both operands 1100)
^ Binary XOR It copies the bit if it is set in one operand but (a ^ b) = 49 (means
not both. 0011 0001)
<< Binary Left Shift The left operands value is moved left by the
a << 2 = 240 (means
>> Binary Right Shift The left operands value is moved right by the a >> 2 = 15 (means
number of bits specified by the right operand. 0000 1111)
Logical Operators
There are following logical operators supported by Python language. Assume variable a
holds 10 and variable b holds 20 then
[ Show Example ]
and Logical If both the operands are true then condition (a and b) is true.
AND becomes true.
not Logical Used to reverse the logical state of its operand. Not(a and b) is false.
NOT
Membership Operators
Python’s membership operators test for membership in a sequence, such as strings,
lists, or tuples. There are two membership operators as explained below −
[ Show Example ]
not in Evaluates to true if it does not finds a variable in the x not in y, here not in results in
a 1 if x is not a member of
Identity Operators
Identity operators compare the memory locations of two objects. There are two Identity
operators explained below −
is not Evaluates to false if the variables on either side of the x is not y, here is notresults in
operator point to the same object and true otherwise. 1 if id(x) is not equal to id(y).
Operators Precedence
The following table lists all operators from highest precedence to lowest.
[ Show Example ]
1 **
2 ~+-
3 * / % //
4 +-
5 >> <<
6 &
Bitwise 'AND'
7 ^|
Comparison operators
9 <> == !=
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
11 is is not
Identity operators
12 in not in
Membership operators
13 not or and
Logical operators
int()
The int() method returns an integer object from any number or string.
int(x=0, base=10)
int() Parameters
an integer object from the given number or string, treats default base as 10
(No parameters) returns 0
(If base given) treats the string in the given base (0, 2, 8, 10, 16)
# float
print("int(123.23) is:", int(123.23))
# string
print("int('123') is:", int('123'))
# octal 0o or 0O
print("For 12, int is:", int('12', 8))
print("For 0o12, int is:", int('0o12', 8))
# hexadecimal
print("For A, int is:", int('A', 16))
print("For 0xA, int is:", int('0xA', 16))
float()
The float() method returns a floating point number from a number or a string.
float([x])
float() Parameters
Parameter
Type Usage
Must contain decimal numbers. Leading and trailing whitespaces are removed.
Optional use of "+", "-" signs. Could contain NaN, Infinity, inf (lowercase or
String uppercase).
# for floats
print(float(11.22))
10.0
11.22
-13.33
-24.45
ValueError: could not convert string to float: 'abc'
# for inf/infinity
print(float("inf"))
print(float("InF"))
print(float("InFiNiTy"))
print(float("infinity"))
nan
nan
inf
inf
inf
inf
Python complex()
The complex() method returns a complex number when real and imaginary parts are
provided, or it converts a string to a complex number.
complex([real[, imag]])
complex() Parameters
If the string passed to this method is not a valid complex number, ValueErrorexception is
raised.
Note: The string passed to the complex() should be in the form real+imagj or real+imagJ
z = complex(1)
print(z)
z = complex()
print(z)
z = complex('5-9j')
print(z)
(2-3j)
(1+0j)
0j
(5-9j)
It's possible to create a complex number without using complex() method. For that, you
have to put 'j' or 'J' after a number.
a = 2+3j
print('a =',a)
print('Type of a is',type(a))
b = -2j
print('b =',b)
print('Type of b is',type(a))
c = 0j
print('c =',c)
print('Type of c is',type(c))
a = (2+3j)
Type of a is <class>
b = (-0-2j)
Type of b is <class>
c = 0j
Type of c is <class>
Operational
Python has four operational built-in functions for numeric types: abs(), divmod(), pow(), and
round(). We will take a look at each and present some usage examples.
Python abs()
The abs() method returns the absolute value of the given number. If the number is a
complex number, abs() returns its magnitude.
abs(num)
abs() Parameters
num - number whose absolute value is to be returned. The number can be:
a. integer
b. floating number
c. complex number
The abs() method returns the absolute value of the given number.
floating = -30.33
print('Absolute value of -30.33 is:', abs(floating))
Python divmod()
The divmod() method takes two numbers and returns a pair of numbers (a tuple)
consisting of their quotient and remainder.
divmod(x, y)
divmod() Parameters
If x and y are integers, the return value from divmod() is same as (a // b, x % y).
If either x or y is a float, the result is (q, x%y). Here, q is the whole part of the quotient.
divmod(8, 3) = (2, 2)
divmod(3, 8) = (0, 3)
divmod(5, 5) = (1, 0)
divmod(8.0, 3) = (2.0, 2.0)
divmod(3, 8.0) = (0.0, 3.0)
divmod(7.5, 2.5) = (3.0, 0.0)
divmod(2.6, 0.5) = (5.0, 0.10000000000000009)
Python pow()
The pow() method returns x to the power of y. If the third argument (z) is given, it
returns x to the power of y modulus z, i.e. pow(x, y) % z.
x**y
pow() Parameters
X y z
Non-negative Integer OR Negative Integer Non-negative Integer May or may not be present
The pow() method's return value depends upon the type of arguments passed.
Return
x y z Value
Non-negative
Non-negative Integer Integer N/A Integer
Non-negative
Negative Integer Integer N/A Integer
# negative x, positive y
print(pow(-2, 2))
# negative x, negative y
print(pow(-2, -2))
4
4
0.25
0.25
print(pow(x, y, z))
Here, 7 is powered by 2 (7**2) which equals 49. Then, 49 modulus 5 (49 % 5) equals 4.
Python round()
The round() method returns the floating point number rounded off to the given ndigits
digits after the decimal point. If no ndigits is provided, it rounds off the number to the
nearest integer.
round(number[, ndigits])
round() Parameters
(If ndigits not provided) nearest integer to the given number If two multiples are really close,
rounding is done toward the even choice
(If ndigits given) floating point number rounded off to the ndigits digits Always rounded to the
closest multiple of 10 to the power minus ndigits
# even choice
print(round(5.5))
10
11
6
2.67
2.67
Here, both numbers result to the same output 2.67, when 2.675 should have been
rounded to 2.68.
This isn't a bug but it is because, most decimal numbers cannot be represented exactly
as a float.