0% found this document useful (0 votes)
6 views60 pages

Adp Unit1

This document provides an overview of Python programming basics, including its history, features, and standard data types such as numbers, strings, lists, and tuples. It highlights Python's ease of use, readability, and versatility for various applications, making it suitable for beginners and experienced programmers alike. Additionally, it covers installation instructions and basic operations for creating and manipulating Python objects and data types.

Uploaded by

gdcwcse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views60 pages

Adp Unit1

This document provides an overview of Python programming basics, including its history, features, and standard data types such as numbers, strings, lists, and tuples. It highlights Python's ease of use, readability, and versatility for various applications, making it suitable for beginners and experienced programmers alike. Additionally, it covers installation instructions and basic operations for creating and manipulating Python objects and data types.

Uploaded by

gdcwcse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

lOMoARcPSD|57417370

PP unit-I

Python Programming (Jawaharlal Nehru Technological University, Hyderabad)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by cse gdcw ([email protected])
lOMoARcPSD|57417370

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.

Guido Van Rossum

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

Prerequisites

You should have a basic understanding of Computer Programming terminologies. A


basic understanding of any of the programming languages is a plus.
Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python is designed to be highly readable. It uses English keywords frequently where as
other languages use punctuation, and it has fewer syntactical constructions than other
languages.
 Python is Interpreted − Python is processed at runtime by the interpreter. You do not need
to compile your program before executing it. This is similar to PERL and PHP.

 Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.

 Python is Object-Oriented − Python supports Object-Oriented style or technique of


programming that encapsulates code within objects.

 Python is a Beginner's Language − Python is a great language for the beginner-level


programmers and supports the development of a wide range of applications from simple text
processing to WWW browsers to games.

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.

 Easy-to-maintain − Python's source code is fairly easy-to-maintain.

 A broad standard library − Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

 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.

 Databases − Python provides interfaces to all major commercial databases.

 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 supports automatic garbage collection.

 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):

C:\Users\Your Name>python --version

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

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

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:

C:\Users\Your Name>python helloworld.py

Where "helloworld.py" is the name of your python file.

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:

C:\Users\Your Name>python helloworld.py

The output should read:

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

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

objects in Python (did we mention that Python was object-oriented?), type() actually
returns an object to you rather than a simple literal.

VALUE Data item that is represented by an object.

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.

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

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 −

str = 'Hello World!'

print str # Prints complete string

print str[0] # Prints first character of the string

print str[2:5] # Prints characters starting from 3rd to 5th

print str[2:] # Prints string starting from 3rd character

print str * 2 # Prints string two times

print str + "TEST" # Prints concatenated string

This will produce the following result −

Hello World!
H
llo
llo World!

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

Hello World!Hello 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.

How to create a list?


In Python programming, a list is created by placing all the items (elements) inside a
square bracket [ ], separated by commas.

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

my_list = ["mouse", [8, 4, 6], ['a']]

How to access elements from a list?


There are various ways in which we can access the elements of a 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.

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

Nested list are accessed using nested indexing.

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])

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

How to slice lists in Python?


We can access a range of items in a list by using the slicing operator (colon).

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.

How to change or add elements to a list?


List are mutable, meaning, their elements can be changed unlike string or tuple.

We can use assignment operator (=) to change an item or a range of items.

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]

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

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.

The * operator repeats a list for the given number of times.

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)

How to delete or remove elements from a list?


We can delete one or more items from a list using the keyword del. It can even delete
the list entirely.
1. my_list=['p','r','o','b','l','e','m']
2.
3. # delete one item
4. delmy_list[2]
5.
6. # Output: ['p', 'r', 'b', 'l', 'e', 'm']

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

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']

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

Python List Methods


Methods that are available with list object in Python programming are tabulated below.

They are accessed as list.method(). Some of the methods have already been used above.

Python List Methods

append() - Add an element to the end of the list

extend() - Add all elements of a list to the another list

insert() - Insert an item at the defined index

remove() - Removes an item from the list

pop() - Removes and returns an element at the given index

clear() - Removes all items from the list

index() - Returns the index of the first matched item

count() - Returns the count of number of items passed as an argument

sort() - Sort items in a list in ascending order

reverse() - Reverse the order of items in the list

copy() - Returns a shallow copy of the list

Some examples of Python list methods:

1. my_list=[3,8,1,6,0,8,4]
2.
3. # Output: 1
4. print(my_list.index(8))
5.
6. # Output: 2

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

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)

List Comprehension: Elegant way to create new


List
List comprehension is an elegant and concise way to create new list from an existing list
in Python.

List comprehension consists of an expression followed by for statement inside square


brackets.

Here is an example to make a list with each item being increasing power of 2.

1. pow2 =[2** x for x in range(10)]


2.
3. # Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
4. print(pow2)

This code is equivalent to

1. pow2 =[]
2. for x in range(10):
3. pow2.append(2** x)

A list comprehension can optionally contain more for or if statements. An


optional ifstatement can filter out items for the new list. Here are some examples.

1. >>> pow2 =[2** x for x in range(10)if x >5]


2. >>> pow2
3. [64,128,256,512]
4. >>> odd =[x for x in range(20)if x %2==1]
5. >>> odd
6. [1,3,5,7,9,11,13,15,17,19]
7. >>>[x+yfor x in['Python ','C ']for y in['Language','Programming']]
8. ['Python Language','Python Programming','C Language','C Programming']

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

Other List Operations in Python


List Membership Test
We can test if an item exists in a list or not, using the keyword in.
1. my_list=['p','r','o','b','l','e','m']
2.
3. # Output: True
4. print('p' in my_list)
5.
6. # Output: False
7. print('a' in my_list)
8.
9. # Output: True
10. print('c'notinmy_list)

Iterating Through a List


Using a for loop we can iterate though each item in a list.
1. for fruit in['apple','banana','mango']:
2. print("I like",fruit)

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: ()

# Tuple having integers

my_tuple = (1, 2, 3)

print(my_tuple) # Output: (1, 2, 3)

# tuple with mixed datatypes

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

my_tuple = (1, "Hello", 3.4)

print(my_tuple) # Output: (1, "Hello", 3.4)

# nested tuple

my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

# Output: ("mouse", [8, 4, 6], (1, 2, 3))

print(my_tuple)

A tuple can also be created without using parentheses. This is known as tuple packing.

my_tuple = 3, 4.6, "dog"

print(my_tuple) # Output: 3, 4.6, "dog"

# tuple unpacking is also possible

a, b, c = my_tuple

print(a) #3

print(b) # 4.6

print(c) # dog

Creating a tuple with one element is a bit tricky.

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")

print(type(my_tuple)) # <class 'str'>

# Creating a tuple having one element

my_tuple = ("hello",)

print(type(my_tuple)) # <class 'tuple'>

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

# Parentheses is optional

my_tuple = "hello",

print(type(my_tuple)) # <class 'tuple'>

Access Tuple Elements


There are various ways in which we can access the elements of a tuple.

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'

# IndexError: list index out of range

# print(my_tuple[6])

# Index must be an integer

# TypeError: list indices must be integers, not float

# my_tuple[2.0]

# nested tuple

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

# nested index

print(n_tuple[0][3]) # 's'

print(n_tuple[1][1]) #4

2. 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.

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')

# elements 2nd to 4th

# Output: ('r', 'o', 'g')

print(my_tuple[1:4])

# elements beginning to 2nd

# Output: ('p', 'r')

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

print(my_tuple[:-7])

# elements 8th to end

# Output: ('i', 'z')

print(my_tuple[7:])

# elements beginning to end

# 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.

We can also assign a tuple to different values (reassignment).

my_tuple = (4, 2, 3, [6, 5])

# TypeError: 'tuple' object does not support item assignment

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

# my_tuple[1] = 9

# However, item of mutable element can be changed

my_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5])

print(my_tuple)

# Tuples can be reassigned

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.

But deleting a tuple entirely is possible using the keyword del.


my_tuple = ('p','r','o','g','r','a','m','i','z')

# can't delete items


# TypeError: 'tuple' object doesn't support item deletion
# delmy_tuple[3]

# Can delete an entire tuple


delmy_tuple

# NameError: name 'my_tuple' is not defined

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

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

count(x) Returns the number of items x

index(x) Returns the index of the first item that is equal to x

Python Tuple Method

Some examples of Python tuple methods:

my_tuple = ('a','p','p','l','e',)

print(my_tuple.count('p')) # Output: 2
print(my_tuple.index('l')) # Output: 3

Other Tuple Operations


1. Tuple Membership Test
We can test if an item exists in a tuple or not, using the keyword in.

my_tuple = ('a','p','p','l','e',)

# In operation

# Output: True

print('a' in my_tuple)

# Output: False

print('b' in my_tuple)

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

# Not in operation

# Output: True

print('g' not in my_tuple)

2. Iterating Through a Tuple


Using a for loop we can iterate through each item in a tuple.
# Output:

# Hello John

# Hello Kate

for name in ('John','Kate'):

print("Hello",name)

Advantages of Tuple over List

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.

Dictionaries are optimized to retrieve values when the key is known.

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

How to create a dictionary?


Creating a dictionary is as simple as placing items inside curly braces {} separated by
comma.

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().

How to access elements from a dictionary?


While indexing is used with other container types to access values, dictionary uses keys.
Key can be used either inside square brackets or with the get() method.
The difference while using get() is that it returns None instead of KeyError, if the key is not
found.
my_dict = {'name':'Jack', 'age': 26}

# Output: Jack

print(my_dict['name'])

# Output: 26

print(my_dict.get('age'))

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

# Trying to access keys which doesn't exist throws error

# my_dict.get('address')

# my_dict['address']

When you run the program, the output will be:

Jack
26

How to change or add elements in a dictionary?


Dictionary are mutable. We can add new items or change the value of existing items
using assignment operator.

If the key is already present, value gets updated, else a new key: value pair is added to
the dictionary.

my_dict = {'name':'Jack', 'age': 26}

# update value

my_dict['age'] = 27

#Output: {'age': 27, 'name': 'Jack'}

print(my_dict)

# add item

my_dict['address'] = 'Downtown'

# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}

print(my_dict)

When you run the program, the output will be:

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

{'name': 'Jack', 'age': 27}


{'name': 'Jack', 'age': 27, 'address': 'Downtown'}

How to delete or remove elements from a


dictionary?
We can remove a particular item in a dictionary by using the method pop(). This method
removes as item with the provided key and returns the value.
The method, popitem() can be used to remove and return an arbitrary item (key, value)
form the dictionary. All the items can be removed at once using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary
itself.
# create a dictionary

squares = {1:1, 2:4, 3:9, 4:16, 5:25}

# remove a particular item

# Output: 16

print(squares.pop(4))

# Output: {1: 1, 2: 4, 3: 9, 5: 25}

print(squares)

# remove an arbitrary item

# Output: (1, 1)

print(squares.popitem())

# Output: {2: 4, 3: 9, 5: 25}

print(squares)

# delete a particular item

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

del squares[5]

# Output: {2: 4, 3: 9}

print(squares)

# remove all items

squares.clear()

# Output: {}

print(squares)

# delete the dictionary itself

del squares

# Throws Error

# print(squares)

When you run the program, the output will be:

16
{1: 1, 2: 4, 3: 9, 5: 25}
(1, 1)
{2: 4, 3: 9, 5: 25}
{2: 4, 3: 9}
{}

Python Dictionary Methods


Methods that are available with dictionary are tabulated below. Some of them have
already been used in the above examples.

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

Method Description

clear() Remove all items form the dictionary.

copy() Return a shallow copy of the dictionary.

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).

items() Return a new view of the dictionary's items (key, value).

keys() Return a new view of the dictionary's keys.

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.

values() Return a new view of the dictionary's values

Python Dictionary Methods

Here are a few example use of these methods.

marks = {}.fromkeys(['Math','English','Science'], 0)

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

# Output: {'English': 0, 'Math': 0, 'Science': 0}

print(marks)

for item in marks.items():

print(item)

# Output: ['English', 'Math', 'Science']

list(sorted(marks.keys()))

Python Dictionary Comprehension


Dictionary comprehension is an elegant and concise way to create new dictionary from
an iterable in Python.

Dictionary comprehension consists of an expression pair (key: value) followed


by forstatement inside curly braces {}.

Here is an example to make a dictionary with each item being a pair of a number and its
square.

squares = {x: x*x for x in range(6)}

# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

print(squares)

This code is equivalent to

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.

odd_squares = {x: x*x for x in range(11) if x%2 == 1}

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

# Output: {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

print(odd_squares)

Other Dictionary Operations


Dictionary Membership Test
We can test if a key is in a dictionary or not using the keyword in. Notice that
membership test is for keys only, not for values.
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

# Output: True

print(1 in squares)

# Output: True

print(2 not in squares)

# membership tests for key only not value

# Output: False

print(49 in squares)

Iterating Through a Dictionary


Using a for loop we can iterate though each key in a dictionary.
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

for i in squares:

print(squares[i])

Built-in Functions with Dictionary


Built-in functions like all(), any(), len(), cmp(), sorted() etc. are commonly used with
dictionary to perform different tasks.

Function Description

all() Return True if all keys of the dictionary are true (or if the dictionary is empty).

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

Return True if any key of the dictionary is true. If the dictionary is empty,
any() return False.

len() Return the length (the number of items) in the dictionary.

cmp() Compares items of two dictionaries.

sorted() Return a new sorted list of keys in the dictionary.

Built-in Functions with Dictionary

Here are some examples that uses built-in functions to work with dictionary.

squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

# Output: 5

print(len(squares))

# Output: [1, 3, 5, 7, 9]

print(sorted(squares))

Other built-in Types


Type

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)

# Python code type() with a single object parameter


x=5
s = "geeksforgeeks"
y = [1,2,3]
print(type(x))

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

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'>

NoneType object indicates no value.


If you try to print the value of the NoneType object, it does not print anything on Python
interpreter console.

When is NoneType used?

It is useful in many places.

It is the default return type of the function when the function does not return any value.

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

Use cases (Examples):

 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 ???

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

ErrorName: error reason


The traceback object is just a data item that holds the stack trace information for an
exception and is created when an exception occurs. If a handler is provided for an
exception, this handler is given access to the traceback object.

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 = 'abcde'

>>> foostr[::-1]

'edcba'
>>> foostr[::-2]

'eca'
>>> foolist = [123, 'xba', 342.23, 'abc']

>>> foolist[::-1]

['abc', 342.23, 'xba', 123]

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

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

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.

Standard Type Operators

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

Standard Type Value Comparison Operators

Operator Function

expr1 < expr2 expr1 is less than expr2

expr1 > expr2 expr1 is greater than expr2

expr1 <= expr2 expr1 is less than or equal to expr2

expr1 >= expr2 expr1 is greater than or equal to expr2

expr1 == expr2 expr1 is equal to expr2

expr1 != expr2 expr1 is not equal to expr2 (C-style)

expr1 < > expr2 expr1 is not equal to expr2 (ABC/Pascal-style)

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'

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

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.

Let us take a look at three examples.

Example 1: foo1 and foo2 reference the same object

foo1 = foo2 = 4.3

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.

Below figure shows an object with two references.

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

Figure . foo1 and foo2 reference the same object

Example 2: foo1 and foo2 reference 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.

Example 3: foo1 and foo2 reference different objects

foo1 = 4.3

foo2 = 1.3 + 3.0

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.

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

Figure: foo1 and foo2 reference different objects

we can check the address of variable by using id() function

id(foo1)

id(foo2)

Standard Type Object Identity Comparison Operators

Operator Function

obj1 is obj2 obj1 is the same object as obj2

obj1 is not obj2 obj1 is not the same object as obj2

In the example below, we create a variable, then another that points to the same object.

>>> a = [ 5, 'hat', -9.3]


>>> b = a
>>> a is b
True
>>> a is not b
False
>>>
>>> b = 2.5e-5
>>> b
2.5e-005
>>> a
[5, 'hat', -9.3]
>>> a is b
False
>>> a is not b
True
Both the is and not identifiers are Python keywords

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

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

immediately one level below all the comparison operators. The and and or operators
follow, respectively.

Standard Type Boolean Operators

Operator Function

not expr Logical NOT of expr (negation)

expr1 and expr2 Logical AND of expr1 and expr2 (conjunction)

expr1 or expr2 Logical OR of expr1 and expr2 (disjunction)

>>> x, y = 3.1415926536, -1024


>>> x < 5.0
True
>>> not (x < 5.0)
False
>>> (x < 5.0) or (y > 2.718281828)
True
>>> (x < 5.0) and (y > 2.718281828)
False
>>> not (x is y)
True

Categorizing the Standard Types


If we were to be maximally verbose in describing the standard types, we would probably call
them something like Python's "basic built-in data object primitive types."
 "Basic," indicating that these are the standard or core types that Python provides
 "Built-in," due to the fact that these types come by default in Python
 "Data," because they are used for general data storage
 "Object," because objects are the default abstraction for data and functionality
 "Primitive," because these types provide the lowest-level granularity of data storage
 "Types," because that's what they are: data types!

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

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

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

Storage Model Category Python Types That Fit Category

Scalar/atom Numbers (all numeric types), strings (all are literals)


Container Lists, tuples, dictionaries

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.

Types Categorized by the Update Model


Update Model Category Python Types That Fit Category
Mutable Lists, dictionaries
Immutable Numbers, strings, tuples
I've done things like the following":
x = 'Python numbers and strings'
x = 'are immutable?!? What gives?'
i=0
i=i+1
What is really happening behind the scenes is that the original objects are actually being
replaced in the above examples.
Rather than referring to the original objects, new objects with the new values were allocated and
(re) assigned to the original variable names, and the old objects were garbage-collected. One
can confirm this by using the id() BIF to compare object identities before and after such
assignments. If we added calls to id() in our example above, we may be able to see that the
objects are being changed, as below:

>>> x = 'Python numbers and strings'


>>> print id(x)
16191392
>>> x = 'are immutable?!? What gives?'
>>> print id(x)
16191232

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

>>> 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.

Types Categorized by the Access Model


Access Model Category Types That Fit Category
Direct Numbers
Sequence Strings, lists, tuples

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

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.

Table : Categorizing the Standard Types


Data Type Storage Model Update Model Access Model
Numbers Scalar Immutable Direct
Strings Scalar Immutable Sequence
Lists Container Mutable Sequence
Tuples Container Immutable Sequence
Dictionaries Container Mutable Mapping

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.

int versus short versus long


Python's plain integers are the universal "standard" integer type, obviating the need for three
different integer types, e.g., C's int, short, and long. For the record, Python's integers are implemented
as C longs.

float versus double


C has both a single precision float type and double-precision double type. Python's float type is actually a C
double. Python does not support a single-precision floating point type because its benefits are
outweighed by the overhead required to support two types of floating point types.

Number Type Conversion


Python converts numbers internally in an expression containing mixed types to a
common type for evaluation. But sometimes, you need to coerce a number explicitly
from one type to another to satisfy the requirements of an operator or function
parameter.
 Type int(x) to convert x to a plain integer.

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

 Type float(x) to convert x to a floating-point number.

 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 ]

Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand operand. a – b = -10

* Multiplies values on either side of the operator a * b = 200


Multiplication

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand and returns b%a=0
remainder

** Exponent Performs exponential (power) calculation on operators a**b =10 to


the power 20

// 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.

Assume variable a holds 10 and variable b holds 20, then −

[ Show Example ]

Operator Description 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.


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.

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

>= 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 ]

Operator Description 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

**= Exponent Performs exponential (power) calculation on c **= a is equivalent to c


AND operators and assign value to the left operand = c ** a

//= Floor It performs floor division on operators and assign c //= a is equivalent to c

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

Division value to the left operand = c // a

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&b = 0000 1100


a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

There are following Bitwise operators supported by Python language


[ Show Example ]

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in (a & b) (means 0000
both operands 1100)

| Binary OR It copies a bit if it exists in either operand. (a | b) = 61 (means


0011 1101)

^ Binary XOR It copies the bit if it is set in one operand but (a ^ b) = 49 (means
not both. 0011 0001)

~ Binary Ones (~a ) = -61 (means 1100


Complement 0011 in 2's complement
It is unary and has the effect of 'flipping' bits.
form due to a signed
binary number.

<< Binary Left Shift The left operands value is moved left by the
a << 2 = 240 (means

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

number of bits specified by the right operand. 1111 0000)

>> 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 ]

Operator Description Example

and Logical If both the operands are true then condition (a and b) is true.
AND becomes true.

or Logical OR If any of the two operands are non-zero then (a or b) is true.


condition becomes true.

not Logical Used to reverse the logical state of its operand. Not(a and b) is false.
NOT

Used to reverse the logical state of its operand.

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 ]

Operator Description Example

in Evaluates to true if it finds a variable in the specified x in y, here in results in a 1 if x


sequence and false otherwise. is a member of sequence y.

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

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

specified sequence and false otherwise. sequence y.

Identity Operators
Identity operators compare the memory locations of two objects. There are two Identity
operators explained below −

Operator Description Example

is Evaluates to true if the variables on either side of the x is y, here is results in 1 if


operator point to the same object and false otherwise. id(x) equals id(y).

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 ]

Sr.No. Operator & Description

1 **

Exponentiation (raise to the power)

2 ~+-

Complement, unary plus and minus (method names for


the last two are +@ and -@)

3 * / % //

Multiply, divide, modulo and floor division

4 +-

Addition and subtraction

5 >> <<

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

Right and left bitwise shift

6 &

Bitwise 'AND'

7 ^|

Bitwise exclusive `OR' and regular `OR'

8 <= < > >=

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.

The syntax of int() method is:

int(x=0, base=10)

int() Parameters

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

The int() method takes two arguments:

 x - Number or string to be converted to integer object. Default argument is zero.


 base - Base of the number in x. Can be 0 (code literal) or 2-36.

Return value from int()

The int() method returns:

 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)

Example 1: How int() works in Python?


# integer
print("int(123) is:", int(123))

# float
print("int(123.23) is:", int(123.23))

# string
print("int('123') is:", int('123'))

When you run the program, the output will be:

int(123) is: 123


int(123.23) is: 123
int('123') is: 123

Example 2: How int() works for decimal, octal and hexadecimal?


# binary 0b or 0B
print("For 1010, int is:", int('1010', 2))
print("For 0b1010, int is:", int('0b1010', 2))

# octal 0o or 0O
print("For 12, int is:", int('12', 8))
print("For 0o12, int is:", int('0o12', 8))

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

# hexadecimal
print("For A, int is:", int('A', 16))
print("For 0xA, int is:", int('0xA', 16))

When you run the program, the output will be:

For 1010, int is: 10


For 0b1010, int is: 10
For 12, int is: 10
For 0o12, int is: 10
For A, int is: 10
For 0xA, int is: 10

float()
The float() method returns a floating point number from a number or a string.

The syntax for float() is:

float([x])

float() Parameters

The float() method takes a single parameter:

 x (Optional) - number or string that needs to be converted to floating point number


If it's a string, the string should contain decimal points

Parameter
Type Usage

Float number Use as floating number

Integer Use as integer

Must contain decimal numbers. Leading and trailing whitespaces are removed.
Optional use of "+", "-" signs. Could contain NaN, Infinity, inf (lowercase or
String uppercase).

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

Different parameters with float()

The float() method returns:

 Equivalent floating point number if an argument is passed


 0.0 if no arguments passed
 OverflowError exception if the argument is outside the range of Python float

Example 1: How float() works in Python?


# for integers
print(float(10))

# for floats
print(float(11.22))

# for string floats


print(float("-13.33"))

# for string floats with whitespaces


print(float(" -24.45\n"))

# string float error


print(float("abc"))

When you run the program, the output will be:

10.0
11.22
-13.33
-24.45
ValueError: could not convert string to float: 'abc'

Example 2: float() for infinity and Nan(Not a number)?


# for NaN
print(float("nan"))
print(float("NaN"))

# for inf/infinity
print(float("inf"))
print(float("InF"))
print(float("InFiNiTy"))
print(float("infinity"))

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

When you run the program, the output will be:

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.

The syntax of complex() is:

complex([real[, imag]])

complex() Parameters

In general, the complex() method takes two parameters:

 real - real part. If real is omitted, it defaults to 0.


 imag - imaginary part. If imag is omitted, it default to 0.

If the first parameter passed to this method is a string, it will be interpreted as a


complex number. In this case, second parameter shouldn't be passed.

Return Value from complex()

As suggested by the name, the complex() method returns a complex number.

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

Example 1: How to create a complex number in Python?


z = complex(2, -3)
print(z)

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

z = complex(1)
print(z)

z = complex()
print(z)

z = complex('5-9j')
print(z)

When you run the program, the output will be:

(2-3j)
(1+0j)
0j
(5-9j)

Example 2: Create complex Number Without Using complex()

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))

When you run the program, the output will be:

a = (2+3j)
Type of a is <class>
b = (-0-2j)
Type of b is <class>
c = 0j
Type of c is <class>

Operational

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

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.

The syntax of abs() method is:

abs(num)

abs() Parameters

The abs() method takes a single argument:

 num - number whose absolute value is to be returned. The number can be:
a. integer
b. floating number
c. complex number

Return value from abs()

The abs() method returns the absolute value of the given number.

 For integers - integer absolute value is returned


 For floating numbers - floating absolute value is returned
 For complex numbers - magnitude of the number is returned

Example 1: Get absolute value of a number


# random integer
integer = -20
print('Absolute value of -20 is:', abs(integer))

#random floating number

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

floating = -30.33
print('Absolute value of -30.33 is:', abs(floating))

When you run the program, the output will be:

Absolute value of -20 is: 20


Absolute value of -30.33 is: 30.33

Example 2: Get magnitude of a complex number


# random complex number
complex = (3 - 4j)
print('Magnitude of 3 - 4j is:', abs(complex))

When you run the program, the output will be:

Magnitude of 3 - 4j is: 5.0

Python divmod()

The divmod() method takes two numbers and returns a pair of numbers (a tuple)
consisting of their quotient and remainder.

The syntax of divmod() is:

divmod(x, y)

divmod() Parameters

The divmod() takes two parameters:

 x - a non-complex number (numerator)


 y - a non-complex number (denominator)

Return Value from divmod()


The divmod() returns

 (q, r) - a pair of numbers (a tuple) consisting of quotient q and remainder r

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

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.

Example: How divmod() works in Python?


print('divmod(8, 3) = ', divmod(8, 3))
print('divmod(3, 8) = ', divmod(3, 8))
print('divmod(5, 5) = ', divmod(5, 5))

# divmod() with Floats


print('divmod(8.0, 3) = ', divmod(8.0, 3))
print('divmod(3, 8.0) = ', divmod(3, 8.0))
print('divmod(7.5, 2.5) = ', divmod(7.5, 2.5))
print('divmod(2.6, 0.5) = ', divmod(2.6, 0.5))

When you run the program, the output will be:

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.

The syntax of pow() method is:

pow(x, y[, z])

The pow(x, y) is equivalent to:

x**y

pow() Parameters

The pow() method takes three parameters:

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

 x - number which is to be powered


 y - number which is to be powered with x
 z (Optional) - number which is to be used for modulus operation

X y z

Non-negative Integer OR Negative Integer Non-negative Integer May or may not be present

Non-negative Integer OR Negative Integer Negative Integer Should not be present

pow() method parameters cases

Return value from pow()

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 Integer Negative Integer N/A Float

Non-negative
Negative Integer Integer N/A Integer

Negative Integer Negative Integer N/A Integer

Non-negative Integer OR Non-negative Non-negative Integer OR


Negative integer Integer Positive Integer Integer

pow() method return value cases

Example 1: How pow() works in Python?

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

# positive x, positive y (x**y)


print(pow(2, 2))

# negative x, positive y
print(pow(-2, 2))

# positive x, negative y (x**-y)


print(pow(2, -2))

# negative x, negative y
print(pow(-2, -2))

When you run the program, the output will be:

4
4
0.25
0.25

Example 2: pow() with three arguments (x**y) % z


x=7
y=2
z=5

print(pow(x, y, z))

When you run the program, the output will be:

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.

The syntax of round() is:

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

round(number[, ndigits])

round() Parameters

The round() method takes two parameters:

 number - number that is to be rounded


 ndigits (Optional) - number upto which the given number is to be rounded

Return value from round()

The round() method returns:

 (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

Example 1: How round() works in Python?


# for integers
print(round(10))

# for floating point


print(round(10.7))

# even choice
print(round(5.5))

When you run the program, the output will be:

10
11
6

Example 2: Round a number to given ndigits places


print(round(2.665, 2))

# cannot be represented exactly as float


print(round(2.675, 2))

Downloaded by cse gdcw ([email protected])


lOMoARcPSD|57417370

When you run the program, the output will be:

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.

Downloaded by cse gdcw ([email protected])

You might also like