100% found this document useful (11 votes)
7K views1,484 pages

Getting Started With Python Programming

Uploaded by

Poorna28
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (11 votes)
7K views1,484 pages

Getting Started With Python Programming

Uploaded by

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

Getting Started with Python Programming

Check out these Python tutorials and step up for becoming the next data scientist. Choose where to begin, learn at your
own pace:

Unlock the latest Python tutorials – Start it from Scratch


 Introduction to Python
 Future of Python
 Python Environment Setup
 Features of Python
 Why Python is in Demand
 Learn Python through Master Guide
 Top Python Projects with Source Code
 Python for Machine Learning
 Python Case Studies
 Python Syntax
 Python Statement, Indentation, and Comments
 Python Interpreter
 Python Advantages and Disadvantages
 Why Should I Learn Python?
 How a Fresher Get a Job in Python?
 Python Applications
 Python in Healthcare
 Python in Stock Market
 Python Career Opportunities
 Python Variables and Data Types
 Python Variable Scope
 Python Identifiers
 Python Namespace and Scope
 Python Operators
 Python Bitwise Operator
 Python Comparison Operator
 Python Operator Precedence
 Python Numbers
 Python Strings
 Python Data Structures
 Python Lists
 Python Tuples
 Python Dictionaries
 Python Sets and Booleans
 Python Tuples vs Lists
 Sequences and Collections in Python
 Python Decision-Making
 Python Switch
 Python Loops
 Python Functions
 Python Built-in Functions
 Range() Function in python
 Python zip() Function
 Python eval() Function
 Python exec() Function
 Python Function arguments
 Python Recursion
 Python Terminologies Part I
 Python Terminologies Part II
 What’s new in Python 3.6
 Python vs Scala
 Python vs Java
 Python vs R
 Python at Netflix
 How to create a Perfect Python Resume
 Best Python Books
 Python For Beginners – Infographic
 Python Features – Infographic
 Python Career – Infographic

Level up to more exciting and challenging Python tutorials


 Python Classes
 Python Methods
 Python Methods vs Functions
 Constructors in Python
 Python Objects
 Python Inheritance
 Multiple Inheritance in Python
 Python Operator Overloading
 Python property Class
 Python Compilers
 Python Modules
 Python OS Module
 Python pprint Module
 Python sys Module
 Python repr Function
 Python Directory
 Copying Files with Python
 Renaming Files with Python
 Zipping Files with Python
 Python File I/O
 Reading and Writing Files in Python
 Python Slicing and slice() Construtor
 List Comprehension in Python
 Python Iterables
 Python Iterators
 Python Decorators
 Python Generators
 Python Generators vs Iterators
 Closure in Python
 Python array Module
 Generating Random Numbers in Python
 Python Modules-Counter, Defaultdict, Ordereddict, Namedtuple
 Python Counter Module
 Python defaultdict Module
 Python OrderedDict Module
 Python namedtuple() Factory Function
 Python Packages
 Python Modules vs Packages
 Python itertools Module
 Python Date and Time
 Python Datetime Object
 Python Calendar Module
 Lambda expressions in python
 Assert Statements in Python
 Ternary Operators
 Shallow Copy and Deep Copy- Python

Master essential Python skills and evolve as an expert


 Python Errors and Exceptions
 Python Exception Handling
 Python 3 Extensions
 Python Tools
 XML Processing in Python3
 Networking in python 3
 Sending mail with Python 3
 GUI Programming in Python 3
 CGI Programming in Python
 Python Multi-threading
 Multiprocessing with Python
 Python Subprocess module
 Python Regular Expressions
 SciPy with Python
 NumPy with Python
 Accessing Database with Python
 Python Image Processing
 Unit Testing with Python
 Logging in Python
 Serialization in Python
 Python Debugger
 Python Forensics
 Python Virtual Environments and Packages
 Important Python Libraries
 Best Python Web frameworks
 Python Django Framework
 Python Pandas
 Python Flask
 Python PyQT
 Python Interview Questions- Part 1
 Python Interview Questions- Part 2
 Python Project- Drowsiness Detection System
 Python Project- Detecting Fake News
 Python Project- Speech Emotion Recognition
 Python Project- Detecting Parkinson’s Disease
 Python Project- Gender & Age Detection
 Python Project- Breast Cancer Classification

Implement your Python learning and step into the world of Data Science
 Python for Data Scientists
 Data Science with Python
 Python Data Science Environment Setup
 Data Scientist Salary in India
 Data Science Skills
 Data Operations and Data Cleansing
 Processing CSV, JSON, and XLS data
 Python Relational databases
 Python NoSQL databases
 Stemming and Lemmatization
 Data Wrangling and Aggregation
 Python Matplotlib
 Box Plots and Scatter Plots
 Bubble Charts and 3D Charts
 Python Heatmaps
 Histograms and Bar Plots
 Geographical Data and Graph Data
 Time Series Analysis
 Central Tendency and Variance
 Normal, Binomial, Poisson, Bernoulli Distributions
 p-Value and Correlation
 chi-Square Test and Linear Regression

Learn how Python is important for Machine Learning


 Machine Learning with Python
 Python Machine Learning Environment Setup
 Data Preprocessing, Analysis & Visualization- ML
 Training Data and Test Data- ML
 Python Machine Learning Techniques
 Python Machine Learning Algorithms
 Python Machine Learning Applications
 Deep Learning with Python
 Python Deep Learning Environment Setup
 Python Deep Learning Applications
 Python Deep Learning Libraries and Frameworks
 Deep Neural Networks- Deep Learning
 Computational Graphs- Deep Learning

Execute your Python skills to develop Artificial Intelligence


 Artificial Intelligence with Python
 Python Logic Programming- AI
 Python Reinforcement Learning- AI
 Python Natural Language Processing- AI
 Python NLTK Package- AI
 Python Speech Recognition- AI
 Python Heuristic Search- AI
 Python genetic Algorithm – AI
 Python Computer Vision- AI

Python Tutorials

 Python – Introduction
 Python – Features
 Python – Pros and Cons
 Python – Master Guide
 Python – Case Studies
 Python – Demand
 Python – Future
 Python – Create Resume
 Python – Career Opportunities
 Python – How Fresher Gets Job
 Python – Tools
 Python – Top Projects
 Python – Data Science Tutorial
 Python – For Data Science
 Python – Data Science Installation
 Python 3.6 Features
 Python – Install on Windows
 Python – Applications
 Python – Healthcare
 Python – Stock Market
 Python – Syntax
 Python – Comments, Indentations and Statements
 Python – Assert Statements
 Python – Number Types
 Python – Random Number
 Python – Variables and Data Types
 Python – Variable Scope
 Python – Identifiers
 Python – Strings
 Python – Interpreter
 Python – Operators
 Python – Bitwise Operators
 Python – Comparison Operators
 Python – Operator Overloading
 Python – Ternary Operator
 Python – Operator Precedence
 Python – Namespaces
 Python – Decision Making
 Python – Loops in Python
 Python – Implement Switch Case
 Python – Functions
 Python – Function Arguments
 Python – Built-in Functions
 Python – Methods
 Python – Methods vs Functions
 Python – Constructors
 Python – Range() Function
 Python – Zip Function
 Python – Eval Function
 Python – exec Function
 Python – repr Function
 Python – Data Structures
 Python – Lists
 Python – Tuples
 Python – Tuples vs Lists
 Python – Collections Module
 Python – Counters
 Python – Namedtuples
 Python – DefaultDict
 Python – OrderedDict
 Python – Dictionaries
 Python – DateTime
 Python – Modules
 Python – Serialization
 Python – Packages
 Python – Python OS Module
 Python – Python pprint Module
 Python – Virtual Environment
 Python – Modules vs Packages
 Python – Sets & Booleans
 Python – List Comprehension
 Python – Date and Time
 Python – Calendar Module
 Python – Recursion
 Python – Lambda Expression
 Python – Decorators
 Python – Generators
 Python – Iterators
 Python – Generators vs Iterators
 Python – Closures
 Python – Classes
 Python – Object
 Python – Inheritance
 Python – Multiple Inheritance
 Python – Compilers & Interpreters
 Python – ZipFile
 Python – File I/O
 Python – File Handling
 Python – Copy A File
 Python – Shallow & Deep Copy
 Python – Rename A File
 Python – Data File Formats
 Python – Errors and Exceptions
 Python – Exception Handling
 Python – Directories
 Python – Iterables
 Python – Itertool
 Python – Property
 Python – Sequences and Collections
 Python – Stemming & Lemmatization
 Python – Aggregation & Data Wrangling
 Python – Data Cleansing & Operations
 Python – Multithreading
 Python – Regular Expressions
 Python – Debugger
 Python – Multi Processing
 Python – XML Processing
 Python – CGI Programming
 Python – Library
 Python – Matplotlib
 Python – SciPy
 Python – NumPy
 Python – Pandas
 Python – PyQT
 Python – Array Module
 Python – Database Access
 Python – Programming with C
 Python – NoSQL Database
 Python – Relational Database
 Python – Frameworks
 Python – Flask
 Python – Django
 Python – Forensics
 Python – Network Programming
 Python – Image Processing
 Python – Sending Email
 Python – GUI Programming
 Python – Statistics
 Python – Descriptive Statistics
 Python – Probability Distributions
 Python – Linear Regression
 Python – Histogram & Bar Plot
 Python – Bubble & 3D Charts
 Python – Scatter & Box Plots
 Python – Heatmap & Word Cloud
 Python – Geographical Map & Graph
 Python – Time Series
 Python – Unittest
 Python – Logging
 Python – Slice
 Python – Subprocess Module
 Python – sys Module
 Python – Importance for ML
 Python ML – Tutorial
 Python ML – Environment Setup
 Python ML – Data Pre-Processing
 Python ML – Train and Test Set
 Python ML – Techniques
 Python ML – Application
 Python ML – Algorithms
 Python Deep Learning Tutorial
 Python DL – Environment Setup
 Python DL – Application
 Python DL – Python Libraries
 Python DL – Deep Neural Networks
 Python DL – Computational Graphs
 Python AI Tutorial
 Python AI – NLTK
 Python AI – Speech Recognition
 Python AI – NLP Tutorial
 Python AI – Heuristic Search
 Python AI – Genetic Algorithms
 Python AI – Computer Vision
 Python AI – Logic Programming
 Python – Best Python Books
 Python – Reasons Why Learn Python
 Python – Terminologies Part 1
 Python – Terminologies Part 2
 Python vs Scala
 Python vs Java
 Python vs R
 Case Study – Python at Netflix
 Python For Beginners – Infographic
 Python Features – Infographic
 Python Career – Infographic
 Python Project- Detecting Fake News
 Python Project- Speech Emotion Recognition
 Python Project- Detecting Parkinson’s Disease
 Python Project- Gender & Age Detection
 Python Project- Breast Cancer Classification

Python Interview Questions

 Python – Interview Questions Part 1


 Python – Interview Questions Part 2

Python certainly is here for the long run. Are you?

Furthermore, if you have any query, feel free to ask in the comment section.

1. Demystifying Python
2. Python Basic Constructs
3. String Handling in Python
4. Python Data Structures
5. Functional Programming in Python
6. Python Modules
7. Python Packages
8. Deep Dive into Python
9. Python Object-Oriented Programming Concepts
10. File Handling in Python
11. Python Exception Handling
12. Python Data Science Libraries
13. Python Advanced Concepts
14. Popular Python Frameworks
15. Python vs Other Programming Languages
16. Real-time Python Projects

1. Demystifying Python

1. Introduction to Python
2. Python Environment Setup
3. Features of Python
4. Basic Python Syntax
o Statements, Indentation, and Comments
5. 7 Reasons to Learn Python
6. Benefits and Limitations of Python
7. Career in Python
8. Applications of Python
9. Python Compilers and Interpreters Available
10. Getting to Know the Python Interpreter

2. Python Basic Constructs

1. Python Variables
o Python Variable Scope
2. Data Types in Python
3. Python Operators
o Bitwise Operators
o Comparison Operators
o Operator Precedence
o Ternary Operators
4. Python Decision Making
o Switch-case in Python
5. Loops in Python
6. Numbers with Python

3. String Handling in Python

1. String Formatters and Escape Sequences in Python


2. String Functions and Operations in Python
3. Python repr() Function

4. Python Data Structures

1. Python Lists
o List Comprehension
o The array Module
2. Python Tuples
o The zip() Function
o Tuples vs Lists
3. Slicing in Python
4. Python Binary Sequence Types- bytes, bytearray, memoryview
5. Dictionaries in Python
6. Sets in Python
7. Booleans in Python

5. Functional Programming in Python

1. Functions in Python
2. Python Lambda Expressions
3. Function Arguments
4. Python Recursion Function
5. Python Built-in Functions
o range()
o eval()
o exec()
6. Decorators in Python
7. Closure in Python
8. Working with Itertools in Python

6. Python Modules

1. Counter
2. Defaultdict
3. OrderedDict
4. namedtuple
5. Python Numeric Modules- math, decimal, random
6. sys
7. Generating Random Numbers
8. Python datetime Module
9. Python calendar Module

7. Python Packages

1. Python pip and PyPI


2. Python Modules vs Packages

8. Deep Dive into Python

1. Multithreading in Python
2. Working with Date and Time in Python
3. Namespace and Scope in Python
4. Terminologies in Python
5. Deep Copy vs Shallow Copy in Python
6. Assert Statements in Python
7. Python Pretty-Printing with pprint

9. Python Object-Oriented Programming Concepts

1. Methods in Python
o Methods vs Functions
o Magic (Dunder) Methods in Python
2. Classes in Python
3. Python Objects
4. Inheritance in Python
5. Python Multiple Inheritance
6. Python Operator Overloading
7. Generators in Python
8. Iterators in Python
o Generators vs Iterators in Python
9. Python Serialization with pickle
10. Python property Decorator

10. File Handling in Python

1. Reading and Writing Files in Python


2. Managing Directories and Files in Python
3. Python OS Module
4. Python shutil Module
5. Copying Files with Python
6. Renaming Files with Python
7. Zipping Files with Python

11. Python Exception Handling

1. Errors and Exceptions in Python


2. Python Exception Handling
3. Testing with unittest in Python

12. Python Data Science Libraries

1. Python Libraries
2. NumPy
3. SciPy
4. pandas
5. Visualizing with matplotlib
6. PyQT
7. Altair
8. Web Scraping with Scrapy
13. Python Advanced Concepts

1. Regular Expressions with Python


2. Virtual Environments and Packages
3. The Python Debugger (pdb)
4. CGI Programming with Python
5. Understanding urllib
6. XML Processing
7. Sending Mail with Python
8. Networking
9. Processing Images
10. GUI Programming
11. Tools
12. Accessing the Database
13. Logging with Python
14. Multiprocessing

14. Popular Python Frameworks

1. Web Frameworks
2. Django
3. Flask

15. Python vs Other Programming Languages

1. Python vs Java
2. Python vs Scala
3. Python vs R

16. Real-time Python Projects


5 real-time python projects based on industry use cases to master the python language

Python Tutorial for Beginners | How to Quickly Learn Python?


by DataFlair Team · December 17, 2018

In this Python tutorial, we will introduce you to Python Programming. This includes features of Python,
Python architecture and its applications in the industry. Also, we will learn about available python frameworks
like Django, Flask, Pyramid, etc.

There’s a reason they choose Python as an introductory language for programming. Simple, concise, easy-
Python has it all. It also equips you to build so much. All aboard the Python train!

So, let’s start this Python Tutorial.


Python Tutorial for Beginners | How to Quickly Learn Python?

1. What is Python?

The Python programming language is an object-oriented language, which means that it can model real-world
entities. It is also dynamically-typed because it carries out type-checking at runtime. It does so to make sure that
the type of a construct matches what we expect it to be. The distinctive feature about Python is that it is an
interpreted language. The Python IDLE (Integrated Development Environment) executes instructions one line
at a time. This also lets us use it as a calculator.

i. Why is it called Python?


Going into etymology, Guido van Rossum named it after the comedy group Monty Python. That is why the
metasyntactic variables (those we will often use to explain code syntax) used here are ‘spam’ and ‘eggs’ instead
of ‘foo’ and ‘bar’. A lot of implementations today run version 2.x, but the future belongs to Python 3.x. It is also
called ‘Python 3000’ or ‘Py3K’. CPython, written in C, is the most common implementation of Python.

ii. What makes Python so powerful?


Apart from the constructs that Python provides, you can use the PyPI (Python Package Index). It is a repository
of third-party Python modules and you can install it using a program called pip. Run the following command
in Command Prompt:

1. pip install library_name

Python or R: To learn the difference between Python and R, please follow Python vs R. For now let us move
ahead with the current Python tutorial.

2. How was Python Born?


 The Python programming language was conceived in the late 1980s and was named after the BBC TV
show Monty Python’s Flying Circus. Guido van Rossum started implementing Python at CWI in the
Netherlands in December of 1989. This was a successor to the ABC programming language which was
capable of exception handling and interfacing with the Amoeba operating system.
 On October 16 of 2000, Python 2.0 released and it had many major new features including cycle-
detecting garbage collector for memory management and support for Unicode.
 The next version of Python 3.0 released on December 3, 2008.

Now we know how Python came into the picture. So, moving ahead in this Python tutorial, let us jump to
Python Architecture.

3. Python Architecture

Let’s now talk about Python architecture and its usual flow –

i. Parser

It uses the source code to generate an abstract syntax tree.

ii. Compiler

It turns the abstract syntax tree into Python bytecode.

iii. Interpreter

It executes the code line by line in a REPL (Read-Evaluate-Print-Loop) fashion. On Windows, when you want
to run the Python interpreter in the shell, you can type the following:

1. $python

Next in Python tutorial, we discuss some useful Python Constructs to give you a better idea of the structure of
Python code.

4. Python Constructs
Python Tutorial – Python Constructs

i. Functions
A function in Python is a collection of statements grouped under a name. You can use it whenever you want to
execute all those statements at a time. You can call it wherever you want and as many times as you want in a
program. A function may return a value.

ii. Classes
As we discussed earlier, Python is an object-oriented language. It supports classes and objects. A class is an
abstract data type. In other words, it is a blueprint for an object of a certain kind. It holds no values. An object is
a real-world entity and an instance of a class.

iii. Modules
A Python module is a collection of related classes and functions. We have modules for mathematical
calculations, string manipulations, web programming, and many more. We will discuss Python Module in detail
in a later lesson.

iv. Packages
Python package is a collection of related modules. You can either import a package or create your own.

v. List
You can think of a list as a collection of values. Declared in the CSV (Comma-Separated Values) format and
delimit using square brackets:
1. life = [‘love’, ‘wisdom’,
‘anxiety’]; 2. arity = [1,2,3];

Notice that we do not declare the type for the list either. A list may also contain elements of different types, and
the indexing begins at 0:

1. person = [‘firstname’, 21];


2. print(person[1])

Output: 21
You can also slice lists; slicing is a way of retrieving some values from it. We will learn more about it in further
lessons.

vi. Tuple
A tuple is like a list, but it is immutable (you cannot change its values).

1. pizza = (‘base’, ‘sauce’, ‘cheese’, ‘mushroom’);


2. pizza[3] = ‘jalapeno’

This raises a TypeError.

vii. Dictionary
A dictionary is a collection of key-value pairs. Declare it using curly braces, and commas to separate key-value
pairs. Also, separate values from keys using a colon (:).

1. student = {‘Name’: ‘Abc’, ‘Age’: 21}


2. print(student[‘Age’])

Output: 21

viii. Comments and Docstrings


Declare comments using an octothorpe (#). However, Python does not support multiline comments. Also,
docstrings are documentation strings that help explain the code.
#This is a comment
“““
This is a docstring
”””
Python has a lot of other constructs. These include control structures, functions, exceptions, etc. We will discuss
these in further tutorials.

Now let us learn about the features of Python. Based on these features, you will be able to choose a
programming language for your next project.

5. Features of Python

The Python programming language is one of the richest languages. In this Python tutorial, we will discuss
several features of Python:
Python Tutorial – Features of Python Programming Language

i.Easy

Python is very easy to learn and understand; using this Python tutorial, any beginner can understand the basics
of Python.

ii. Interpreted

It is interpreted(executed) line by line. This makes it easy to test and debug.

iii. Object-Oriented

The Python programming language supports classes and objects. We discussed these above.

iv. Free and Open Source

The language and its source code are available to the public for free; there is no need to buy a costly license.

v. Portable

Since it is open-source, you can run Python on Windows, Mac, Linux or any other platform. Your programs
will work without needing to the changed for every machine.

vi. GUI Programming

You can use it to develop a GUI (Graphical User Interface). One way to do this is through Tkinter.

vii. Large Library


Python provides you with a large standard library. You can use it to implement a variety of functions without
needing to reinvent the wheel every time. Just pick the code you need and continue. This lets you focus on other
important tasks.

Now, let us see the frameworks available in Python.

6. Python Frameworks

Python tutorial – Frameworks in Python Programming Langauge

i. Django
Python Django is a free and open-source framework written in Python and is the most common framework for
Python. It allows you to create database-driven websites. It follows the DRY Principle (Don’t Repeat
Yourself). This is a design philosophy that keeps code simple and eloquent.

Popular websites like Instagram, Mozilla, and Disqus make use of it.

ii. Flask
Like Django, Flask is a web framework written in Python itself. It is a micro framework because it does not
need certain libraries and tools. It also does not have form validation or a database abstraction layer. However,
you can make use of extensions to add extra features.
iii. Pyramid
Pyramid is another web framework. It is neither a mega-framework that would make decisions for you nor a
micro-framework that wouldn’t force decisions. It gives you optimal liberty of your project.

iv. Tornado
Another open-source web framework, Tornado is written in Python Language. It is noted for its excellent
performance and scalability.

v. Bottle
Like Flask, it is a micro-framework for Python. It is used for web development. Bottle is known for its speed,
simplicity, and lightweight. A single file can run both Python 2.5+ and 3.x.

vi. web2py
Written in Python, web2py is another open source web framework. It emphasizes on rapid development and
follows an MVC architecture. MVC stands for Model View Controller.

vii. NumPy
NumPy is an open-source framework for Python. We use it for scientific computing. It supports large
multidimensional arrays and matrices, and functions to operate on them.

viii. SciPy
SciPy is a Python library that you can use for scientific computing. It has modules for linear algebra,
interpolation, fast Fourier transform(FFT), image processing, and many more. It uses multidimensional arrays
from the NumPy module.

ix. Pylons
This is a deprecated framework, which means it is no longer recommended. It is a web framework and is open
source as well. It makes extensive use of third-party tools.

7. Flavors of Python

Now, let’s take a look at major Python implementations –


Python Tutorial – Flavors of Python Programming Langauge

i. CPython
This is the most widely accepted implementation of Python. It is written in the language C, and is an interpreter.

ii. Jython
Jython is a Python implementation written in Java. A Jython program can import any Java class. It compiles to
Java bytecode.

iii. IronPython
IronPython is implemented in C#. It can function as an extensibility layer to application frameworks written in a
.NET language.

iv. Brython
Brython stands for Browser Python. It is an implementation of Python that runs in the browser.
v. RubyPython
It acts as a bridge between the Python and Ruby interpreters. It marshals data between Python and Ruby virtual
machines.

vi. PyPy
Interesting to know how PyPy is Python implemented in Python. This makes it faster and easier to experiment
with. However, the standard implementation is CPython.

vii. MicroPython
This is an implementation of Python meant to run on a microcontroller. It uses a MicroPython board that runs
MicroPython on bare metal.

Let’s move ahead in this Python tutorial and learn file extensions of Python.

8. File Extensions in Python

 .py –The normal extension for a Python source file


 .pyc- The compiled bytecode
 .pyd- A Windows DLL file
 .pyo- A file created with optimizations
 .pyw- A Python script for Windows
 .pyz- A Python script archive

9. Python Applications

Python is easy to pick-up even if you come from a non-programming background. You can look at the code and
tell what’s going on. Talking of Python applications, some of the cool things that you can do with Python are –

 Build a website
 Develop a game
 Perform Computer Vision (Facilities like face-detection and color-detection)
 Implement Machine Learning (Give a computer the ability to learn)
 Enable Robotics
 Perform Web Scraping (Harvest data from websites)
 Perform Data Analysis
 Automate a web browser
 Perform Scripting
 Perform Scientific Computing
 Build Artificial Intelligence

Python isn’t limited to these applications. If you’ve ever used services from brands like YouTube, Dropbox,
and Netflix, then you’ve been a consumer of Python. The search-engine Google also made great use of the
language in its initial stages.

When writing code in Python, you need fewer lines of code compared to languages like Java. This high-level
language is also open-source and free. Going by the TIOBE Index, it is among the major programming
languages with the fastest growth. This makes a career in Python a great choice.
To make it clearer about Python, we have covered how it is different from other programming languages like
Java or C++.

10. Python vs Java vs C++

Python uses whitespace indentation to delimit code, you don’t need to use curly braces for that. Also,
semicolons are optional. It has two correct syntaxes :

1. a = 7
2. print(a)

1. a = 7;
2. print(a)

While Java and C++ are statically-typed, Python is dynamically-typed. You also don’t need to declare the type
of a variable; you assign it:

1. life=42

Java is faster by a few seconds, but the difference does not invalidate Python’s advantages over it. Since you
can interpret Python, the code is easier to test and debug.

So, this was all about Python. Hope you liked our explanation.

11. Summary: Python Tutorial

Let’s conclude this Python Tutorial with a quick revision. Today, we discussed Python and how it came to be.
We also took a brief look at its architecture and various constructs. Moreover, we learned about Python
frameworks, and its flavors and file extensions. We then discussed a few Python applications and enquired
about how it is different from Java. Well, Python is a beautiful language and we wish to empower you to create.

Python certainly is here for the long run. Are you?

13 Unique Features of Python Programming Language


by DataFlair Team · August 26, 2019

1. Features of Python Programming Language

At some point in time, we had about as many programming languages as we could count on our fingers. Today,
there are so many, and all with their own specialities. But what makes a language unique is its features. And
ultimately, it is its features that get it chosen or passed for a project. So before beginning with deeper concepts
of Python, let’s take a look at the major features of python programming language that give you reasons why
you should learn Python as compared to R or other tool. So lets start with the Features of Python
Programming Language.
Features of Python Programming language

2. Easy

When we say the word ‘easy’, we mean it in different contexts.

a. Easy to code
As we have seen in earlier lessons, Python is very easy to code. Compared to other popular languages like Java
and C++, it is easier to code in Python. Anyone can learn python syntax in just a few hours. Though sure,
mastering Python requires learning about all its advanced concepts and packages and modules. That takes time.
Thus, it is programmer-friendly.

b. Easy to read
Being a high-level language, Python code is quite like English. Looking at it, you can tell what the code is
supposed to do. Also, since it is dynamically-typed, it mandates indentation. This aids readability.
Read: Applications of Python Programming Language

3. Expressive

First, let’s learn about expressiveness. Suppose we have two languages A and B, and all programs that can be
made in A can be made in B using local transformations. However, there are some programs that can be made
in B, but not in A, using local transformations. Then, B is said to be more expressive than A. Python provides us
with a myriad of constructs that help us focus on the solution rather than on the syntax. This is one of the
outstanding python features that tells you why you should learn Python.

4. Free and Open-Source


Firstly, Python is freely available. You can download it from the following link
https://www.python.org/downloads/
For insight on how to download and install Python, refer to our tutorial on Python Installation.
Secondly, it is open-source. This means that its source code is available to the public. You can download it,
change it, use it, and distribute it. This is called FLOSS(Free/Libre and Open Source Software). As the Python
community, we’re all headed toward one goal- an ever-bettering Python.

5. High- Level
As we discussed in point 2b, it is a high-level language. This means that as programmers, we don’t need to
remember the system architecture. Nor do we need to manage the memory. This makes it more programmer-
friendly and is 1 of the key python features.Any doubt yet in the features of Python. Please ask.

6. Portable

Let’s assume you’ve written a Python code for your Windows machine. Now, if you want to run it on a Mac,
you don’t need to make changes to it for the same. In other words, you can take one code and run it on any
machine, there is no need to write different code for different machines. This makes Python a portable language.
However, you must avoid any system-dependent features in this case.

7. Interpreted

If you’re any familiar with languages like C++ or Java, you must first compile it, and then run it. But in Python,
there is no need to compile it. Internally, its source code is converted into an immediate form called bytecode.
So, all you need to do is to run your Python code without worrying about linking to libraries, and a few other
things.
By interpreted, we mean the source code is executed line by line, and not all at once. Because of this, it is easier
to debug your code. Also, interpreting makes it just slightly slower than Java, but that does not matter compared
to the benefits it has to offer.
Any doubt or query yet about the features of python programming language? If yes, Drop a comment and we
will get back to you.

8. Object-Oriented

A programming language that can model the real world is said to be object-oriented. It focuses on objects, and
combines data and functions. Contrarily, a procedure-oriented language revolves around functions, which are
code that can be reused. Python supports both procedure-oriented and object-oriented programming which is
one of the key python features. It also supports multiple inheritance, unlike Java. A class is a blueprint for such
an object. It is an abstract data type, and holds no values.
9. Extensible

If needed, you can write some of your Python code in other languages like C++. This makes Python an
extensible language, meaning that it can be extended to other languages.
Let us look at some more Python features.

10. Embeddable
We just saw that we can put code in other languages in our Python source code. However, it is also possible to
put our Python code in a source code in a different language like C++. This allows us to integrate scripting
capabilities into our program of the other language.

11. Large Standard Library

Python downloads with a large library that you can use so you don’t have to write your own code for every
single thing. There are libraries for regular expressions, documentation-generation, unit-testing, web browsers,
threading, databases, CGI, email, image manipulation, and a lot of other functionality.

12. GUI Programming

You can use Tk to create basic GUIs.

13. Dynamically Typed

Python is dynamically-typed. This means that the type for a value is decided at runtime, not in advance. This is
why we don’t need to specify the type of data while declaring it.
This is all about the features of python programming language tutorial. lets get to the conclusion.

14. Features of Python: Conclusion

Now that you know what are the features of python, you know what makes it special. In this tutorial, we learned
about various features of Python. We saw that it is interpreted, dynamically-typed, and object-oriented, among
other python features. It is also portable, free, and easy. Now that’s some motivation to dive into the world of
Python.

Hope you like the Features of Python Programming Tutorial.

If you have any query regarding the features of python programming language, drop a comment below and we
will get back to you.

Refer Top Python Books to deep dive into the Python Programming.

Advantages and Disadvantages of Python Programming Language


by DataFlair Team · December 3, 2018

1. Advantages and Disadvantages of Python Programming Language

When we want to choose a language for a project, we want to be thorough with what we can do with it. We
want to be aware of how it can help us be efficient at what we want to do, but we also want to be careful of the
problems that can arise. So, we believe it is worthwhile to take out some time and find out more. In this
advantages and disadvantages of the Python programming language tutorial, we will learn the advantages and
disadvantages of a python programming language that will help you in knowing the benefits of learning Python
programming.
Advantages and Disadvantages of Python Programming Language

2. Advantages of Python Programming Language

Let’s see why Python is cool.

a. Extensive Libraries
Like we mentioned in our article on Python features, it downloads with an extensive library. These contain
code for various purposes like regular expressions, documentation-generation, unit-testing, web browsers,
threading, databases, CGI, email, image manipulation, and more. So, we don’t have to write the complete code
for that manually.

b. Extensible
As we have seen earlier, Python can be extended to other languages. You can write some of your code in
languages like C++ or C. This comes in handy, especially in projects.

c. Embeddable
Complimentary to extensibility, Python is embeddable as well. You can put your Python code in your source
code of a different language, like C++. This lets us add scripting capabilities to our code in the other language.

d. Improved Productivity
The language’s simplicity and extensive libraries render programmers more productive than languages like Java
and C++ do. Also, the fact that you need to write less lets more get done.

e. IOT Opportunities
Since Python forms the basis of new platforms like Raspberry Pi, it finds the future bright for Internet Of
Things. This is a way to connect the language with the real world.

f. Simple and Easy


When working with Java, you may have to create a class to print ‘Hello World’. But in Python, just a print
statement will do. It is also quite easy to learn, understand, and code. This is why when people pick up Python,
they have a hard time adjusting to other more verbose languages like Java.

g. Readable
Because it is not such a verbose language, reading Python is much like reading English. This is also why it is so
easy to learn, understand, and code. It also does not need curly braces to define blocks, and indentation is
mandatory. This further aids the readability of the code.

h. Object-Oriented
This language supports both the procedural and object-oriented programming paradigms. While functions help
us with code reusability, classes and objects let us model the real world. A class allows the encapsulation of data
and functions into one.

i. Free and Open-Source


Like we said earlier, Python is freely available. But not only can you download python for free, but you can also
download its source code, make changes to it, and even distribute it. It downloads with an extensive collection
of libraries to help you with your tasks.

j. Portable
When you code your project in a language like C++, you may need to make some changes to it if you want to
run it on another platform. But it isn’t the same with Python. Here, you need to code only once, and you can run
it anywhere. This is called Write Once Run Anywhere (WORA). However, you need to be careful enough not to
include any system-dependent features.

k. Interpreted
Lastly, we will say that it is an interpreted language. Since statements are executed one by one, debugging is
easier than in compiled languages.
Python Pros and Cons

3. Disadvantages of Python Programming Language

So far, we’ve seen why Python is a great choice for your project. But if you must choose it, you should be aware
of its consequences as well. Let’s now see the downsides of choosing Python over another language.

a. Speed Limitations
We have seen that Python code is executed line by line. But since Python is interpreted, it often results in slow
execution. This, however, isn’t a problem unless speed is a focal point for the project. In other words, unless
high speed is a requirement, the benefits offered by Python are enough to distract us from its speed limitations.

b. Weak in Mobile Computing and Browsers


While it serves as an excellent server-side language, Python is much rarely seen on the client-side. Besides that,
it is rarely ever used to implement smartphone-based applications. One such application is called Carbonnelle.
The reason it is not so famous despite the existence of Brython is that it isn’t that secure.

c. Design Restrictions
As you know, Python is dynamically-typed. This means that you don’t need to declare the type of variable
while writing the code. It uses duck-typing. But wait, what’s that? Well, it just means that if it looks like a duck,
it must be a duck. While this is easy on the programmers during coding, it can raise run-time
errors. In Any query regarding the advantages and disadvantages of Python programming language, tutorial feel
free to drop a comment.

d. Underdeveloped Database Access Layers


Compared to more widely used technologies like JDBC (Java DataBase Connectivity) and ODBC (Open
DataBase Connectivity), Python’s database access layers are a bit underdeveloped. Consequently, it is less often
applied in huge enterprises.

e. Simple
No, we’re not kidding. Python’s simplicity can indeed be a problem. Take my example. I don’t do Java, I’m
more of a Python person. To me, its syntax is so simple that the verbosity of Java code seems
unnecessary. This was all about the Advantages and Disadvantages of Python Programming Language.

4. Conclusion – Advantages and Disadvantages of Python Programming Languages

Concluding the tutorial on advantages and disadvantages of Python Programming Language I would say while
there are some speed, security, and runtime issues, Python is a great language to pick up. Its popularity speaks
for itself. And this popularity is attributed to its being free, easy, interpreted, object-oriented, extensible,
embeddable, portable, and readable. Now that you know the advantages and disadvantages of python
programming language, tell us in the comments if you would choose it for your next project. We would love to
hear from you.

Hope you like the Advantages and Disadvantages of Python Programming Language Tutorial

Learn Python through the Master Guide – Python Notes for


Beginner to Advanced Learners
by DataFlair Team · September 10, 2019

The best way to initiate your steps towards any new language after choosing the language you want to learn is
mind mapping the process you will go about throughout the learning process. It basically starts with how you
plan to learn the language, followed by the sequence of topics you will cover to become completely skilled in
that language. Once you have the idea of what are the major sections to cover with possible background
information,
you will be able to cope up well with language and the knowledge gaining procedure too! The same thing will
happen when you learn Python programming language with DataFlair.

Focusing on how to plan so that one can keep up with the changes that usually and gradually take place in a
growing language like Python. We recommend you to code every day and side by side following the sessional
topics. Start with 25-30 mins on a daily basis, it will help you to develop that muscle memory.

While you move from one Python topic to another, do take time to make notes and jot down information that
you will require for the long-term. This has proven beneficial for users who are aiming to become a full-time
developer. This habit of making Python notes can help you plan your code before you move to the computer
when you go for any small/big projects.

With these strategies, you are ready to learn Python. I’m providing the complete series of Python and its
resources so that you can have exposure to other topics not listed here and explore the best in Python.

Learn Python Programming from Scratch

Python notes for beginners


 Introduction
 Syntax
 Statement, Indentation, and Comments
 Variables and Datatypes
 Operators
 Numbers
 Strings
 Data structure
 List
 Tuples

Python notes for intermediates


 Module
 Classes
 Methods
 Iterators
 Decorators
 Generators

Python notes for advanced learners


 Web framework
 Machine Learning
 Deep learning
 Artificial Intelligence
 Relational Database

These blogs are not supposed to be accessed and learned at once. As suggested above, one can plan out the
whole process to learn Python and then navigate through them according to their grasping capabilities and
practice.
Python Notes

Now, in these python notes, the first part is learning Python beginner-level topics

Learn Python Beginner Level Topics


Below is the list of Python topics for beginners that will help you to learn Python from scratch

1. Python basic tutorial


It covers a general introduction of the Python language with its key features, architecture, and applications. It
will provide you with answers to questions like- why choose python and what its future holds.

For further reference


-Features
-Applications
-Future opportunities

2. Python syntax
Door to learn any language, not only technical but any language in general, one has to have strong command on
its grammar. Grammar in a technical scenario means syntax. It will demonstrate to you how Python’s syntax is
different than Java and C++. You will unfold the use of different identifiers and variables and also how they are
different from each other.

3. Python statements, indentation and comments


As you are getting used to Python and its syntax, you can move forward with the next level of understanding,
i.e. statements and indentation. Python overall is not considered a strict language to follow, the only thing that is
needed to be taken care of is the indentation. It increases its reliability and effectiveness.

Throughout the journey of learning Python, conditional statements like ‘if’, ‘for’, ‘while’ etc will be observed
constructing the logical code for the given problem. Whereas “Python comments” will be used for
understanding the code written by the coder and make changes accordingly. Hence good hold of “comments”
might not help you in coding but will improve your presentation skills of the code when you present it in front
of its target audience.

4. Python variable and datatypes


To give a general idea, we don’t specify the type of a variable when declaring one also there are some set of
rules of naming a variable. Although we don’t declare the type of data, but a value certainly has a type that is
previously known to the interpreter. It includes- integer, float, long, complex, etc.

5. Python Operators
It is responsible for performing various mathematical and logical operations in the code. The operand is a value
on which the operation is performed. 7 main categories are present in which operands are divided for proper
programming from- Arithmetic, Relational, Assignment, Logical, Bitwise, Comparison, Membership, Identity,
etc. So, in the journey of learning Python, Python Operators plays a major role.

6. Python Numbers
An entity that lets you measure something is termed as numbers. It will allow you to dig a little deeper into the
number types of Python, i.e. int, float, complex numbers and so on. Programmers often deal with numbers in
binary, octal and hexadecimal, and their interconversion.

7. Python Strings
It will cover the general introduction of a string ( a sequence of characters ) and its examples. Also, look at
Python string functions and its operations and how to access it.

8. Python Data Structures


Different data structures of python will be covered that includes list, tuple, set and dictionaries. It is nothing
but a way of organizing, storing, and accessing data. According to their advantages and disadvantages, one can
decide which data structure will be suitable.

9. Python List
How to create, access, slice and re-assign list in Python will be discussed. Also, how to apply functions to them
by covering various operations and concatenation. A general idea of the list will be provided in the Data
structures, here you will come across a detailed study. Learn how to delete or reassign elements or list and some
built-in functions and methods.

The next topic in beginner level Python notes is Python Tuples.


10. Python Tuples
A deeper look than that of Data Structure material and insights of how to create, access, slice, delete tuples.
Also, look into inbuilt functions, methods, and operations that can be called on a tuple.

Before moving forward to the next level of learn Python mission do take a while to understand the building
blocks of Python language. You do not need to learn “all” the Python syntax before you start to do something
interesting with it but you should have a good hold on the basics mentioned above. But don’t spend months on
it, with practice and good revision plan one can easily grasp the concepts.

Learn Python Intermediate Level Topics


The next level in learns Python mission is intermediate level. So, let’s start exploring Python notes –

1. Python Module
Learn about modules- how to create them, import modules in python, how can we execute module as a script,
standard python modules, python dir functions and lot more! Have a glance at packages vs modules section to
get an idea of Packages too and their advantages and disadvantages over each other!

No idea about Packages? Work it out here! – Python Packages Guide

2. Python Classes
It is nothing but a blueprint for objects. Explore more about how they work and access. Different attributes
belonging to a python class with its objects is discussed. As python is an object-oriented language, it focuses on
objects more than procedures. Though it is too much to take in, still have good hands-on these concepts as their
understanding will help a lot later.

3. Python Methods
Much like functions, they are labels that you can call on an object; a piece of code to execute on that object. At
the end of it, you will know how to define and make use of _init_ method, and also a self parameter. Here and
onwards, have a good hold on data structure for better combinational implementation.

Can’t differentiate between Functions & Methods? Refer here! – Python Methods vs Functions

4. Python Iterators
Create your own methods with Python Iterators. Also, create ‘for loop’ in iterators, infinite python iterators,
and benefits of iterators with examples. After their complete understanding, they become handy and very
interesting to use.

5. Python Decorators
What are they and why we use them, all here! Also, along with this, cover decorators with Parameters and Pie
syntax. Decorators, nothing but help add extra functionality to a function without modifying it.

6. Python Generators
Generators are kind of iterators that generate for us a sequence of values that we can iterate on. Example: Use
it to iterate on a for-loop in python, but you can’t index it.

Before you start diving into the supreme and advance level of learn python mission, it’s good that you ask
yourself ‘why you want to learn it?’ This is because Python has a ‘sea’ of applications and each one of them is
in the growing stage. So is going to be a long journey and sometimes painful too! Figuring out what actually
you want to pursue will really help to find the end goal and set paths towards it.

Learn Python Advanced Level Topics


Ready to explore Python notes for advanced level topics? Let’s start with Python and web framework –

1. Python & Web-Framework


If web-development is the goal then python will provide help with a range of frameworks. It includes a full-
stack framework and a non-full stack framework. It allows developers to write web applications and services
without worrying about protocols or thread management. Example: Django, Flask, etc.

For Reference-

Django

Flask

2. Python & Machine Learning


It aims to grant machines the ability to learn by using various techniques. Data is used to learn from and make
further predictions in various applications. Python has a number of characteristics that make it the language to
be chosen for Machine learning and its uses in the industry.

Python has a major contribution in Machine learning application. Know how!

3. Python & Deep Learning


Discuss what exactly is deep learning and why Python adds glory to it? Also, see its uses in artificial neural
networks and deep neural networks. Look into some deep learning applications and their analysis to the reason
why Python?

4. Python & Artificial Intelligence


Starting with a general introduction then AI programming that will include problems, tools and approaches.
With the journey of AI, Natural language processing will be introduced with its components, libraries and its
benefits. We will also come across speech recognition and the NLTK toolkit with their components.

Don’t forget to check the best tutorial on Natural Language Processing

5. Python & Relational Database


It’s working with Python. Learn to read CSV files, insert data into them, and delete data from them using simple
query language-SQL. Come across some important prerequisites of the Relational Database. Pandas is one of
the main Python libraries for data manipulation and analysis.

For reference – Python Pandas Library

These resources are presented in a way that assists your journey of mastering Python. There may be other
possible ways too but this one was found to be very effective and promising as it serves well for mostly all kinds
of users.

Summary

So, here completes our learn Python mission. We all know Python is evolving with time and one cannot
confidently say that he/she has the “complete” knowledge and understanding of Python and its area of
application. A constant need for learning is a requirement to master it to a larger extent. Working on the things
that interest you will take you one notch higher than before. Python is a very rewarding language and with its
help, anyone can do wonders! All you need to do is keep a constant check on what you already know and what
new you need to add on to your skillset.

Hope you like these Python Notes.

Google, Facebook, Netflix, Quora – the


Secret Ingredient – Python!
by DataFlair Team · September 9, 2019

From the time Python has come into existence, its popularity has started rising since then and reached to the tag
of “most-popular programming language” now. Python was and still is the choice for most of the startups
because of its low cost, simplicity and various different frameworks. On top of every other thing, it’s free, open-
source, and has a mighty army of developers that have been formed over the years. Giant companies like
Instagram, Spotify use python and appreciate its use in bulk by others too! Let’s look at some Python Case
Studies or I can say entrepreneurial cases written and solved by Python.
Python Case Studies
Starting with the very first Python case study that is Spotify, then we will discuss other companies like Quora,
Netflix, Google, and Facebook.

Spotify
One of the music streaming giant which is using Python as its sword primarily for data analysis and backend
services. It is one of the major market players and amongst top Python users. Overall backend communication
takes place with the use of ZeroMQ, an open networking framework written in Python and in C++. The reason
behind the choice of Python’s services is the fast development pipeline during coding. The suggestions and
recommendations on Spotify largely depend upon volumes of data analytics. Hence as an interpreter for this
stream of data, Spotify uses Luigi, a Python module that syncs with Hadoop. This is how Spotify also manages
functions such as “Radio and Discovery”. Python handles how libraries work together and cross-check errors
quickly to allow troubleshooting and redeployment. Around 6000 individual processes work together now in
Spotify over the nodes of the Hadoop cluster.

Quora
So, after knowing how Spotify works using Python, now let’s move on to another Python case study that is
Quora. It is a social network platform of question and answer. There was a lot of consideration before choosing
Python amongst C#, Java, and Python. Lack of type checking and relative slow behavior was drawing back the
interest from python. They also had reasons for not choosing other languages. They didn’t go with C# because
of it’s proprietary Microsoft Language and didn’t want to put efforts to cope up with future updates to it. For
Java, its strict syntax was enough to get rejected. Also, Java was a little less older in the market so there were
doubts about its future growths. So the founders of Quora got inspired by Google and choose Python for its ease
of writing and readability. They got rid of their initial problem of type checking by writing unit tests that
accomplish the same
thing. Another reason for the choice was again the good framework support that python provided, such as
Django and Pylons. Having Python and JS together for handling user interactions was also a plus point.

Netflix
The use of Python by Netflix is very similar to that by Spotify. That is they rely on python for data analysis of
the server-side. A significant increase in the number of users of Python in Netflix itself is because they allow
their engineers to choose the language of code. They prefer the standard and third-party libraries and enjoy the
extremely active community. Also, Python is so easy to develop that the developers are left with no choice other
than python! The primary use of Python is in the Central Alert Gateway. This app process alerts, suppressing
the duplicate ones and then route them to people that need to see them. This app has proven to a good addition
to Netflix as it can give automated solutions to shaky problems such as terminating the process or rebooting.
Secondly, the monkey app used to track down security and history issues has also proven to be a hit. It is also
used to ensure to track dozens of SSL certificates related to Netflix’s domain.

DataFlair has published this Netflix Python Case Study in detail. Have a look – how Netflix uses Python

Facebook
This platform is an exceptional user of python because of its developer’s extensive use of the language. This is
so because of the Python libraries and framework reduce the “code-load” and they can majorly focus on
“actual” improvements. It is also noticed that the infrastructure of Facebook has become more scale efficient.

According to a 2016 post by Facebook, “Python is currently responsible for multiple services in infrastructure
management.”

There are various Py3 written projects of Python that were published by Facebook including Facebook Ads API
and a Python async IRC bot framework.
Facebook, upgrading their infrastructure and handlers to 3.4 from 2, and guess who is helping their engineers in
the process – AsyncIO!

Google
Above any company, Google has been a super supporter of Python, that too from the very beginning. There
decision – “Python where we can, C++ where we must” stated that python will be implemented for enabling
ease of maintenance and relatively fast delivery than C++.

Some scripts which were originally written in Perl or Bash were re-coded into Python. It is now the official
Google server-side language. To top it all off, Peter Norvig said:

“Python has been an important part of Google since the beginning and remains so as the system grows and
evolves. Today dozens of Google engineers use Python, and we’re looking for more people with skills in this
language.”

Summary
Python initially was used as a language for drafts as it was simple and cheap. But as we know that “simple is
reliable” and so is python. Many companies learned it later and a lot harder way that more parts a mechanism
has more mess it creates. That is why they choose python and now it covers most of the world’s popular apps
built-
in mechanisms. It is proved in black and white by Python that an amazing product can be backed up by simple
and time-honored tools. As long as the users are satisfied with the performance, there is no loss!

Hope you liked these top Python case studies. I am sure you also want to share some more amazing Python case
studies, do share them with comments.

Learn everything about Python through DataFlair’s best ever Python Tutorial Series. Save this now for FREE
and you can thank me later

What are the Reasons behind Increasing Demand for Python?


by DataFlair Team · July 17, 2019

With every inch of time, we move forward, we can observe that Artificial intelligence and Machine Learning
are becoming the shine on the eyes of every developer. Which is why, beginner or expert, all are driving the
“popularity traffic” towards Python. This is the reason for the increase in Python demand.

Claimed by some old school coders/working professionals, there are some negative conceptions concerning
with the “non-serious” nature of Python. Yet still, increasing demand of python programmers seems to be at
odds with this idea. For proving the same DataFlair have set down some key points.

Why Python Demand is high?


Below are the reasons for the increase in demand for Python –
1. Data Science
Python holds a special place in the hearts of Data Scientists compared to any available language, such as R or
C++. Data Science is all about dealing with data at huge amounts (Big Data). Hence with simple usage and a
large set of libraries and frameworks, Python has become the most promising option to handle it! e.g. PyBrain,
PyMySQL, and NumPy are one of the big reasons. Another step forward is because of Python’s easy integration
with other programming languages, making it more scalable and future-oriented.

2. Machine Learning
Python being an interpreted language makes it comprehensive enough for the language to be interpreted by
virtual machine against any other machine language which is what the hardware understands. It can even be
used in complicated scenarios by making use of variables, objects, complex arithmetic or boolean expressions
and other concepts to make its demand and usability increase exponentially. Even the growth of machine
learning has been phenomenal in the last couple of years and is rapidly changing everything around us.
Algorithms are becoming sophisticated every day. Examples are: Google’s search algorithms and Uber are
completely driven by algorithms. The machine learning libraries compared to Java, found more content around
Python as the current preference of the developer community is Python over anything else for machine learning.

3. Web Development
While concerning backend development, Python is chosen by 2 out of 3 developers who initially worked with
PHP. Python’s trend has been witnessing a steep upward in the past two years as it is serving as a better
alternative. It offers so many good libraries and frameworks, e.g. Flask and Django, which make web
development easy. After adopting Python some of the product based platforms have become the biggest names
– YouTube, Instagram, Facebook, Google, Netflix, and Spotify. Considering the general perception towards
python, in web development Python creates more robust code that can be used to form versatile use cases.

4. Simplicity
Single yet the biggest reason for beginners to learn Python. Whenever you decide to start learning
programming and coding, you don’t want to start with a programming language that is complex in syntax and
tough with rules. Python is readable as well as simple. It’s even easy to set up Python; There’s nothing like
classpath problems like that in Java and compiler issues present in C++. Just install it and run it! Whenever you
write something in Python, you will want to show off to others as it is so elegant to look, not generally in the
case with typically written languages.

5. Huge Community
Mostly decision are community influenced and when to learn something new you need a community and friends
which serve as your biggest asset. Thanks to Google, many solutions to single Python-related problem can be
found out in minutes. With the progression of time, learning python has become the new “cool” in the
programming community. As Python has such vast use cases like development, scientific application, scripting
and so on, hence it brings many Python experts together. The more the merrier!
6. Libraries and Frameworks
Not just a framework but it has got “superior framework”. Django is the clear winner when python’s
frameworks are considered. Frameworks are easy to use, secure and fast. Mostly developers prefer these
frameworks, as their use results in shorter development time and ease of setup. The richer the framework, more
deeper one should learn as it will translate into a lot of long-term valuable results.

7. Automation
You are required to write test scripts to automate tasks, that’s where Python comes into existence in automation.
You’ll be impressed with the time and the number of lines required to write codes for tools. As python supports
with lots of tools and modules, it makes things easier and even highlight the power of Python. With basic
python codes, one can reach the advanced level of automation easily. Software testing is one of the tedious tasks
in automation and python becomes its performance booster!

8. Multipurpose
Swiss Army knife-like nature describes well the overall work of python. It’s not tied to just one discipline, you
can do many things. You don’t really need to fetch data from a SQL server or a MongoDB database; Python
supports all these sources of data with very clean syntax use. Python API called PySpark can be used to
distribute computing. It also provides support for Natural language processing through NLTK.

9. Jobs and Growth


Python is growing as fast as it seems that everyone is adopting python. So, it makes a lot of sense to learn a
growing programming language – Python. As the number of python users are increasing, the language is
becoming more and more popular. It will not only help you to get a job quickly but will also accelerate your
career growth. For beginners, one of the most important reasons to learn Python after simplicity is job
opportunity.

10. Salary
Last but most important – money talks! Salary keeps every individual going. Python developers are one of
the highest-paid jobs available. Particularly in the fields of data science, machine learning, and web
development, these jobs shine. Though much of the factors contributing to it are also dependent upon
experience, location, and area of specialty.

Conclusion
With the increasing demand of programming and coding in today’s world, you are really missing something if
you don’t know Python. Nevertheless, it is even a great way to start learning experience of coding.

Programmers who already know C/C++ and Java, learning Python will be a great opportunity to achieve more
in less time in the exciting fields of data science, machine learning and a lot more which is in demand! To learn
Python you can check the complete Python Tutorial Series for free.
Python’s Future is even above the ‘C’ level!
by DataFlair Team · July 9, 2019

Imagine everything that you are surrounded by is raw, unstructured, incomplete, vast and just Data!
Python will definitely be there for your rescue!

Python is the Future and it will serve as a huge, reliable, effective and ready-to-use technology. What it can do
for us? Well, it can play around with data, visualize the data, transform inputs into a numerical matrix, or actual
machine learning and assessment.

All that needs to be done is to write the code — that would glue everything together. As simple as that!

What will be the Future of Python?

Laying some grounds on which we will define the future of Python.

How are we defining the popularity of programming language?


According to recent studies, Python showed 456-percent growth. Quite a number, isn’t it? In business terms —
Netflix, IBM, Dropbox and hundreds more utilize Python as their success key!

If you want to explore Python more, you need to check how Netflix is using Python

How are we defining Python’s popularity in a specific field?


Python is and remains a stable programming language currently used not only by developers but it is considered
great for deployment automation and web development. Non-developers when first introduced to the Python
language and its ecosystem, also prefer it for doing data work.
Who is driving the growth till now and will drive it in the future?
The sudden rise of demand for python and every platform becoming a “python-oriented-platform”, isn’t
everything just getting “pythonized”?

First of all, man’s life chasing point – money!

For future and present programmers, Python is becoming the first-choice language for learning it to get
“actual jobs”. It is also being used for many purposes, from web development to mobile app development to
data science. However, Data science is attracting the mob towards Python.

Secondly, Python’s serious versatility. Python is a multipurpose language used for various tasks, as seen
above. “Pandas” is by far the fastest-growing Python package. Therefore it seems clear that the rise of data
science is responsible for the growth of Python as “it’s” programming language.

Finally, Machine Learning. There is no special programming language dedicated to Machine Learning, but
looking at the characteristics of each language that can do ML, choose the best that will fulfill their needs,
Python. It is one of the most popular and the best languages for Machine Learning.

Python’s growth is for now!? or this growth has some Future!!??


Trends somehow define the need and needs definitely define the actual trends. There’s no doubt that Python is
now in “the trend”. All thanks to its popularity and the helpful community, Python is really friendly. Since it is
so easy to learn Python, you can start your python journey at this moment itself. That is not all, it is the way it
lets developers express their thoughts in a simpler way, adds on to the “choose python!” thing.

Python in Robotics and Machine Learning


The use is not little but extensive. It is a gift to the systems originally written in C and C++ as it makes it easy to
interface with Python. Anywhere that data analysis is required, Python and its diverse libraries shine.

At the end of the day, everyone is aware of how important machine learning is in the modern world. From
moderating social networks to driving cars, trained neural networks are doing everything. The field has moved
forward incredibly in recent years due to quickly increase in processing power. The potential for machine
learning is vast, and not yet even close to fulfillment.

What has this got to do with Python?


A lot. While there are libraries designed to work with other popular languages, Python is in actuality language
of machine learning. Notably, Google’s TensorFlow works primarily with Python. Almost every course on
neural networks uses Python.

Machine learning as a skill is in greater demand every day. A good grasp of the Python programming language
puts you in a leading position amongst others learning it from scratch.

Python being open source


Saying Python is free may not take your interest in it at first glance. After all, the language you decide to pursue,
simply using it, doesn’t actually cost anything. Python is free as in ‘Open Source’. It is entirely Open Source
and GPL compatible. Open-source software has already changed the world. Python’s being a perfect tool even
takes the “no-strings-attached status” to complement its use.

Python is blooming
Over the years, Python has swept into the coding world and has managed to reach the top. The survey and job
research in major countries calculated that over 40,000 jobs are entirely for python experienced developers. To
add on, internet search tags are also higher for python only in those countries which helped it to make it to the
top! It is no wrong in saying that Data science combined with python has the best career and future
complementing each other and to new heights.

You must check the latest article on Python Career Opportunities

Conclusion

We’re going to see continuous growth in the scientific programming part of Python. So things that support the
performance of Python as a language and its stability are going to continue to evolve. Beyond that, Python is a
pretty powerful and solid language. Even if you stopped development today, Python is a good sewed up
language.

Not trying to declare a war between language as to make a belief that Python’s the king. Whereas, it is crucial to
understand that trends might be changing, and there’s room for discussion left for everyone. We live in a data-
driven world and we’re really setting Python up for another 20 years of success and growth.

Hope you liked our Python Future article. Drop your feedback in the comment section, it means a lot to us. We
recommend you to try this DataFlair’s Python Self-paced Training to become a master of Python.

How to create a perfect Python Resume – Let your resume


speak!
by DataFlair Team · September 10, 2019

Python Resume – Not just a piece of paper but a way to outshine from other candidates.

When I created my resume for a Python job, I remember that I was not able to figure out what skills to add and
what all certifications should I mention. And, after checking 4-5 websites on google, I somehow found an
appropriate article which helped me in creating my first Python resume.

You don’t need to scroll through these much websites, DataFlair is here for your rescue. I have collected all the
essential points and strategies that you need to follow while creating your Python resume. Make sure to read
till the last as without knowing the last point, you won’t be able to get interview calls.

So, why wait? Let’s unlock your door to success in Python programming.
How to put Python in your Resume?
Follow the below steps to build Python resume for fresher as well as experienced:

1. Keep It Brief
The very first important thing you should strive for Python resume is – keeping it short and sweet! It should not
be any longer than a page unless you are an experience holder of 12-15+ years. On average, the recruiters have
about 30 seconds to go through the resume and make a decision, so it should be very clear. Jot your experience
down to the most important points and make it easily scannable.

2. Customize the Resume according to the Python Job


description
Add or subtract small details in your resume for each application you submit instead of giving out a single
resume to every job. You may also want to have a look at the company’s website to try to get an idea of what
style, tone and writing adjustments they will prefer and change your resume for Python job accordingly.

“The most important tool you have on a resume is language.”

– Jay Samit

3. Choose Proper
Templates
While all the resume involves information like work experience, skills, contact information, etc but it should be
unique to you. It can also be accomplished by changing the looks or design of the resume. For example- if you
are applying for companies with a traditional feel, aim for a classic or subdued style for resume whereas more
colors can be added for startup vibe companies. Even though you start with a template, take time to personalize
it.

4. Contact Information
This piece of information should be kept at a very approachable position. In case the recruiter decides to contact
you based on your resume of Python, you don’t want them to search through the whole resume. Double-check
all the information to assure that they are right. Make sure your headline reflects what you are aiming through
the job and not the one you currently have. If you are trying to become a Python Developer, your heading
should be “Python-developer” even if you are working as a marketing intern.

5. Work Experience
The most recent job should be listed on top, with a job below that, and so on in chronological order. Each entry
written in this section should include the job title, the company, the period of time you held the position, and
your accomplishments. Employers want to see what you actually did, not just what you were assigned. Frame
your Python accomplishments in the context of business metrics to show that you are aware of the bigger
picture and can translate your work results into real-world outcomes.

6. Education
The things you should list here are post-secondary degrees (i.e. community college, college, and graduate
degrees). If your degree is not relevant to the job you are applying for, still list it. Many Python developers are
from a variety of fields that do not have a computer science background. Don’t list your micro- degrees here,
like certifications or professional training. We will list them later.

7. Skills and Certifications


For technical positions, the skills section is not optional but a necessity. You want to make sure that the terms
like Python, Data Science or Machine Learning are highlighted. Also, list your soft skills like communication
or leadership here. Don’t rank your skills, it can lead to overpromise or sell yourself short. You can list skills
you are strongest at first and weakest later but do not overload this section with unnecessary details. Here you
can specify your professional training or Python online certifications. Coding based hackathons are a huge plus
point in resumes. Shows your healthy competitive spirit and confidence in your skills.

8. Add Python Projects and Applications


The main thing that you have to highlight is what you have created. For Python-developers, this could be Data
Science projects, machine learning projects, Web-development projects, published scientific articles or coding
tutorials. The companies are actually looking for what you actually do with your skills instead of what skills
you have. They don’t aim to see whether the solution was “cool” or not or how technically difficult the
challenge you took. It is all about whether you were able to solve the problem or not with your skillset. Hence
definitely include projects in your resume but their description should be very specific, including all main
tools and technologies you used and how you created it i.e. individual contribution.

WORRIED? Not done any Python Projects yet? Don’t worry, DataFlair is here to resolve this
problem. Check out 5 Python Projects from our Certified Python Training Course

Summary
Of course, a resume doesn’t mean you have to prove that you’ve got the skills that you have listed. You just
have to let the recruiters know that you are capable to handle that position you are applying for and also will be
very productive towards it. Hope this tutorial of Python resume creation helped you.

Now, it is the right time to prepare yourself for Python interviews. Here are the Python Interview
Questions and Answers that were asked to me.

Practice these questions. Don’t forget to share your valuable feedback with us.
Happy learning

Python Career Opportunities – Python Job Profiles


by DataFlair Team · February 20, 2019

1. Python Career Opportunities

We’ve been seeing a lot of Python every day here, but what is it all worth? Sure, Python is easy, and cool to
learn, and powerful, but what do you get in return? To answer questions like these, we base today’s article on
the Python Career Opportunities and Python Scope it gifts you. In this tutorial on Python Careers, we talk about
India. Read on.

2. Number of Python Jobs

While there’s a high demand and career opportunities for Python developers in India, the supply is really, really
low. To testify this, we’ll take account of an HR professional statement. The professional was expected to
recruit 10 programmers each for both Java and Python for a few projects. About a hundred good resumes
flooded in for Java, but they received only 8 good ones for Python. So, while they had to go through a long
process to filter out good candidates, with Python, they had no choice but to take those 8 candidates.

What does this tell us about the situation? Even though Python has really easy syntax, we really need more
people in India to consider it. But then, this is what makes it a great opportunity for an Indian with the skills.
When we talk about the number of jobs, there may not be too many for Python in India. But we have an
excellent number of jobs per Python programmer. This a good news about Python Careers

Not very long ago, one of India’s unicorn software companies faced a dilemma. It had won a $200 million (Rs.
1200 crore) contract with a large US bank to develop an app store for them. But the company lacked enough
dexterous Python programmers. Since Python was the best language for the project, it ended up paying thrice
the billing amount to a group of freelance Python programmers in the US instead.

Job boards like Indeed and Naukri offer around 20,000 to 50,000 job listings for Python and this shows that
Python career opportunities in India are High. Python Careers are good to go with. The below screenshot from
indeed job trends shows job trends in Python compared to other languages.
Python Career Opportunities – Python job Trends

Source: Indeed Job Trends

3. Types of Python Jobs

So what types of jobs can you land with Python?

Well, for one, Python Scope is intensive use in data science and analysis. Clients often want hidden patterns
extracted from their data pools. It is also preferred in Machine Learning and Artificial Intelligence. Data
scientists love Python. Also, in our article on Applications of Python, we read about NumPy, SciPy, scikit-
learn, pandas, IPython notebook. These are some useful libraries available for Python, and they let us explore
the advanced areas of Python and different Python career opportunities.
Python Career Opportunities – Python Careers

a. Job Profiles:
With Python on your resume, you may end up with one of the following positions in a reputed company:

i. Software Engineer

 Analyze user requirements


 Write and test code
 Write operational documentation
 Consult clients and work closely with other staff
 Develop existing programs

ii. Senior Software Engineer

 Develop high-quality software architecture


 Automate tasks via scripting and other tools
 Review and debug code
 Perform validation and verification testing
 Implement version control and design patterns

iii. DevOps Engineer

 Deploy updates and fixes


 Analyze and resolve technical issues
 Design procedures for maintenance and troubleshooting
 Develop scripts to automate visualization
 Deliver Level 2 technical support
iv. Data Scientist

 Identify data sources and automate collection


 Preprocess data & analyze it to discover trends
 Design predictive models and ML algorithms
 Perform data visualization
 Propose solutions to business challenges

v. Senior Data Scientist

 Supervise junior data analysts


 Build analytical tools to generate insight, discover patterns, and predict behavior
 Implement ML and statistics-based algorithms
 Propose ideas for leveraging possessed data
 Communicate findings to business partners

4. Future of Python

In our write-up on Applications of Python, we saw where Python finds its use. But what about the future?
While many top companies are stuck with Java, Python is one of the new technologies. The future is bright for
Python with:

Python Career Opportunities – Python Future

a. Artificial Intelligence
Artificial Intelligence is the intelligence displayed by machines. This is in contrast to the natural intelligence
displayed by humans and other animals. It is one of the new technologies taking over the world. When it’s
about AI, Python is one of the first choices; in fact, it is one of the most-suited languages for it.
For this purpose, we have different frameworks, libraries, and tools dedicated to let AI replace human efforts.
Not only does it help with that, but it also raises efficiency and accuracy. AI gives us speech recognition
systems, autonomous cars, and so. The following tools and libraries ship for these branches of AI:

 Machine Learning- PyML, PyBrain, scikit-learn, MDP Toolkit, GraphLab Create, MIPy
 General AI- pyDatalog, AIMA, EasyAI, SimpleAI
 Neural Networks- PyAnn, pyrenn, ffnet, neurolab
 Natural Language and Text Processing- Quepy, NLTK, genism

b. Big Data
Big Data is the term for data sets so voluminous and complex that traditional data-processing application
software are inadequate in dealing with them.

Python has helped Big Data grow, its libraries allow us to analyze large amount of data across clusters:

 Pandas
 scikit-learn
 NumPy
 SciPy
 GraphLab Create
 IPython
 Bokeh
 Agate
 PySpark
 Dask

c. Networking
Python also lets us configure routers and switches, and lets us perform other network-automation tasks cost-
effectively. For this, we have the following libraries:

 Ansible
 Netmiko
 NAPALM(Network Automation and Programmability Abstraction Layer with Multivendor Support)
 Pyeapi
 Junos PyEZ
 PySNM
 Paramiko SSH

All these technologies rely on Python today and tomorrow.

5. Top Organizations Using Python

With its extreme popularity and powerfulness, Python is preferred by unicorns too:
Python Career Opportunities – Top Companies Using Python

a. NASA
The National Aeronautics and Space Administration uses Workflow Automation System (WAS), an application
written and developed in Python. It was developed by NASA’s shuttle-support contractor USA (United Space
Alliance).
NASA also uses Python for APOD(Astronomy Picture Of the Day), API, PyTransit, PyMDP Toolbox,
EVEREST.

b. Google
Who, on this Earth, lives and doesn’t know Google? We use it for everything- sometimes, even to find answers
to life’s deepest questions. Google uses Python for its internal systems, and its APIs for report-generation, log
analysis, A/Q and testing, and writing core search-algorithms.

c. Nokia
This one reminds me of Nokia 3310, that pocket phone that could break a tile. Nokia makes use of PyS60
(Python for S60). It also uses PyMaemo(Python for Maemo) for its S60(Symbian), and Maemo(Linux) software
platforms.

d. IBM
An American multinational technology company headquartered in New York, IBM uses Python for its factory
tool control applications.

e. Yahoo! Maps
Maps is an online mapping portal by Yahoo! It uses Python in many of its mapping lookup services and
addresses.

f. Walt Disney Feature Animation


WDFA uses Python as a scripting language for animation. All the magic that happens in Disneyland has a bit of
Python behind it.

6. Payscale in Python

In section 4, we saw a rough approximate of how much a Python professional makes. In section 3, we saw some
job profiles. So, how does each profile fair in this department?

Python Career Opportunities – Python Salary

 Software Engineer – $103,035/yr


 Sr. Software Engineer – $129,328/yr
 DevOps Engineer – $115,666/yr
 Data Scientist – $117,345/yr
 Sr. Data Scientist – $136,633/yr

These statistics have been sourced from payscale.com and indeed.com.

7. Why Must You Learn Python

So, after all this Python career opportunities talk, why must you learn Python? What has it to offer to you?
What is the cope of Python? Let’s see.
Python Career Opportunities – Why Python

1. Its simplicity and conciseness make it perfect for beginners.


2. It has a large community that continuously contributes to its development.
3. Because of the highly demand-supply ratio, it provides excellent career opportunities, especially in
India.
4. We have a number of frameworks to make web development easy as pie.
5. Python is the chosen language for Artificial Intelligence and Machine Learning.
6. Raspberry Pi, a microcomputer, lets us make our own DIYs with Python, at prices that do not blast holes
in your pockets.
7. Both startups and corporates, make extensive use of Python, thanks to its powerfulness and simplicity.
8. Python replaced Java as the second-most popular language on GitHub, with 40 percent more pull
requests opened this year than last.
Python Career Opportunities

Source: GitHub –The State of the Octoverse 2017

So, this was all about our blog post on Python Career Opportunities

8. Conclusion: Python Scope


Now that you know what doors Python can open for you and what are the different Python Career
opportunities, which one will you take? Let us know in the comments.

Want to crack your upcoming Python Interviews? – Practice Most Asked Python Interview Questions

If you have any question on Python Career Opportunities, please drop a comment.

How to get a Job in Python as a Fresher? The essential steps you must
follow!
by DataFlair Team · September 24, 2019

Python has changed the industry with its ease-of-use and powerful libraries, and its vast applications and
productivity. Python jobs pay well and developers are in demand. And since Python is easy, many choose to go
for a lucrative job in Python. Are you dreaming of a job in Python too? And wanted to know how to get a job in
Python as a fresher? Let’s find out.

Can a Fresher get a Job in Python?


Yes! If you’re a fresher, you can definitely secure a job in Python. Get ready to perfect your foundation and
make your dreams come true. Read on to learn how to get a job in python as a fresher.

How to get a Job in Python as a Fresher?

There are two ways to learn Python

 One is through a quick, inclusive online course, and the other will take almost a year. If you learn
Python through an online course, you’ll be sure you’re not missing anything, will get more insight based
on what others think, and also finish practicals and build projects.
 If you rather don’t want to spend on this, you can go for free online tutorials at your own pace. But it
will not guarantee success and will be slow.

Who knows what the competition will be in a year? This is the right time to learn Python but with correct
guidance. The time is not far when every other person is learning Python technology. That’s why I recommend
you to master it as soon as possible and become top of everyone.

Sharing both the ways with you. All up to you what to choose.

1. The Quick Way – Online Course


DataFlair has this Certified Python Online Course with over 20 hours of material and 5 exciting real-time
projects with complete code. This will ensure you learn everything and with a practical approach. Check it out
now and start learning Python.

This Certified Python Course by DataFlair is what you need. It has countless practicals and will give you a
hands-on experience. Remember that you’ll need to practice along with the course; it will make you better at
Python.

2. The Long Way – Online Tutorials


Now, below is the way to learn Python through online tutorials –

a. What to study?
As a fresher in Python, you should study the following things to build a strong foundation in Python.

 Python installation and syntax


 Basic concepts like statements, variables, and operators
 Differences between Python 2 and Python 3
 Data structures like lists, sets, and dictionaries
 Decision making and loops
 Virtual environments
 Functions and recursion
 OOP concepts- classes, methods, inheritance, overloading
 Modules and packages
 File handling
 Decorators, generators, iterators
 Random numbers and regular expressions
 Exception handling
 Networking, XML processing, multiprocessing
 GUI
 SciPy, NumPy, Pandas
 Debugging, unit testing, logging, serializing, accessing the database
 It is also beneficial to know more than two high-level languages.

DataFlair has published a Python Master Guide for you by which you can learn all these topics.

b. Ways to Learn Python


Whether you’re beginning from scratch or not, there are a few sources where you can choose to study Python
for free:

 Online Python Tutorials


 Good Books on Python
 Python Official Documentation

c. Python Projects
After you’ve finished learning about the constructs in Python, you should build some personal projects to solve
the problems you face. Or, if you feel confident, you can contribute to some open-source Python projects like
Django.

DataFlair has published a complete package of 5 Python Projects which you must try.

d. Do an Internship
If you’re in your last semester of college or are done with college, you can go for a data science internship. This
will show the employer that you’re serious about Python, and will also give you some experience and exposure
to the professional world.
e. Build a good resume
Build a strong resume if you want to be preferred over other candidates. List your skills and projects carefully
on it. Mention any hackathons you’ve participated in- they show your confidence in your skills. Read this
article by DataFlair to understand how to create a perfect resume for your next interview.

Check Python Job Profiles and Salary


What profiles to apply for? Or what profiles can you get as a Python techie? If you’re wondering this, we’ve
listed out 10 profiles you can end up with if you go for Python.

 Software engineer
 Front-end software/web developer
 Python developer/programmer
 DevOps engineer
 Product manager
 Data Analyst/Journalist
 Educator
 Financial Advisor
 Research Analyst
 Data Scientist

In your first job with Python, you will take home around 3-5 lakhs per year. With experience, that can go up to
7-8 lakhs quick.

Who said a fresher can’t get a job in Python? If you try hard enough, you can get a Python job at a company
you want. Also note that some knowledge about data science, machine learning, big data, and artificial
intelligence can be beneficial for an interview and for a job itself. For the knowledge of all these technologies,
you can check DataFlair.

What you have selected – The fast way or the long way? Tell us through comments.

Python Tools – 4 Major Utilities of Python


by DataFlair Team · September 27, 2018

1. Python Tools

After reading Python Flask we move towards Python Tools. Python provides us with many utilities that we can
also use as command-line utilities. In this Python Tools tutorial, we will focus on – Python Dis modules, Python
PDB module, Python Profile module, and Python Tabnanny module with an example.

So, let’s start with Python Tools.


Python Tools – 4 Major Utilities of Python

2. Which Python Tools are Commonly Used?

Here, we will discuss 4 types of Python Utilities.

a. Python Dis Module


To convert bytecode into a more human-readable format, Python has the ‘dis’ module. You can say that it
compiles a script, disassembles the bytecode, and prints the output to the STDOUT. We can use it as a module
or through the command line. As an argument, we can pass a function, a method, a class, or a code object to
the dis() function.

Let’s take an example.

1. >>> def add():


2. a=3
3. b=4
4. c=a+b
5. print(f"{a}+{b}={c}")
6. >>> add()
7. 3+4=7

Now, we import the Python dis module and call the dis() function on it.

1. >>> dis.dis(add)

2 0 LOAD_CONST 1 (3)

2 STORE_FAST 0 (a)
3 4 LOAD_CONST 2 (4)

6 STORE_FAST 1 (b)

4 8 LOAD_FAST 0 (a)

10 LOAD_FAST 1 (b)

12 BINARY_ADD

14 STORE_FAST 2 (c)

5 16 LOAD_GLOBAL 0 (print)

18 LOAD_FAST 0 (a)

20 FORMAT_VALUE 0

22 LOAD_CONST 3 (‘+’)

24 LOAD_FAST 1 (b)

26 FORMAT_VALUE 0

28 LOAD_CONST 4 (‘=’)

30 LOAD_FAST 2 (c)

32 FORMAT_VALUE 0

34 BUILD_STRING 5

36 CALL_FUNCTION 1

38 POP_TOP

40 LOAD_CONST 0 (None)

42 RETURN_VALUE

Do you know the difference between Python Modules vs Packages

b. Python Tabnanny Module


Python tabnanny checks code for ambiguous indentation. It tells us about any weird combinations of tabs and
spaces in the code. In Python, whitespace shouldn’t be ambiguous.

Like dis, we can run tabnanny from the command line or using the function check().

1. >>> import os
2. >>> import tabnanny
3. >>> os.chdir('C:\\Users\\lifei\\Desktop')
4. >>> tabnanny.check('nannydemo.py')
5. >>>

Python Tabnanny module has the following methods:

Python Tools Tutorial – Python Tabnanny Module

i. tabnanny.check(file_or_dir)
This checks the file or directory we pass to it for examining whitespace-related issues. Then, it prints the
diagnostic messages to the standard output.
Let’s define Python Datetime Module with Quick Examples

ii.tabnanny.verbose
This is a flag that depicts whether Python will print verbose messages.

iii. tabnanny.filename_only
This is a flag that depicts whether Python should print only the filenames for those files that contain issues
involving whitespace.
It also has the following function:

I. tabnanny.process_tokens(tokens)
The tokenize module generates some tokens. check() uses process_tokens() to process these tokens.
Finally, this module may raise the following exception:

II. exception tabnanny.NannyNag


When process_tokens() detects an ambiguous indent, it raises this exception. check() captures and handles this.

c. Python Profile Module


We may sometimes like to know which parts of our code take the longest. So in a way, through profiling, we try
to find bottlenecks in our code. Other profilers in Python are cProfile and hotshot.

Let’s explore List of 63 Python os Modules in 2018

Let’s try this module with the cProfile module.

1. >>> import hashlib


2. >>> import cProfile
3. >>> cProfile.run("hashlib.md5('abcdefghijkl').digest()")

4 function calls in 0.000 seconds

Ordered by: standard name

ncalls tottime percall cumtime percall filename:lineno(function)

1 0.000 0.000 0.000 0.000 <string>:1(<module>)

1 0.000 0.000 0.000 0.000 {built-in method _hashlib.openssl_md5}

1 0.000 0.000 0.000 0.000 {built-in method builtins.exec}

1 0.000 0.000 0.000 0.000 {method ‘disable’ of ‘_lsprof.Profiler’ objects}

We profile the creation of an MD5 hash here. The first output we get tells us that four function calls were made.
These are ordered by standard name. Here’s what all the other columns mean:

 ncalls- The number of calls made.


 tottime- Total time spent in a function.
 percall- The quotient of tottime divided by ncalls.
 cumtime- Cumulative time spent in this function and all subfunctions.
 percall- The quotient of cumtime divided by primitive calls.
 filename: lineno(function)- Data of each function.

Read about Python Collections Module in detail

d. Python PDB Module


Pdb is the standard Python debugger. It helps us debug our code line by line and we have talked about this at
length in our article on Python Debugger.

1. >>> import pdb


2. >>> n=4
3. >>> def raised(a):
4. return a**a
5. pdb.set_trace()
6. eight=raised(8)
7. >>> print(eight)
8. >>> two=raised(2)
9. >>> print(two)

In the command prompt:

C:\Users\lifei\Desktop>python nannydemo.py

> c:\users\lifei\desktop\pdbdemo.py(6)<module>()

-> seven=raised(7)

(Pdb)

Now, we can use the commands of the pdb module to debug our code.

For a detailed demonstration, please refer to Debugging in Python.

So, this was all about Python Tools Tutorial. Hope you like our explanation.

3. Conclusion

Hence, these are few basic tools and utilities of Python: Dis modules, PDB module, the Profile module, and
Tabnanny module with an example. Furthermore, if have a doubt regarding Python Tools, feel free to ask in the
comment box.
See Also – Recursion in Python with Examples
For reference – Python Dis Module

Python Projects with Source Code – Practice Top Projects in Python


by DataFlair Team · October 1, 2019

Python Projects with Source Code

Looking to build a career in Python? Want to improve your resume with multiple personal projects on it? Then
this blog of Python projects with source code is for you. You earlier read about the top 5 data science projects;
now, we bring you 5 projects implementing data science with Python. In this blog, you’ll find the entire code to
all the projects. Read on to give your data science/ Python career a head-start.

List of amazing Python Projects with source code –

 Detecting Fake News Python Project with source code


 Speech Emotion Recognition Python Project with source code
 Detecting Parkinson’s Disease Python Project with source code
 Age and Gender Detection Python Project with source code
 Breast Cancer Classification Python Project with source code

Why do Projects in Python?


In an interview, a resume with projects shows interest and sincerity. Spending time on personal projects
ultimately proves helpful for your career. In this blog of python projects, we try our best to include different
data science and machine learning libraries of Python to give you a better experience.

Top Python Projects with Source Code

Let’s start discussing python projects with source code –

1. Detecting Fake News with Python

Fake news can be dangerous. This is a type of yellow journalism and spreads fake information as ‘news’ using
social media and other online media. This is a common way to achieve a certain political agenda. Fake news
may contain false and/or exaggerated claims. Social media algorithms often viralize these and create a filter
bubble. In this, we will train on a news.csv dataset of shape 7796×4. We’ll mainly use two things- a
TfidfVectorizer and a PassiveAggressiveClassifier. A TfidfVectorizer turns a collection of raw documents into
a matrix of TF-IDF features. And a PassiveAggressiveClassifier is an online learning algorithm that stays
passive for a correct classification and becomes aggressive when there’s a miscalculation.

Please refer – Detecting Fake News with Python for the complete implementation of the python project
with source code.

2. Speech Emotion Recognition with librosa


Speech Emotion Recognition (SER) is an attractive application of data science today as we constantly attempt
to give the consumer a better experience. This includes recognizing human emotion and affective states from
speech. Since voice often exposes underlying emotions with tone and pitch, it can be used to understand the
users’ needs and use it to improve the service. We will use the RAVDESS dataset and the libraries librosa,
soundfile, and sklearn to build a model using an MLPClassifier. In most projects, we use Jupyter Lab to run our
code.

Ready to build your own model? Speech Emotion Recognition Python Project with Source Code

3. Detecting Parkinson’s Disease with XGBoost


Parkinson’s disease is a progressive disorder of the central nervous system that affects over 1 million people in
India every year. It affects movement and can be a cause of tremors and stiffness. This is a neurodegenerative
disorder with 5 stages to it, and affects dopamine-producing neurons in the brain. In this python project, we will
use the UCI ML Parkinsons dataset and use XGBClassifier from xgboost to build a model that can accurately
detect the presence of Parkinson’s disease in a person. We will also use the libraries scikit-learn, numpy, and
pandas.

Check the complete python project with source code – Detecting Parkinson’s Disease with Python

4. Gender and Age Detection with OpenCV

Computer Vision is a field of study enabling computers to see and recognize digital images and videos- this is
something only humans (and animals) are generally capable of. This involves processes like object recognition,
video tracking, motion estimation, and image restoration. It is exciting to be able to predict a person’s gender
and age from just a photograph. CNNs (Convolutional Neural Networks) are often the choice when we work
with images. In this project, we’ll use OpenCV (Open Source Computer Vision) and implement deep learning,
using trained models on the Adience dataset.

This is just a brief, explore detailed Gender and Age Detection Python Project with source code

5. Breast Cancer Classification with Keras


IDC (Invasive Ductal Carcinoma) is the most common form of breast cancer, forming about 80% of all breast
cancer diagnoses. This is a cancer that develops in milk ducts, and then invades the fibrous/fatty breast tissue
outside them. In this project, we use the IDC_regular dataset (with breast cancer histology images). Histology is
the study of the microscopic structure of tissues. With 2,77,524 patches of size 50×50 from 162 whole mount
slide images scanned at 40x, we’ll learn to build a classifier to train on 80% of the dataset. We’ll use 10% of it
for validation. We’ll be using Keras to define a CNN (CancerNet).

Excited? Check the entire python project of breast cancer classification with source code

Summary

We have learned to build 5 exciting python projects with source code. Try them at your own end and pay
attention to every step as you do it. Which one was your favorite? Tell us in the comment.

Data Science Tutorial – Introduction to Data Science for Python


by DataFlair Team · May 27, 2019

1. Data Science Tutorial – Objective

This Data Science tutorial aims to guide you to the world of data science and get you started with the basics like
what is Data Science, History of Data Science, and Data Science Methodologies. Here, we will cover the Data
Science Applications, a difference between Business Intelligence and Data Science. Along with this, we will
discuss Life-Cycle of Data Science and Python Libraries.

So, let’s begin Data Science Tutorial.


Data Science Tutorial – Introduction to Data Science with Python

2. What is Data Science?

Before we start the Data Science Tutorial, we should find out what data science really is.

Data science is a way to try and discover hidden patterns in raw data. To achieve this goal, it makes use of
several algorithms, machine learning(ML) principles, and scientific methods. The insights it retrieves from
data lie in forms structured and unstructured. So in a way, this is like data mining. Data science encompasses
all- data analysis, statistics, and machine learning. With more practices being labelled into data science, the term
itself becomes diluted beyond usefulness. This leads to variation in curricula for introductory data science
courses worldwide.

Do you know the Best Data Scientist Certifications to Choose from

3. Data Science Tutorial – History

Through the recent hype that data science has picked up, we observe that it has been around for over thirty
years. What one we could use as a synonym for practices like business analytics, business intelligence, or
predictive modeling, now refers to a broad sense of dealing with data to find a relationship within it. To quote a
timeline, it would go something like this:

a. In 90’s
 1960- Peter Naur uses the term as a substitute for computer science.
 1974- Peter Naur publishes Concise Survey of Computer Methods, uses a term in a survey of
contemporary data processing methods.
 1996- Biennial conference in Kobe; members of the IFCS (International Federation of Classification
Societies include the term in the conference title.
 1997- November- Professor C.F. Jeff Wu delivers inaugural lecture on the topic “Statistics=Data
Science?”.

b. In 2000’s
 2001- William S. Cleveland introduces data science as an independent discipline in article Data Science:
An Action Plan for Expanding the Technical Areas of the Field of Statistics.
 2002- April- The ICSU (International Council for Science): Committee on Data for Science and
Technology (CODATA) starts Data Science Journal- this publication is to focus on issues pertaining to
data systems- description, publication, application, and also legal issues.
 2003- January- Columbia University publishes journal The Journal of Data Science- a platform that
allows data workers to exchange ideas.
 2005- National Science Board publishes Long-lived Digital Data Collections: Enabling Research and
Education in the 21st Century- this provides a new definition to the term “data scientists”.
 2007- Jim Gray, Turing awardee, envisions data-driven science as the fourth paradigm of science.
 2012- Harvard Business Review article attributes coinage of the term to DJ Patil and Jeff
Hammerbacher in 2008.
 2013- IEEE launches a task force on Data Science and Advanced Analytics; first European Conference
on Data Analysis (ECDA)organized in Luxembourg, European Association for Data Science (EuADS)
comes into existence.
 2014- IEEE launches first international conference International Conference on Data Science and
Advanced Analytics; General Assembly launches student-paid Bootcamp, The Data Incubator launches
data science fellowship for free.
 2015- Springer launches International Journal on Data Science and Analytics.

4. Data Science Tutorial – Methodologies


In this Data Science Tutorial, we will cover the following Methodologies in data Science:

Data Science Tutorial – Methodologies of Data Science

a. Machine Learning for Pattern Discovery


With this, clustering comes into play. This is an algorithm to use to discover patterns; an unsupervised model.
When you don’t have parameters on which to make predictions, clustering will let you find hidden patterns
within a dataset.

One such use-case is to use clustering in a telephone company to determine tower locations for optimum signal
strength.

b. Machine Learning for Making Predictions


When we have the data we need to train our machine, we can use supervised learning to deal with transactional
data. Making use of machine learning algorithms, we can build a model and determine what trends the future
will observe.

c. Predictive Causal Analytics


Causal analytics lets us make predictions based on a cause. This will tell us how probable an event is to hold
occurrence in future. One use-case will be to perform such analytics on payment histories of customers in a
bank. This tells us how likely customers are to reimburse loans.

d. Prescriptive Analytics
Predictive analysis will prescribe your actions and the outcomes associated with those. This intelligence lets it
take decisions and modify those using dynamic parameters. For a use-case, let us suggest the self-driving car by
Google. With the algorithms in place, it can decide when to speed up or slow down, when to turn, and which
road to take.

5. Data Science Applications

Let’s see some applications in this Data Science Tutorial:

Data Science Tutorial – Data Science Applications


a. Image Recognition
Using the face recognition algorithm of data science, we can get a lot done. Did Facebook ever suggest people
tag in your pictures? Have you tried the search-by-image feature from Google? Do you remember scanning a
barcode to log in to WhatsApp Web using your smartphone?

b. Speech Recognition
Siri, Alexa, Cortana, Google Voice all make use of speech recognition to understand your commands.
Attributing to issues like different accents and ambient noise, this isn’t always completely accurate, though
intelligible most of the time. This facilitates luxury like speaking the content of a text to send, using your virtual
assistant to set an alarm, or even use it to play music, inquire about the weather, or make a call.

c. Internet Search
Search engines like Google, Duckduckgo, Yahoo, and Bing make good use of data science to make fast, real-
time searching possible.

d. Digital Advertisements
Data science algorithms let us understand customer behaviour. Using this information, we can put up relevant
advertisements curated for each user. This also applies to advertisements as banners on websites and digital
billboards at airports.

e. Recommender Systems
Names like Amazon and Youtube will throw in suggestions about similar products aside or below as you
browse through a product or a video. This enriches the UX(user experience) and helps retain customers and
users. This will also take into account the user’s search history and wishlist.

f. Price Comparison Websites


Websites like Junglee and PriceDekho let us compare prices for the same products across different platforms.
This facility lets you make sure you grab the best deal. These websites work in the domains of technology,
apparel, and policy among many others, and use APIs and RSS feeds to fetch data.

g. Gaming
As a player levels up, a machine learning algorithm can improve or upgrade itself. It is also possible for the
opponent to analyze the player’s moves and add an element of difficulty to the game. Companies like Sony and
Nintendo make use of this.

h. Delivery Logistics
Freight giants like UPS, FedEx, and DHL use practices of data science to discover optimal routes, delivery
times, and transport modes among many others. A plus with logistics is the data obtained from the GPS devices
installed.
i. Fraud and Risk Detection
Practices like customer profiling and past expenditures let us analyze whether there will be a failure. This lets
banks avoid debts and losses.

6. Business Intelligence vs Data Science

Here, in this part of Data Science Tutorial, we discuss Data Science Vs BI. Business intelligence and data
science aren’t exactly the same thing.

 BI works on structured data; data science works on both- structured and unstructured data.
 Where BI focuses on the past and the present, data science considers the present and the future.
 The approach to BI is statistics and visualization; that to data science is statistics, machine learning,
graph analysis, and NLP.
 Some tools for BI are Pentaho, Microsoft BI, and R; those for data science are RapidMiner, BigML,
and R.

7. Data Science Tutorial – Life-Cycle

The journey with data science goes through six phases-

Data Science Tutorial – Introduction to Data Science with Python

a. Discovery
Before anything else, you should understand what the project requires. Also consider the specifications, the
budget needed, and priorities. This is the phase where you frame the business problem and form initial
hypotheses.
b. Data Preparation
In the preparation phase, you will need to perform analytics in an analytical sandbox. This is for an entire
project. You will also extract, transform, load, and transform data into the sandbox.

c. Model Planning
In the third phase, you choose the methods you want to work with to find out how the variables relate to each
other. This includes carrying out Exploratory Data Analytics (EDA) making use of statistical formulae and
visualization tools.

d. Model Building
This phase includes developing datasets for training and testing. It also means you will have to analyze
techniques like classification and clustering and determine whether the current infrastructure will do.

e. Communicate results
This is the second last phase in the cycle. You must determine whether your goals have been met. Document
your findings, communicate to stakeholders, label the project a success or failure.

f. Operationalize
In the last phase, you must craft final reports, technical documents, and briefings

This Data Science Tutorial is dedicated to Python. So, let’s start Data Science for Python.

8. Data Science Tutorial – Why Python?

So, now you know what data science is all about. But why is Python the best choice for it? Here are a few
reasons-

 Open-source and free.


 Easy to learn; intuitive.
 Fewer lines of code.
 Portability.
 Better productivity.
 Demand and popularity.
 Excellent online presence/ community.
 Support for many packages usable with analytics projects; can also use packages that can use code from
other languages.
 It is faster than similar tools like R and MATLAB.
 Amazing memory management abilities.

9. Python 2.x or 3.x- Which should you go for?


Among a lot of other factors, the support for Python 2 ends officially on January 1st, 2020, so the future belongs
to Python 3. Also, 95% of the libraries for data science are done being migrated from Python 2 to Python 3.
Apart from that, Python 3 is cleaner and faster.

Well, then what about Python 2? It has its own perks- it is rich with a large online community and plenty of
third-party libraries, and some features are backwards-compatible and work with both versions.

With the perks of each version listed, make your choices.

10. Data Science Tutorial – Python Libraries

For carrying out data analysis and other scientific computation, you will need any of the following libraries:

Data Science Tutorial – Data Science Libraries

a. Pandas

Pandas help us with munging and preparing data; it is great for operating on and maintaining structured data.

b. SciPy

SciPy (Scientific Python) stands on top of NumPy. With this library, we can carry out functionality like Linear
Algebra, Fourier Transform, Optimization, and many others.

c. NumPy

NumPy (Numerical Python) is another library that lets us deal with features like linear algebra, Fourier
transforms and advanced random number capabilities. One very import feature of NumPy is the n-dimensional
array.
d. Matplotlib

Matplotlib will let you plot different kinds of graphs. These include pie charts, bar graphs, histograms, and
even heat plots.

e. Scikit-learn

Scikit-learn is great for machine learning. It will let you statistically model and implement machine learning.
The tools for these include clustering, regression, classification, and dimensionality reduction.

f. Seaborn

Seaborn is good with statistical data visualization. Making use of it, we can create useful and attractive
graphics.

g. Scrapy

Scrapy will let you crawl the web. It begins on a home page and gets deeper within a website for information.

Follow this link to know more about Python Libraries in detail

11. Learning in Data Science Tutorial

Before you begin with data science Tutorials, we suggest you should brush up on the following:

 Variables in Python
 Operators in Python
 Dictionaries in Python
 Strings in Python
 Python Lists
 Python Tuples

So, this was all about Data Science Tutorial. Hope you like our explanation.

12. Conclusion
Hence, we complete this Data Science Tutorial, in which we learned: what is Data Science, History of Data
Science, and Data Science Methodologies. In addition, we covered the Data Science Applications, BI Vs Data
Science. At last, we discussed Life-Cycle of Data Science and Python Libraries. This will get you started with
Python.

Got something else to add in this Data Science Tutorial? Drop it in the comments below.

Python for Data Science – Data speaks, Python listens!


by DataFlair Team · July 13, 2019

As you must know by now, it is a great choice to do data analysis using Python. This is why data scientists
prefer Python.
Out there, there’s a battle taking place in minds of future Data scientists for choosing the best tools. Though
there are quite a number of tools with many options, the close combat narrows down between two popular
languages – Python and R.

Why Python over R for Data Science?

One of the push of choosing Python over R is from the variety of data science/data analytics libraries made
available. Some of the libraries well known in the data science community – Pandas, StatsModels, NumPy,
SciPy, and Scikit-Learn. It doesn’t stop there, some 72,000 of them in the Python Package Index (PyPI) and still
growing constantly. After all these, I recommend you to check the difference between Python and R for better
understanding

So, before we start our topic I recommend you to take a brief of what data science is?

What is Data Science?

Data science, aka data-driven science, is an interdisciplinary field of scientific methods, processes, and systems.
It is used to extract knowledge or insights from data in various forms, either structured or unstructured. In this
way, it is similar to data mining. With data at its heart, it employs a wide range of techniques on the data to
extract essential insights from it.

Data science attracting beginners towards Python. How?

For this reason and others, Python is the most demanding for programmers . Data scientists coming from
engineering or scientific backgrounds might feel a bit out of place the first time they try to use it for data
analysis but when they do use it, they make most out of it. Python didn’t make its inroads to data science
initially when it was conceived in the late 1980s. Tools for covering every aspect of scientific computing are
now readily available in Python.

Python’s readability and simplicity make it comparatively easy to pick up. The number of dedicated and
analytical libraries freely available for download today mean that data scientists present in every sector will find
packages already tailored to their needs. As a jack of all trades, Python is not specialized to do statistical
analysis, but in many cases, organizations already have heavily invested in extending it to that purpose as they
saw advantages of standardizing on it. In short, we can say, Python has become the go-to language for data
scientists. And you
must start learning Python now! Our DataFlair team has designed a perfect self-paced course of Python for
Data Science and the passionate learners like you. Get the course now and move a step ahead in the data science
field.

Essential Python Libraries for Data Scientists

Data science has the early benefits of these extensions and libraries!

1. Python Pandas

Now the big daddy to all of them is Python Pandas. From importing data from spreadsheets to processing sets
for time-series analysis, Pandas is used for everything. Pandas pretty much convert one data form to another on
your fingertips. Hence, Pandas powerful data frames can perform both, basic cleanup and advance data
manipulations.

“One of the reasons we like to use Pandas is because we like to stay in the Python ecosystem,” Burc Arpat,
a quantitative engineering manager at Facebook.

Behind Python’s data science success story, one of the earliest libraries is Numpy (Numerical Python), on
which Pandas is built. NumPy’s functions exposure is used in Pandas for advanced analysis. For more
specialization, one can use Scipy which is scientifically equivalent to Numpy, offering tools and techniques for
scientific data analysis.

a. NumPy
NumPy facilitates easy and efficient numeric computation. It has many other libraries built on top of it. Make
sure to learn NumPy arrays.

b. SciPy
SciPy will give you all the tools you need for scientific and technical computing. It has modules for
optimization, linear algebra, integration, interpolation, special functions, FFT, signal and image processing,
ODE solvers, and other tasks.

2. Matplotlib
Python also provides powerful visualization libraries – Matplotlib. It can be used in all kinds of GUI toolkits
such as python scripts, web applications as well as shell, etc. With this, you have the opportunity to use
different types of plots and work with multiple plots.

3. Scikit – Learn & Pybrain

Scikit – Learn & Pybrain, one of the attractions of python where you implement machine learning. With the
support of simple and efficient tools in this library which can be used for data analysis and data mining. Various
algorithms have their back, like — logistic regression, time series, etc.

4. TensorFlow

TensorFlow is the most popular tool for Machine Learning in Python. It was developed specifically for carrying
out deep learning operations. The basic data structure of TensorFlow ecosystem are the tensors. As a matter of
fact, the name of TensorFlow is derived from these tensors. TensorFlow is continuously evolving owing to an
open-source community who have made it a pioneering toolkit for machine learning operations. It provides
support for CPUs, GPUs as well as TPUs. Due to this, it provides lightning speed execution speed for various
machine learning algorithms.

TensorFlow has numerous applications. This is mainly because of its high processing capability. It is used for
the development of speech recognition product, recommendation systems, Generative Adversarial Networks,
etc. TensorFlow is basically the standardized tool for performing Deep Learning operations.

5. Seaborn
Welcoming the next important library of Python for Data Science – Seaborn! So whatever and whenever you
will be using Python for data science, the first thing that will click to and should click will be using matplotlib
(for 2D visualization) & seaborn. They have many high-level interfaces and styles in default for drawing
statistical graphics.

Python is an obvious language choice for Data Science. These above-stated libraries and other specialized one’s
aid everything in python, from machine learning to neural networks to data processing. Hence this flexibility
has become the main benefit of choosing python at every step of the way towards data science.

Python’s large community is taking Data Science to the top!

Another plus point to above all the extensions/ libraries and properties of python that contribute to “python
being the choice” is the large community of data scientist, machine learning experts, and programmers who are
not only working their heart out to make it easy to learn python but also provide datasets to test one’s mastery
and skillset in python. So, whether you are a social scientist needing python for advanced data analysis or a
growing developer who needs inspiration, one of the parts of this python community will be ready to help you!

Summary
Along with Data Science and analytics, Python has also built a major force to conquer artificial intelligence and
machine learning. So if you learn python, a lot of career opportunities have open doors for you. Even if you
don’t work on AI, ML or data analysis, Python itself is capable to set to up! Being one of the contributors to the
web development world and graphic user interfaces. When you have Data Science hand in hand with Python, an
average salary of $92,000 to $132,000 a year (according to Glassdoor analysis) is not away!

Python Data Science Environment Setup


by DataFlair Team · August 7, 2019

1. Data Science Environment Setup With Python


Today, in this Python Data Science tutorial, we will see Data Science Environment Setup for Python.
Moreover, we will tell you about all that you need to install for Data Science Environment Setup, such as
Python, Anaconda, Miniconda. Along with this, we will see how to set a virtual environment for Data Science
Environment Setup and also importing Data Science Packages. Today, we will guide you to set up your
machine so you can begin your journey with data science. Before you begin, we suggest you read up on Python
Data Science Introduction to make things flow easier when you
come back. So, let’s start the Python data Science Environment Setup.
Python Data Science Environment Setup

2. Install Python
Before anything else, you should get Python on your machine. You can refer to the Step-by-Step Guide to
Install Python on Windows for this.
While 2.7 is widely adopted, 3.x will take over the future and has already started to leave its mark. Apart from
that, some software and features aren’t backward-compatible. So take your pick.

3. Getting Anaconda for Data Science Environment Setup

Data Science Environment Setup – Install Anaconda

Anaconda is a Python distribution for data science and machine learning. It is free and open-source and makes
managing and deploying packages simple.
It has more than 1000 data science packages and the Conda package. Other tools it comes with are core Python,
IPython, among others.

a. Anaconda Navigator
Anaconda ships with a virtual environment manager- the Anaconda Navigator. This is a desktop GUI that lets
you launch applications and manage packages, environments, and channels for conda. This lets you bypass the
command-line commands. The Navigator searches for a package on the Anaconda Cloud, or in a local
repository for Anaconda, and installs, runs, and updates them. It has the following applications-

 Glueviz
 Jupyter Notebook
 JupyterLab
 Orange 3 App
 VSCode
 RStudio
 Rodeo
 Spyder
 QTConsole

Anaconda will give you two package managers- pip and conda. When some packages aren’t available with
conda, you can use pip to install them. Note that using pip to install packages also available to conda may cause
an installation error.

b. Installing Anaconda
To download an Anaconda distribution, you can use the official download page:
https://www.anaconda.com/download/
Here, you can select your platform and then choose the installer. For this, you can choose which version you
want and whether 32-bit or 64-bit.
To install a package with conda, you can use the following command–

1. conda install scipy

4. Install Miniconda
Miniconda is a minimal installer for conda; a small, bootstrap version of Anaconda. It is free and ships with
conda, Python, and packages like pip and zlib. This lets you install more than 720 packages from conda. Since
Miniconda is a lighter version of Anaconda, it lets you download faster.
To install Miniconda, you can get to the following page-
https://conda.io/miniconda.html
Here, choose your platform and then pick a 32-bit or a 64-bit installer according to the needs of your machine.

5. Setting up a Virtual Environment


Since, here, we talk about setting up a data science environment with Python, let’s find out what a virtual
environment is. Well, a virtual environment lets us create different Python versions with the packages we want,
or as the project needs. Such an environment helps us ensure that there are no clashes between the versions of
packages and that of Python and its package managers. You should check out this blog on How to Create a
Python Virtual Environment and Install Packages.
For now, let’s see how we can create one with Anaconda. Use the following command in your Anaconda
prompt-
Data Science Environment Setup – setting up Virtual Environment

This should give you an idea of what the Anaconda prompt looks like. Now, to activate this environment, you
can type-

1. conda activate demo

This lets you start using it. Now to deactivate it, try-

1. conda deactivate

The following command tells you all the environments that exist; the asterisk (*) marks the current-

1. conda info -e

6. Important Python Data Science Packages


Important Python Data Science Packages

Working with data science, out of more than 1000 packages available, you will need a few that will let you
implement the basic functionalities. Let’s take a quick look at some of those packages.

a. NumPy

Python data Science Packages – NumPy

As discussed ample times earlier, NumPy lets you deal with large, multi-dimensional arrays and matrices. To
act on these, it also gives us various high-level mathematical functions.

b. SciPy

Python data Science Packages – SciPy


Scipy is a Python library for scientific and technical computin, and is free and open-source. Modules from
SciPy include those for-

 Optimization
 Linear algebra
 Integration
 Interpolation
 Special functions
 FFT
 Signal and Image processing
 ODE solvers

c. Matplotlib

Python Data Science packages – Matplotlib

We’ve used Matplotlib so far to plot many of the figures we needed to get started with visualization. Some of
these were bubble charts and scatter plots. This is a plotting library with Python and extends NumPy. With an
object-oriented API, it lets you embed plots into applications. For this, it uses GUI toolkits like Tkinter, Qt,
GTK+, and wxPython.

d. Pandas

Python Data Science Packages – Pandas

We have taken an extensive Pandas Tutorial. Now, it’s time for a quick recap. pandas is a software library for
Python that is supposed to serve for data manipulation and analysis. It is free and lets you manipulate numerical
tables and time series using data structures and operations.

e. scikit-learn

Python Data Science Packages – Scikit-learn


scikit-learn is a software machine learning library for Python. It is free and offers different algorithms for
classification, regression, and clustering-

 Support Vector Machines


 Random forests
 Gradient boosting
 K-means
 DBSCAN

We usually use it alongside NumPy and SciPy.

f. seaborn
Finally, seaborn is a visualization library for Python and is based on matplotlib. It lets us perform data
visualization in a statistical manner with a high-level interface that results in attractive graphics.
Let’s revise Python regular expression

7. How to Get Jupyter Notebook?

Data Science Environment Setup – getting Jupyter Notebook

As we saw earlier, the Jupyter Notebook ships with Anaconda. To run it, you can get in your virtual
environment and type the following-

1. jupyter notebook

You can also install it with pip-

1. python3 -m pip install --upgrade pip


2. python3 -m pip install jupyter

The notebook looks something like this-


Data Science Environment Setup – Jupyter Notebook

You can find this at http://localhost:8888/


Now to run Python here, you can create a new file. It looks like this-

Data Science Environment Setup – Jupyter Notebook

You can quit using the logout button at the top-right corner.
Let’s revise the Python Array Module
So, this was all in the Data Science Environment Setup with Python. Hope you like our explanation.

8. Conclusion: Data Science Environment Setup


Hence, in this Python Data Science Environment Setup tutorial, we discussed all that to need to install for data
Science Environment Setup. Moreover, we look at Python packages as Numpy, Scipy, matplotlib. With this, we
conclude our data Science environment setup tutorial, on how to set your machine up for data science. Still, if
any query regarding Python Data Science Environment setup, feel free to drop your questions in comments
below.

What’s New in Python 3.6 ? | New Features in Python 3.6


by DataFlair Team · September 27, 2018

1. Python 3.6 Tutorial

In this article on Python 3.6, we will discuss the following new features in Python 3.6. Moreover, we will
discuss

 New Syntax Features of Python 3.6


 New Modules in Python 3.6
 Improved Python 3.6 Modules

So, let’s start the Python 3.6 Tutorial.

What’s New in Python 3.6? | New Features in Python 3.6

2. What’s new in Python 3.6?

We know that the future belongs to Python 3.x. But we have a number of versions in Python 3000. For example,
Python 3.3.3 and Python 3.4.3. The latest version of Python is 3.6. So, let’s see what’s new in Python 3.6 and
how it is different from older versions, Python 3.6 performance and features.

3. New Syntax Features of Python 3.6


With Python 3.6, we see some new syntax features. Let’s take a look.

a. PEP 498 (Formatted String Literals)

You guessed it right. PEP 498 introduces f-strings.

An f-string is a string that you can format to put values inside it. For this, we precede the string with an ‘f’ or an
‘F’. We mention the variables inside curly braces.

1. >>> hometown,city='Ahmedabad','Indore'
2. >>> print(f"I love {hometown}, but I live in {city}")

I love Ahmedabad, but I live in Indore

For more on f-strings, read Python Strings.

b. PEP 526 (Syntax for Variable Annotations)

PEP 484 standardizes type annotations for function parameters. We also call these type hints.

1. >>> class A:
2. name:str
3. >>> A. annotations
4. {'name': <class 'str'>}

Annotations do not pose meaning to the interpreter, and are of use to third-party tools and libraries.

c. PEP 515 (Underscores in Numeric Literals)

With PEP 515, we can use underscores in numeric literals- between digits and after base specifiers.

1. >>>

0x_FF_FE_FF_FE

4294901758

d. PEP 525 (Asynchronous Generators)

PEP 492 introduced native coroutines and async/await syntax. Unlike Python 3.5, Python 3.6 can have await
and yield in the same function body. So, we can define asynchronous generators:

1. >>> async def ticker(delay, to):


2. """Yield numbers from 0 to *to* every *delay* seconds."""
3. for i in range(to):
4. yield i
5. await asyncio.sleep(delay)

This makes code faster and more concise.

e. PEP 530 (Asynchronous Comprehensions)

With PEP 530, you can use async for in lists, sets, dict comprehensions, and generator expressions.
result = [i async for i in aiter() if i % 2]

f. PEP 487 (Simpler Customization of Class Creation)

Now, we don’t need a metaclass to customize subclass creation. Whenever we create a new subclass, it calls the
init_subclass classmethod.

1. class PluginBase:
2. subclasses = []
3. def init_subclass (cls, **kwargs):
4. super(). init_subclass__(**kwargs)
5. cls.subclasses.append(cls)
6. class Plugin1(PluginBase): pass
7. class Plugin2(PluginBase): pass

g. PEP 495 (Local Time Disambiguation)

PEP 495 introduces the ‘fold’ attribute to instances of the datetime.datetime and datetime.time classes. This
way, it can differentiate between two moments in time with the same local times.

h. PEP 529 (Change Windows filesystem encoding to UTF-8)

With Python 3.6, no data loss occurs when we use bytes paths on Windows.

i. PEP 528 (Change Windows console encoding to UTF-8)

Now, the default console on Windows accepts all Unicode characters. It also provides correctly-read str objects
to Python code. Now, sys.stdin, sys.stdout, and sys.stderr default to utf-8 encoding.

j. PEP 520 (Preserving Class Attribute Definition Order)

With PEP 520, the natural ordering of attributes in a class is preserved in the class’ dict attribute. Now, the
default effective class ‘execution’ namespace is an insertion-order-preserving mapping.

k. PEP 468 (Preserving Keyword Argument Order)

Python now guarantees that **kwargs in a function signature is an insertion-order-preserving mapping.

l. PEP 523 (Adding a frame evaluation API to CPython)

PEP 523 introduces an API to make frame evaluation pluggable at the C level. This way, tools like debuggers
and JITs can intercept frame evaluation before the Python code even begins to execute.

These are the Python 3.6 new feature syntax.

Read:13 Unique Features of Python Programming Language

4. Other Additions in Python 3.6

 The PYTHONMALLOC environment variable allows us to set the Python memory allocators and install
debug hooks.
 New dict implementation- Now, dict() uses between 20% and 25% less memory compared to
Python 3.5.
 Earlier, it would give you a SyntaxWarning if you did not use a ‘global’ or ‘nonlocal’ statement before
the first use of the affected name in that scope.
 Now, Import raises the new exception ModuleNotFoundError, which is a subclass of ImportError. Code
that checks for ImportError still works.
 The interpreter now abbreviates long sequences of repeated traceback lines as
“[Previous line repeated {count} more times]”.
 Class methods that rely on zero-argument super() now work perfectly when we call them from metaclass
methods at class creation.
 Now, we can set a special method to None when we want to indicate that the operation is unavailable.
For instance, a class that sets iter () to None isn’t iterable.

The is some this what’s extremely new in Python 3.6.

5. New Modules in Python 3.6

a. secrets

Python 3.6 introduces a new module, ‘secrets’. This module lends us a way to reliably generate
cryptographically strong pseudo-random values. Using these, we can manage secrets like account
authentication, tokens, and so.

What’s new in python 3.6 – Secrets

Any doubt yet in What’s new in Python 3.6 tutorial because now there is a long list of Improved modules. Also
refer this article on Python Modules vs Packages.

6. Improved Python 3.6 Modules

Why stop at what we have, when we can tweak it into something even more awesome? Python 3.6 makes the
following improvements:
 array – Now, exhausted iterators of array.array stay exhausted even when the iterated array extends.
This is in consistence with other mutable sequences’ behavior.
 ast – Python adds the new ast.Constant AST node. External AST optimizers use them for constant
folding.
 asyncio – With Python 3.6, the asyncio module is no longer provisional; its API is now stable.
 binascii – Now, the function b2a_base64() accepts an optional newline keyword. This way, it can
control whether the newline character appends to the return value.
 cmath – Python 3.6 added a new constant cmath.tau(τ).

1. >>> from cmath import tau


2. >>> tau

6.283185307179586

 collections – Here’s all that is new in the ‘collections’ module:

Collection ABC- to represent sized iterable container classes.

Reversible ABC- to represent iterable classes. These also provide the method reversed ().

AsyncGenerator ABC- to represent asynchronous generators.

Other than these, the namedtuple() function will now accept an optional keyword argument ‘module’. Now, the
arguments ‘verbose’ and ‘rename’ for namedtuple() are keyword-only. Finally, we can now pickle recursive
collections.deque instances.

 concurrent.futures – Now, the class constructor ThreadPoolExecutor accepts an optional


thread_name_prefix argument. This lets us customize thread names for the thread created by the
pool.
 contextlib – The new contextlib.AbstractContextManager class provides an ABC for context managers.
This provides a sensible default implementation for enter ().
 datetime – Python 3.6 has a fold attribute for the datetime and time classes. This disambiguates local
time.

The function datetime.isoformat() takes an optional argument ‘timespec’.


The function datetime.combine() takes an optional argument tzinfo.

 decimal – The decimal module has a new method Decimal.as_integer_ratio(). It returns (n,d)- a pair of
integers representing a given Decimal instance as a fraction.

1. >>> Decimal('-3.14').as_integer_ratio()

(-157, 50)

 k. distutils – Python 3.6 removes the default_format attribute from distutils.command.sdist.sdist. Also,
now, the formats attribute defaults to [‘gztar’].
 l. encodings – On Windows, we now have the ‘oem’ encoding for ‘CPOEMCP’. We also have the ‘ansi’
alias for ‘mbcs’ encoding.
 m. enum – The enum module has two new enumeration base classes- Flag and IntFlags. These define
constants that we can combine using bitwise operators.

1. >>> from enum import Enum, auto


2. >>> class Color(Enum):
3. red=auto()
4. blue=auto()
5. green=auto()
6. >>> list(Color)
7. [<Color.red: 1>, <Color.blue: 2>, <Color.green: 3>]

 faulthandler – This module installs a handler for Windows exceptions.


 fileinput – With Python 3.6, hook_encoded() supports the ‘errors’ argument.
 http.client – Now, chunked encoding request bodies work with both HTTPConnection.request() and
endheaders().
 idlelib and IDLE – The idlelib package is refactored to give the IDLE a better look and
better performance. This also makes the code easier to understand, test, and improve.
 importlib – Now, importlib raises the exception ModuleNotFoundError when it is unable to find a
module. This is a subclass of ImportError.
 inspect – Now, the function inspect.signature() reports the implicit .0 parameters that the compiler
generates for comprehension and generator expression scopes.
 json – Now, json.load() and json.loads() support binary input.
 logging – To check if a log file must be reopened, we have WatchedFileHandler.reopenIfNeeded().

Read: Python Collections Module

 math – We have the new constant tau(τ) in both math and cmath modules.
 multiprocessing – We can now nest proxy objects returned by multiprocessing.Manager().
 x. os – Now, scandir() supports bytes paths on Windows. The method close() lets us explicitly close a
scandir() iterator.
 pathlib – Now, pathlib supports path-like objects.
 pdb – Python 3.6 adds a new optional readrc argument to the class constructor. This controls whether
.pdbrc files should be read. This is what’s new in Python 3.6, but this is not it.
 pickle – Pickle is the module that helps with serialization. We can now use pickle protocols older than
protocol version 4 to pickle objects needing new called with keyword arguments.
 pickletools – Now, pickletools.dis() outputs the implicit memo index for the MEMOIZE opcode.
 ac. pydoc – With Python 3.6, pydoc has learned to respect the MANPAGER environment variable.
 random – With the new random module, choices() returns a list of elements of a certain size. It picks
these elements from a given population of optional weights.
 re – The module re now has support for modifier spans in regular expressions. For instance,
‘(?i:p)ython’ will match ‘python’ and ‘Python’, but not ‘PYTHON’.
 readline – The function set_auto_history() can enable/disable automatic addition of input to the history
list.
 rlcompleter – We no longer have private and special attribute names unless prefixed with an
underscore. Sometimes, you can see a space or colon after some completed keywords.
 shlex – To control what characters must be treated as punctuation, shlex now has much improved shell
compatibility. This is through the punctuation_chars argument.
 site – We can now specify file paths on top of directories to add paths to sys.path in a .pth file.
 aj. sqlite3 – Now, sqlite3.Cursor.lastrowid supports the REPLACE statement.
 ak. socket – getsockopt() now supports constants SO_DOMAIN, SO_PROTOCOL, SO_PEERSEC,
and SO_PASSSEC.
setsockopt() now supports the setsockopt(level, optname, None, optlen: int) form.
 socketserver – The servers based on the socketserver module support the context manager protocol.
 am. ssl – Now, ssl supports OpenSSL 1.1.0. Also, SSLContext now has better default configuration for
options and ciphers.
 statistics – The statistics module has the new harmonic_mean() function.
 struct – Now, struct supports IEEE 754 half-precision floats. It does this via the ‘e’ format specifier.
 subprocess – With Python 3.6, if the child process is still running, the subprocess.Popen destructor
emits a ResourceWarning warning.
 sys – The function getfilesystemencodeerrors() returns the name of the error mode used to
convert between Unicode filenames and bytes filenames.
 telnetlib – Now, Telnet is a context manager.
 time – struct_time attributes tm_gmtoff and tm_zone now work on all platforms.
 timeit – When there is substantial (4x) variance between best and worst times, timeit warns.
 tkinter – New methods in the tkinter.Variable class include trace_add(), trace_remove() and
trace_info().
 traceback – Along with the interpreter’s built-in exception display, the traceback module abbreviate
long sequences of repeated lines in tracebacks. For instance:

1. >>> def f(): f()


2. ...
3. >>> f()

Traceback (most recent call last):

File “<stdin>”, line 1, in <module>

File “<stdin>”, line 1, in f

File “<stdin>”, line 1, in f

File “<stdin>”, line 1, in f

[Previous line repeated 995 more times]

RecursionError: maximum recursion depth exceeded

 aw. tracemalloc – tracemalloc now supports tracing memory allocations in multiple different address
spaces.
 typing – This module now has an improved support for generic type aliases. Also, new classes include
typing.ContextManager and typing.Collection.
 unicodedata – This module now uses data from Unicode 9.0.0.
 unittest.mock – New methods include Mock.assert_called() and Mock.assert_called_once().
 urllib.request – If an HTTP request has a file or iterable body, other than a bytes object, but no
Content-Length header, it does not throw an error. Now, AbstractHTTPHandler uses chunked transfer
encoding.
 urllib.robotparser – The RobotFileParser now supports the Crawl-delay and Request-rate extensions.
 venv – venv now accepts a new parameter- –prompt. This is an alternative prefix for the virtual
environment.
 warnings – The warnings.warn_explicit() function now has an optional ‘source’ parameter.
 winreg – What’s new? The 64-bit integer type REG_QWORD.
 winsound – winsound now allows us to pass keyword arguments to Beep, MessageBeep, and
PlaySound.
 bg. xmlrpc.client – This module now supports unmarshalling additional data types that are used by
the Apache XML-RPC implementation for numerics and None.
 zipfile – The class method ZipInfo.from_file() allows us to make a ZipInfo instance from a filesystem
file.
 zlib – We can now pass keyword arguments to functions compress() and decompress().
So, this is all on what’s new in Python 3.6 Tutorial. Hope you like our explanation.

7. Conclusion

In this article on what’s new in Python 3.6, we discussed what changes have been made to Python 3.5 to make it
Python 3.6. Tell us how you like them the what’s new in Python 3.6 article.

How to Install Python on Windows – Possible Issues after Installation


by DataFlair Team · November 15, 2018

1. Install Python – Objective

Previously, we discussed Introduction to python. In this Install Python Windows tutorial, we will see how to
install python windows. Along with this, we will discuss issues we faced after the installation of Python.

Learn: Python Syntax and Semantics for Beginners

So, let’s start how to install Python Windows Tutorial.

How to Install Python on Windows – Possible Issues after Installation

2. How to Install Python on Windows?

Installing and running Python on your personal computer is no difficult task. It involves just a few simple steps:

 Download binaries from python.org


 Install the binaries
 Add Python to system environment variables
 Install pip
 [Optional] Install virtualenv using pip
a. Download binaries from python.org

Install Python 3 on Windows

Firstly, to install Python Windows you need to download required binaries from the following link:

https://www.python.org/downloads/

We recommend you to download Python latest (Python 3.6.3, currently) installer for Windows.

If you have a different OS, download binaries accordingly. You may choose an x86-64 installer if you have a
64-bit system. Choose an x86 installer if you have a 32-bit system. But you can also click on the download
button in the page header.

b. Install Python binaries


Next, you need to install the binaries you downloaded.

Run the installer. It will show you two options.

Install PIP Windows

This is the default option. It also includes the IDLE (Integrated Development Environment),

pip, and the official documentation. It also creates shortcuts.

Learn:Python Comment, Indentation and Statement


Customize Python Installation

This option allows you to choose the features that you want.

Install Python 3 on Windows: Customize Python Installation

You will see the following checkboxes:

 Documentation
 pip
 tcl/tk and IDLE- installs tkinter and the IDLE
 Python test suite- This installs the standard library test suite of Python

Advanced Options while Installing Python


Install Python on Windows: Advanced Options while Installing Python

 Next, it gives you a set of advanced options:


 Install for all users
 Associate files with Python (requires the py launcher)
 Create shortcuts for installed applications
 Add Python to environment variables
 Precompile standard library
 Download debugging symbols
 Download debug binaries (requires VS 2015 or later)
 You may also specify the location to install the directory at.

Learn: Variables and Data Types in Python

Other than these two options, the installer also asks you if you want to add Python to PATH.

We will look at this in step 3. Click ‘Install’ and wait till the progress meter hits the end.
Locate the Python directory on your computer and append the location to the end of the PATH variable. It may
look like this: C:\Users\lifei\AppData\Local\Programs\Python\Python36-32

An environment variable holds values about the current environment. You need it so you can access Python
through the command line.

d. Install pip
If you tick the checkbox for pip in Step 2, pip will install for you.

e. [Optional] Install virtualenv using pip

Python Installation – Install virtualenv using pip


This step is optional. If you install virtualenv, you can create a virtual Python environment. Now you don’t need
to worry about version conflicts among projects. Use pip to install it:
pip install virtual env

Pip will install this for you.

Learn:Python Strings with String Functions and String Operations

3. After You Install Python on Windows

You have now installed Python. Now, you can find a list of programs in the Start Menu.
Install Python 3 on Windows

So now, you can reach Python in the following ways:

a. Command Prompt
You can run Python on the command prompt in two ways:

1) The Conventional way

Search for Command Prompt, and type the following:

python
Now, you can use it as an interpreter. As an example, we have calculated 2+3.

Install Python 3 on Windows

2) Using the Start Menu

Open the Start menu. Click on Python 3.6 (32-bit). This will take you to the command prompt for Python. You
can now begin coding.

Learn: Python Operators with Syntax and Examples

b. The IDLE

Python 3 install on Windows

You can use the Integrated Development Environment to code in Python. If you use the Python Shell, you can
use it as an interpreter. Otherwise, you can create a new file to write a Python program. Later, you can save it
and click ‘Run’ to run the program.

1. for a in range(7):
2. print(a)

c. Python 3.6 Manuals (32-bit)


This is the official Python documentation. You can refer to it when you run into an issue with a program.

d. Python 3.6 Module Docs (32-bit)


This takes you to the index of modules available in Python through a localhost.
Learn:Bitwise Operator in Python with Syntax and Example
4. Possible Issues After Python Installation

 The Python setup may fail if you don’t have Windows Service Pack 1 (SP1) installed on your computer.
It is a requirement for installing Python. You may download it from the following link:
https://support.microsoft.com/en-in/help/15090/windows-7-install-service-pack-1-sp1
 If it states an unspecified error, try downloading KB2999226 here:
https://www.microsoft.com/en-us/download/confirmation.aspx?id=49093
It is an update for Windows 7.
 For other issues, check the log file.

So, this was all about the Install Python Windows Tutorial. Hope you like the tutorial on Install Python on
Windows.

5. Conclusion – Install Python Windows

We saw how easy it is to set up an environment for you to install Python on your computer. It does not take
more than 5 minutes in the best case. See you in the next lesson where we explain the syntax of Python.

If you have any query or feedback on the tutorial on Install Python on Windows, drop a comment and we will
get back to you.

Python Applications – 9 Real World Applications of Python


Programming
by DataFlair Team · July 17, 2019

Let’s discuss python applications to that python can accomplish in the world. In this applications of Python
programming tutorial, you will know about 9 applications of Python Lets go through these Python applications
one by one.

We’ve been learning Python programming over the last two months and we’ve learned quite some useful stuff.
But when you can see what you can do with something, it feels powerful. It lends you some actual motivation to
keep going.

So, let’s start Python Applications.


Python Applications – 9 Real World Applications of Python Programming

Python Applications

1. Web and Internet Development


Python lets you develop a web application without too much trouble. It has libraries for internet protocols like
HTML and XML, JSON, e-mail processing, FTP, IMAP, and easy-to-use socket interface. Yet, the package
index has more libraries:

 Requests – An HTTP client library


 BeautifulSoup – An HTML parser
 Feedparser – For parsing RSS/Atom feeds
 Paramiko – For implementing the SSH2 protocol
 Twisted Python – For asynchronous network programming

We also have a gamut of frameworks available. Some of these are- Django, Pyramid. We also get
microframeworks like flask and bottle. We’ve discussed these in our write-up on an Introduction to
Python Programming.
We can also write CGI scripts, and we get advanced content management systems like Plone and Django CMS.

2. Applications of Python Programming in Desktop GUI


Most binary distributions of Python ship with Tk, a standard GUI library. It lets you draft a user interface for an
application. Apart from that, some toolkits are available:

 wxWidgets
 Kivy – for writing multitouch applications
 Qt via pyqt or pyside
And then we have some platform-specific toolkits:

 GTK+
 Microsoft Foundation Classes through the win32 extensions
 Delphi

3. Science and Numeric Applications


This is one of the very common applications of python programming. With its power, it comes as no surprise
that python finds its place in the scientific community. For this, we have:

 SciPy – A collection of packages for mathematics, science, and engineering.


 Pandas- A data-analysis and -modeling library
 IPython – A powerful shell for easy editing and recording of work sessions. It also supports
visualizations and parallel computing.
 Software Carpentry Course – It teaches basic skills for scientific computing and running bootcamps. It
also provides open-access teaching materials.
 Also, NumPy lets us deal with complex numerical calculations.

4. Software Development Application


Software developers make use of python as a support language. They use it for build-control and management,
testing, and for a lot of other things:

 SCons – for build-control


 Buildbot, Apache Gump – for automated and continuous compilation and testing
 Roundup, Trac – for project management and bug-tracking.
 Roster of Integrated Development Environments

5. Python Applications in Education


Thanks to its simplicity, brevity, and large community, Python makes for a great introductory programming
language. Applications of python programming in education has huge scope as it is a great language to teach in
schools or even learn on your own.
If you still haven’t begun, we suggest you read up on what we have to say about the white and dark sides of
Python. Also, check out Python Features.

6. Python Applications in Business


Python is also a great choice to develop ERP and e-commerce systems:

 Tryton – A three-tier, high-level general-purpose application platform.


 Odoo – A management software with a range of business applications. With that, it’s an all-rounder and
forms a complete suite of enterprise-management applications in-effect.

7. Database Access
With Python, you have:
 Custom and ODBC interfaces to MySQL, Oracle, PostgreSQL, MS SQL Server, and others. These are
freely available for download.
 Object databases like Durus and ZODB
 Standard Database API

8. Network Programming
With all those possibilities, how would Python slack in network programming? It does provide support for
lower-level network programming:

 Twisted Python – A framework for asynchronous network programming. We mentioned it in section 2.


 An easy-to-use socket interface

9. Games and 3D Graphics


Safe to say, this one is the most interesting. When people hear someone say they’re learning Python, the first
thing they get asked is – ‘So, did you make a game yet?’

PyGame, PyKyra are two frameworks for game-development with Python. Apart from these, we also get a
variety of 3D-rendering libraries.

If you’re one of those game-developers, you can check out PyWeek, a semi-annual game programming contest.

Other Python Applications


These are some of the major Python Applications. Apart from what we just discussed, it still finds use in more
places:

 Console-based Applications
 Audio – or Video- based Applications
 Applications for Images
 Enterprise Applications
 3D CAD Applications
 Computer Vision (Facilities like face-detection and color-detection)
 Machine Learning
 Robotics
 Web Scraping (Harvesting data from websites)
 Scripting
 Artificial Intelligence
 Data Analysis (The Hottest of Python Applications)

This was all about the Python Applications Tutorial. If you like this tutorial on applications of Python
programming comment below.

Why should you Learn python? Refer this link to get your answer.
Ready to install Python? Refer this link Python Installation
Summary

Python is everywhere and now that we know python Applications. We can do with it, we feel more powerful
than ever. If there’s a unique project you’ve made in the Python language.

Share your experience with us in the comments. You can also share your queries regarding Python Application
tutorial.

For Reference

Python in Healthcare – Good Health now depends on Code too!!


by DataFlair Team · September 11, 2019

We have always known python as an object-oriented, high-level programming language with dynamic
semantics. It has attracted users from different platforms for its advantages in rapid application development
and its dynamic building options. Little did we know that it is considered to be one of the “safest” programming
languages too apart from all the popularity because of its functionality. Also, Python plays an important role in
the healthcare sector.

Although it is tough for a normal person to believe that programming languages like Python are important in
healthcare. There’s not only one reason that makes python in the limelight of healthcare. There are a number of
reasons which make Python an important asset for the ones researching in the healthcare department.

Let’s explore, what is the importance of Python in healthcare and why it is considered to be one of the safest
languages.

Before moving ahead in Python in Healthcare article, read a little about Python Frameworks that are Django and
Flask.
Django and Flask – The Python Frameworks

The performance of Python is appreciated against abilities like meeting deadlines, quality and amount of code.
To achieve the same, Python is present with a framework Django.

Its trustworthy modules are so effective that you don’t need to develop them by yourself. Also, the built-in
maintenance against the web-app attack adds to its utility. Django framework allows developers to meet their
requirements of any business idea related to eHealth or telemedicine projects.

There is also Flask, again a Python-based framework often used for building prototypes because of its great
efficiency and can be extended to the full-stack framework with existing extensions. Its uses are still less than
that of Django because it requires more time for configuration.

Why Python in Healthcare is Important?


Below are some important reasons for using Python in Healthcare sector, have a look –

1. Python and its frameworks work on principles that are grounded equally and agreed upon the HIPAA
checklist.
2. A full look at the big data healthcare allows the organization to exchange information for seeking
patient outcomes.
3. The performance of the platforms made with Python is focused on their availability in phones and the
web.

How Medical Startups are using Python?

 Roam Analysis
Uses machine learning (artificial intelligence) and comprehensive contextual data to take over
biopharmaceutical and medical device companies, that need to make decisions, suggest treatments and get the
best possible patient outcomes.

Roam’s platform is powered by a proprietary data asset called Health Knowledge Graph which is continuously
enriched using natural language processing to gather information and make connections with new data.

According to the official description, “Roam’s machine learning and data platform powers rich analysis
of patient journeys to reveal the factors affecting treatment decisions and outcomes.”

 AiCure
It is an NIH and VC-funded healthcare startup in New York. AiCure automates the process of ensuring that
patients are taking their medicines, that too at their assigned time. It has combined artificial intelligence and
mobile technology together.

For example, it uses computer vision to identify the patient (face recognition) and verify the right pill for the
specific patient (using pill recognition) and they are actually consuming them (action recognition). They
develop their backend applications using Django frameworks and use python base coding and research
engineers to develop it.
Amazed by the magic of Python in Healthcare? Here are some more startups –

 Drchrono
It is a software as a service patient care platform that consists of a web and cloud-based app. This American
company is for doctors and patients that make electronic health records available digitally and provides
management and medical billing services. This is also a phone and web concentrated platform.

 Fathom Health
Again a Healthcare startup with deep learning NLP system for reading and understanding electronic health
records. This startup with headquarters in San Francisco, California is backed up by Google. Their employees
are familiar with Flask for API programming and data engineers prefer Python’s NLTK.

Summary
As we saw that Python is not only suitable for programming and web-based applications but it is also helpful in
the healthcare sector. The Python is in the continuous development face. That is one of the major reasons why
Python got such a big hand in the healthcare department. This application of Python will lead towards a better
future and betterment of healthcare. Healthcare is a challenging field and Python is performing very well here.

Python role in Healthcare is just not limited here there are much more applications of Python that will lead
towards a better and more high tech future. Many of us are unknown from the fact that Iron Man’s Jarvis is
made up of Python.

So you must start thinking of your future in Python. As Python is the most trending language, you must
start learning Python on your own to secure your future.

Happy learning

Python will make you rich in the stock market!


by DataFlair Team · September 13, 2019

There are so many factors involved in the prediction of stock market performance hence it becomes one of the
most difficult things to do especially when high accuracy is required. Here data science & its techniques have
been used to search patterns and insights that were not approachable before. Learning Python- object-oriented
programming, data manipulation, data modeling, and visualization is a ton of help for the same. So, what are
you waiting for? Read the complete article and know how helpful Python for stock market.

Stocker is a Python class-based tool used for stock prediction and analysis. (for complete code refer GitHub)
Stocker is designed to be very easy to handle. Even the beginners in python find it that way. It is one of the
examples of how we are using python for stock market and how it can be used to handle stock market-related
adventures.

So, before we move further, I recommend you to check the Python master guide, to learn everything
about Python.
Python for Stock market
Let’s look at the analytical capabilities of Stocker in parts.

Starting with Stocker


The first thing that should be done is importing the Stocker class into the current python session after installing
the required libraries. You can use it to create an object. The constructed object will contain all the properties of
the Stocker class. As the stocker is built on quandl WIKI database hence it allows access to 3000 and more US
stocks.

Python classes are comprised of – attributes and methods. Amongst all the attributes of the class, one of it is
stock data for a specific company.

The benefits of using the Python class include – the functions and the data it acts on are associated with the
same object. The entire history of the stock can be plotted by using the method of the Stocker object. The
‘plot_stock’ function has a number of arguments that are optional and by default, it plots the adjusted closing
price for the entire date range that can also be customized according to our needs (range, stats to be plotted, type
of plot). Using ‘plot)stock’ we can investigate any number of quantities in the data present in any data range and
also suggest real-world correlations.

Additive tools
These are very powerful for analyzing and predicting time series. We know that the long term trend of any
established multinational company seems to be increasing in nature but there is a possibility of identifying
yearly or daily basis patterns. Such help of time series with daily observations can be provided by Prophet,
developed by Facebook. Stocker can do all the work that be done by Prophet behind the scenes using simple
method call to create and inspect the model.
These types of models remove disturbance present in data and smoothen it. Prophet models also look into
fluctuations of data in real-life processes and make predictions for the future. Though there is concern related to
past data but future data analysis is what companies strive for. This method call returns two objects (data and
model) which are then assigned to variables that are later on used to plot time series components.

Explore top Python Applications to know more about the use of Python

Changepoints
It occurs when the time-series go from increasing to decreasing or vice-versa. These patterns are also very
important as one needs to know when the stock rate is at its peak or there are significant economic benefits.
Identifying these points and their cause of change helps in predicting the future. The stocker object can
automatically predict the 10 largest changepoints which tend to line up near the peaks and valleys of the stock
price graph (generally). On the other hand, the prophet can only find changepoints in the first 80% data only.
Google search tools allow us to see the popularity of any search word over time in Google searches. Stocker can
automatically retrieve this data for any specific term.

These are only the first half capabilities of the stocker where Python for stock market is used. The second half –

Predictions
They are designed for forecasting, or predicting future prices. This is a tiresome exercise and hence needs plenty
of learning to get into the actual process. The capabilities are publically available, even creating the tool itself.

Summary
We live in an age where anyone can learn programming or arts like data science or machine learning without
that much of formal instructions. The idea can be anything, even stock prediction, python can be used in any
sort of application base. All you need is hands-on knowledge of it!

Python Syntax | The Best Tutorial to Learn Python Syntax


by DataFlair Team · September 17, 2019

1. Python Syntax: Objective

Previously, we saw what is Python and how to set up a Python environment on your computer. The code in
any language must follow a set of rules. Today, we will learn about the Python syntax. In doing so, you will see
what is Python Syntax and how it is different to Java and C++. After this lesson, you will be able to identify and
debug beginner Python syntax.

So, let’s start the Python Syntax Tutorial.


Python Syntax | The Best Tutorial to Learn Python Syntax

Read: Python Built-In Functions with Syntax and Examples

2. Introduction to Python Syntax

Let us see various basic python syntax that is used while doing programming in Python.

3. Python Line Structure

A Python program comprises logical lines. A NEWLINE token follows each of those. The interpreter ignores
blank lines.

The following line causes an error.

1. >>> print("Hi
2. How are you?")

Output:

SyntaxError: EOL while scanning string literal

If you face any doubt anywhere in the Python Syntax Tutorial, Please Comment.

Read: Python Function Arguments with Types, Syntax, and Examples

4. Python Multiline Statements

This one is an important Python Syntax


We saw that Python does not mandate semicolons. A new line means a new statement. But sometimes, you may
want to split a statement over two or more lines. It may be to aid readability. You can do so in the following
ways.

a. Use a backward slash


1. >>> print("Hi\
2. how are you?")

Output:

Hihow are you?

You can also use it to distribute a statement without a string across lines.

1. >>> a\
2. =\
3. 10
4. >>> print(a)

Output:

10

b. Put the string in triple quotes


1. >>> print("""Hi
2. how are you?""")

Output:

Hi
how are you?

However, you can’t use backslashes inside a docstring for statements that aren’t a string.

1. >>> """b\
2. =\
3. 10"""

Output:
‘b=10’

1. >>> print(b)

Output:

Traceback (most recent call last):


File “<pyshell#6>”, line 1, in <module>
print(b)
NameError: name ‘b’ is not defined
Read: Python Functions with Syntax and Examples

5. Python Comments

Python Syntax ‘Comments’ let you store tags at the right places in the code. You can use them to explain
complex sections of code. The interpreter ignores comments. Declare a comment using an octothorpe (#).

1. >>> #This is a comment

Python does not support general multiline comments like Java or C++.

6. Python Docstrings

A docstring is a documentation string. Like a comment, this Python Syntax is used to explain code. But unlike
comments, they are more specific. Also, they are retained at runtime. This way, the programmer can inspect
them at runtime. Delimit a docstring using three double quotes. You may put it as a function’s first line to
describe it.

1. >>> def func():


2. """
3. This function prints out a greeting
4. """
5. print("Hi")
6. >>> func()

Output:

Hi

Any query yet in Python Syntax Tutorial? Please Comment.

7. Python Indentation

Since Python doesn’t use curly braces to delimit blocks of code, this Python Syntax is mandatory. You can
indent code under a function, loop, or class.

1. >>> if 2>1:
2. print("2 is the bigger person");
3. print("But 1 is worthy

too"); Output:

2 is the bigger
person But 1 is
worthy too

You can indent using a number of tabs or spaces, or a combination of those. But remember, indent statements
under one block of code with the same amount of tabs and spaces.

1. >>> if 2>1:
2. print("2 is the bigger person");
3. print("But 1 is worthy too");
Output:

SyntaxError: unindent does not match any outer indentation level

8. Python Multiple Statements in One Line

You can also fit in more than one statement on one line. Do this by separating them with a semicolon. But
you’d only want to do so if it supplements readability.

1. >>> a=7;print(a);

Output:

9. Python Quotations

Python supports the single quote and the double quote for string literals. But if you begin a string with a single
quote, you must end it with a single quote. The same goes for double quotes.

The following string is delimited by single quotes.

1. >>> print('We need a

chaperone'); Output:

We need a chaperone

This string is delimited by double quotes.

1. >>> print("We need a 'chaperone'");

Output:

We need a ‘chaperone’

Notice how we used single quotes around the word chaperone in the string? If we used double quotes
everywhere, the string would terminate prematurely.

1. >>> print("We need a "chaperone"");

Output:

SyntaxError: invalid syntax

10. Python Blank Lines

If you leave a line with just whitespace, the interpreter will ignore it.

Let us see next python syntax of Identifiers.


11. Python Identifiers

An identifier is a name of a program element, and it is user-defined. This Python Syntax uniquely identifies the
element. There are some rules to follow while choosing an identifier:

1. An identifier may only begin with A-Z, a-z, or an underscore(_).


2. This may be followed by letters, digits, and underscores- zero or more.
3. Python is case-sensitive. Name and name are two different identifiers.
4. A reserved keyword may not be used as an identifier. The following is a list of keywords.

and def False import not True


as del finally in or try
assert elif for is pass while
break else from lambda print with
class except global None raise yield
continue exec if nonlocal return

Apart from these rules, there are a few naming conventions that you should follow while using this Python
syntax:

1. Use uppercase initials for class names, lowercase for all others.
2. Name a private identifier with a leading underscore ( _username)
3. Name a strongly private identifier with two leading underscores ( password)
4. Special identifiers by Python end with two leading underscores.

12. Python Variables

In Python, you don’t define the type of the variable. It is assumed on the basis of the value it holds.

1. >>> x=10
2. >>> print(x)

Output:

10

1. >>> x='Hello'
2. >>> print(x)

Output:

Hello

Here, we declared a variable x, and assigned it a value of 10. Then we printed its value. Next, we assigned it the
value ‘Hello’, and printed it out. So, we see, a variable can hold any type of value at a later instant. Hence,
Python is a dynamically-typed language.

13. Python String Formatters

Let us see next python syntax String formatters.


a. % Operator
You can use the % operator to format a string to contain text as well as values of identifiers. Use %s where you
want a value to appear. After the string, put a % operator and mention the identifiers in parameters.

1. >>> x=10; printer="HP"


2. >>> print("I just printed %s pages to the printer %s" % (x,

printer)) Output:

I just printed 10 pages to the printer HP

b. format method
The format method allows you to format a string in a similar way. At the places, you want to put values, put
0,1,2,.. in curly braces. Call the format method on the string and mention the identifiers in the parameters.

1. >>> print("I just printed {0} pages to the printer {1}".format(x, printer))

Output:

I just printed 10 pages to the printer HP

You can also use the method to print out identifiers that match certain values.

1. >>> print("I just printed {x} pages to the printer {printer}".format(x=7,

printer='HP')) Output:

I just printed 7 pages to the printer HP

c. f-strings
If you use an f-string, you just need to mention the identifiers in curly braces. Also, write ‘f’ right before the
string, but outside the quotes used.

1. >>> print(f"I just printed {x} pages to the printer {printer}")

Output:

I just printed 10 pages to the printer HP

So, this was all about the Python Syntax tutorial. Hope you like our explanation

14. Python Syntax – Conclusion

In this Python Syntax tutorial, we learned about the basic Python syntax. We learned about its line structure,
multiline statements, comments and docstrings, indentation, and quotations. We also learned about blank lines,
identifiers, variables, multiple statements in one line, and string formatters. In the next lesson, we will look at
different variable types in Python.
If you have any query regarding the Python Syntax Tutorial, please drop a comment.

Python Comment | Python Indentation | Python Statement


by DataFlair Team · May 17, 2019

1. Python Comment, Python Indentation and Python Statement

Now that we’re getting used to Python and its ways, we think it is time to sharpen python syntax in our brains.
In this tutorial, we will revise basic syntax- Python Comment, Python indentation, and a Python statement with
their sub types, syntax and examples.

So, let’s start learning Python Comment, Python Indentation, and Python Statement.

Python Comment, indentation, and Statement

2. Python Statement

The Python interpreter deals with statements. Through our journey, we have seen the conditional statements in
python like ‘if’, ‘for’, ‘while’, and so on. The following is a Python statement.

1. >>> a*=3
Python Comment – Python Statement

a. Multiline Python Statement


In Python, every statement ends with a newline character. But like we have seen, it is possible to span a
statement over multiple lines. We do this using the ‘\’ character.

1. >>> a=\
2. 10\
3. +20
4. >>> a

30

1. >>> "Hello\
2. hi"

‘Hellohi’
But you can also use a set of parentheses for this.

1. >>> a=(
2. 10+
3. 20)
4. >>> a

30

1. >>> type(a)
2. <class 'int'>

Read: Syntax in Python with Examples

b. Multiple Python Statement in One Line


You can easily put multiple statements in python on one line.
1. >>> a=7; print(a)

7
You can also do this to an if-statement.

1. >>> if 2>1: print("2")

c. Strings Python Statements


To declare strings in python, you may use single or double quotes.

1. >>> "Hello 'user'"

“Hello ‘user'”
If you use double quotes outside, use single quotes wherever you need to use a quote inside.

d. Blank Lines Python Statements


The interpreter simply ignores blank lines.

3. Python Indentation

Unlike C++ or Java, Python does not use curly braces for indentation. Instead, Python mandates indentation. At
this point, our inner monsters are laughing at the lazy programmers around us.

1. >>> if 2>1:
2. print("2")

2
There are no strict rules on what kind of Python indentation you use. But it must be consistent throughout the
block. Although, four whitespaces are usually preferred, and tabs are discouraged. Let’s take an example with
an inconsistent indentation in python.

1. >>> if 2>1:
2. print("1")
3. print("2")

SyntaxError: unexpected indent

Read: Python Built-In Functions with Syntax and Examples

4. Python Comment

Python Comment is a programmer’s tool. We use them to explain the code, and the interpreter ignores them.
You never know when a programmer may have to understand code written by another and make changes to it.
Other times, give your brain a month’s time, and it might forget what it once had conjured up in your code. For
these purposes, good code will hold comments in the right places.
In C++, we have // for single-lined comments, and /* … */ for multiple-lined comments. Here, we only have
single-lined python comment.
To declare a Python comment, use the octothorpe (hash) (#).

1. >>> #This is a comment


2. >>>

Types of Python comment

a. Multiline Python Comment


To have multiline python comment in your code, you must use a hash at the beginning of every line of your
comment in python.

1. >>> #Line 1 of comment


2. >>> #Line 2 of comment
3. >>> #Line 3 of comment

You can also use triple quotes (‘’’ ‘’’ or “”” “””) for this purpose.

1. >>> """This comment


2. is spanned across
3. multiple lines"""

‘This comment\nis spanned across\nmultiple lines’


This gives us an output because we type it in the shell. When you create a file and write this in that, there is no
output. While triple quotes are generally used for multiline python comment, we can conveniently use them for
python comment as well.
Triple quotes will also preserve formatting.

1. >>> print("""Hello
2. Hi""")

Hello
Hi
b. Docstrings Python Comment
A docstring is a documentation string in Python. It is the first statement in a module, function, class, or
method in Python. In this, we explain what a python function/class does.

1. >>> def sayhi():


2. """
3. This function prints Hi
4. """
5. print("Hi")
6. >>> sayhi()

Hi
To check a function’s docstring, use its doc attribute.

1. >>> def sayhi():


2. """
3. This function prints Hi
4. """
5. print("Hi")
6. >>> sayhi. doc

‘\n\tThis function prints Hi\n\t’


The interpreter is unable to get the docstring to a function if it isn’t the first thing in the python function.

1. >>> def sayhi():


2. print("Hi")
3. """
4. This function prints Hi
5. """
6. >>> sayhi. doc
7. >>>

Read: Applications of Python Programming Language

So, this was all about Python indentation, comment and statement. Hope you like our explanation.

5. Python Comment – Conclusion

Hope we’ve reconnected you to some basics python Syntax- Python indentation, comments and statement.
Don’t forget to try out your own combinations. If you don’t get something in Python indentation, Comment and
statement ask us in the comments.

Python Assert Statements | Assertionerror in Python


by DataFlair Team · May 17, 2019

1. Objective – Python Assert


In what follows, we will discuss Python Assert Statements. We will see what they are, how to implement and
where to use Python Assert Statements. Moreover, we will discuss Python Assert syntax and example. Also, we
will learn using error message and handling Assertionerror Python.

So, let’s start Python Assert Tutorial.

Python Assert Statements | Assertion Error in Python

2. What are Python Assert Statements?

Let’s discuss the meaning of Assertion in Python Programming Langauge in detail:

a. What is Assertion in Python?


An Assertion in Python or a Python Assert Statement is one which asserts (or tests the trueness of) a condition
in your code. This is a Boolean expression that confirms the Boolean output of a condition.
Do you know about Python variables and Data Types

b. Why Assertion in Python is Used?


This is a debugging tool. If it finds the condition to be true, there is nothing it needs to do. So, it moves over to
the next line of code. If not, it stops all operations and throws an error. It also shows the point of error in the
code.
The point of assertions in Python is to help deal with unrecoverable errors.
The assertion in Python programming Language

c. Where Assertion in Python used?


 In checking types/ in checking valid input.
 In checking values of arguments.
 Checking outputs of functions.
 As a debugger to halt where an error occurs.
 In testing code.
 In detecting abuse of an interface by another programmer.

3. Python Assert Example and Syntax

Python Assert Statement is one we always want to see true. Let’s take an example and see what happens when a
condition turns false-
You must read about Python Syntax

1. >>> assert 2==3

Traceback (most recent call last):


File “<pyshell#0>”, line 1, in <module>
assert 2==3
AssertionError
Hence, this is an AssertionError in Python. We’d use it to catch false assumptions we made while writing the
code.

a. Python Assert Syntax


1. assert <condition>
1. assert <condition>, <error message>

b. Python Assert Example


Now, let’s devise a function to divide two numbers. What happens when we try to divide a number by 0?

1. >>> def div(p,q):


2. assert q!=0
3. return p/q
4. >>> div(2,3)
5. 0.6666666666666666
6. >>> div(2,0)

Traceback (most recent call last):


File “<pyshell#7>”, line 1, in <module>
div(2,0)
File “<pyshell#5>”, line 2, in div
assert q!=0
AssertionError
As you can see, this stopped the program and threw a Python AssertionError.
Have a look at Python Classes and Object-Oriented Programming

4. Using an Error Message in Python Assert

Instead of throwing six red lines at the developer, Python may want to display something more sophisticated
and less hostile. For this, we give an error message to the assert statement. Let’s see how.

1. >>> def div(p,q):


2. assert q!=0, "You cannot divide a number by zero\nPlease try again"
3. return p/q
4. >>> div(2,0)

Traceback (most recent call last):


File “<pyshell#10>”, line 1, in <module>
div(2,0)
File “<pyshell#9>”, line 2, in div
assert q!=0, “You cannot divide a number by zero\nPlease try again”
AssertionError: You cannot divide a number by zero
Please try again
Okay, this seems longer than what we got before this, but pull a magnifying glass to the last line. It tells you
what really happened, but we can do better than this.

5. Handling the AssertionError in Python

Let’s put this function in a try block and hope to catch it.

1. >>> try:
2. def div(p,q):
3. assert q!=0, "You cannot divide a number by zero\nPlease try again"
4. return p/q
5. except:
6. print("So you tried to divide by 0. Please try again")
7. >>> div(2,0)

Traceback (most recent call last):


File “<pyshell#18>”, line 1, in <module>
div(2,0)
File “<pyshell#17>”, line 3, in div
assert q!=0, “You cannot divide a number by zero\nPlease try again”
AssertionError: You cannot divide a number by zero
Please try again
Wow, this did not work at all. Where’s the “So you tried to divide by 0. Please try again”? Let’s give this
another try.
Let’s discuss Exception Handling in Python

1. >>> def div(p,q):


2. try:
3. assert q!=0, "You cannot divide a number by zero\nPlease try again"
4. return p/q
5. except:
6. print("So you tried to divide by 0. Please try again")
7. >>> div(2,0)

So, you tried to divide by 0. Please try again


Ah, works like a charm this time!

So, this was all in Python Assert. Hope you like our explanation

6. Conclusion: Python Assert

Call it sanity check or paranoia, Python assert statements help us make sure everything’s going fine with our
code. Or maybe we can say that assertions in Python are a secret gift to you from yourself. Twenty days from
today, you will open the box and feel grateful.

Hence, we discussed Assert Statements in Python. Moreover, we saw Python Assert example and syntax. Also,
we discussed using error message and handling Assertionerror Python. Have something to add to this tutorial?
Feel free to drop it in the comments below.

Python Number Types – Python Int, Float, Complete Numbers


by DataFlair Team · May 17, 2019

1. Python Number Types

In our article on Python Variables and Data Types, we learnt about different data types supported by Python.
Now, we will dig a little deeper into those Python number types. As we have seen, a python number can be-
Python int, Python float, or even Python complex number. long is no longer supported by Python 3.x.

So, let’s begin with the python number types tutorial.


Python Number Types – Python Int, Float, Complete Numbers

2. Python Number Types

Before starting with Python number types in, let us revise Python basics and various syntax used in Python
for better understanding.

A number is an arithmetic entity that lets us measure something. Python allows us to store the integer, floating,
and complex numbers and also lets us convert between them. Since Python is dynamically-typed, there is no
need to specify the type of data for a variable. So now let’s start with python number types.

 None- The None keyword indicates the absence of value.

3. Python int

Python can hold signed integers.

1. >>> a=7
2. >>> a

7
It can hold a value of any length, the only limitation being the amount of memory available.

1. >>> a=9999999999999999999999999999999999999
2. >>> a

9999999999999999999999999999999999999

There are three types of this Python number types:


Python Number Types – Python Int

i. type() function
It takes one argument, and returns which class it belongs to.

1. >>> a=9999999999999999999999999999999999999
2. >>> type(a)

<class ‘int’>

ii. isinstance() function


It takes two arguments. The first is the construct(ex- a variable or a list), and the
second is a class. It returns True or False based on whether the construct belongs to
that class. Suppose we want to check if ‘a’ belongs to class bool. We write the following
code for the same.

1. >>>

isinstance(a,bool) False

Since it belongs to the class ‘int’ instead, it returns False.

iii. Exponential numbers

You can write an exponential number using the letter ‘e’ between the mantissa and the
exponent.
1. >>> print(2e5)

200000.0

Remember that this is power of 10. To raise a number to another’s power, we use the ** operator.
If you face difficulty in Python number types, please comment.

4. Python float

Python also supports floating-point real values. An int cannot store the value of the mathematical constant pi,
but a float can.

1. >>> from math import pi


2. >>> pi

3.141592653589793

1. >>> type(pi)

<class ‘float’>

A float value is only accurate upto 15 decimal places. After that, it rounds the number off.

1. >>> a=1.1111111111111111119
2. >>> a

1.1111111111111112

Note that division results in floats.

1. >>> 2/2

1.0

5. Python Complex Numbers

A complex number is a Python number type made of real and imaginary parts. It is represented as a+bj.

1. >>> a=2+3j
2. >>> a

(2+3j)

i. Coefficient to the imaginary part


Here, 2 is the real part, and 3j is the imaginary part. To denote the irrational part, however, you can’t use the
letter ‘i’, like you would do on paper.

1. >>> a=2+3i
SyntaxError: invalid syntax

Also, it is mandatory to provide a coefficient to the imaginary part.

1. >>> a=2+j

Traceback (most recent call last):

File “<pyshell#33>”, line 1, in <module>

a=2+j

NameError: name ‘j’ is not defined

In this case, a coefficient of 1 will do.

1. >>> a=2+1j
2. >>> a

(2+1j)

ii. Operations on complex numbers


Finally, you can perform the basic operations on complex numbers too.

1. >>> a=2+3j
2. >>> b=2+5j
3. >>> a+b

(4+8j)

1. >>> a*=2
2. >>> a

(4+6j)

Here, *= is an in-place assignment operator.

Any Doubt yet in Python number Type? Please Comment.

6. Writing numbers in binary, octal, and hexadecimal

More often than not, programmers need to deal with numbers other than decimal. To do this, you can use
appropriate prefixes.

Number System Prefix


Binary 0b or 0B
Octal 0o or 0O
Hexadecimal 0x or 0X
i. Binary
When you want to write a binary number, use the prefix 0b or 0B. For example, we know that the binary for 7 is
111.

1. >>> print(0b111)

You can also apply conversion functions on these numbers.

1. >>> int(0b10)

ii. Octal
The prefix for octal is 0o or 0O.

1. >>> print(0O10)

The following code causes an error. This is because the octal number system does not have the number 8. It has
the numbers 0-7.

1. >>> print(0O8)

SyntaxError: invalid token

1. >>> float(0B10)

2.0

iii. Hexadecimal
The hexadecimal number system has numbers 0-9 and then A-F. For that, use the prefix 0x or 0X.

1. >>> print(0xFF)

255

1. >>> print(0xFE)

254

7. Python Conversion Functions


Although most times Python does the conversion as needed, you can do it explicitly if you want. These
functions allow us to convert one numeric type into another python number types.
Python Number Types – Python Conversion Functions

i. int()
The int() function can convert another numeric type into an int. It can also convert other types into an int, but in
this tutorial, we focus on numeric types.

1. >>> int(7)

1. >>> int(7.7)

As you can see, it does not round the number 7.7 up to 8; it truncates the 0.7.

However, you cannot convert a complex number into an int.

1. >>> int(2+3j)

Traceback (most recent call last):

File “<pyshell#22>”, line 1, in <module>

int(2+3j)
TypeError: can’t convert complex to int

1. >>> int(3j)

Traceback (most recent call last):

File “<pyshell#23>”, line 1, in <module>

int(3j)

TypeError: can’t convert complex to int

We can also apply this function on representations other than decimal, i.e., binary, octal, and hexadecimal.

1. >>> int(0b10)

1. >>> int(0xF)

15

ii. float()
This function converts another numeric type into a float.

1. >>> float(110)

110.0

1. >>> float(110.0)

110.0

Like int(), float() can’t convert a complex either.

1. >>> float(3j)

Traceback (most recent call last):

File “<pyshell#26>”, line 1, in <module>

float(3j)

TypeError: can’t convert complex to float

1. >>> float(0o10)

8.0

Here, we applied it to an octal number.


iii. complex()
The complex() function converts another numeric type into a complex number.

1. >>> complex(2)

(2+0j)

1. >>> complex(2.3)

(2.3+0j)

1. >>> complex(2+3.0j)

(2+3j)

iv. bin()
The bin() function returns the binary value of a number.

1. >>> bin(2)

‘0b10’

However, you can’t apply it to a float value or a complex value. The same is true for oct() and hex() functions
too.

1. >>> bin(2.3)

Traceback (most recent call last):

File “<pyshell#49>”, line 1, in <module>

bin(2.3)

TypeError: ‘float’ object cannot be interpreted as an integer

1. >>> bin(2+3j)

Traceback (most recent call last):

File “<pyshell#50>”, line 1, in <module>

bin(2+3j)

TypeError: ‘complex’ object cannot be interpreted as an integer

v. oct()
This function returns the octal value of a number.
1. >>> oct(8)

‘0o10’

We know that 8.0 is the same as 8, but the function doesn’t think the same. It is a float, so it cannot convert it
into an oct.

1. >>> oct(8.0)

Traceback (most recent call last):

File “<pyshell#59>”, line 1, in <module>

oct(8.0)

TypeError: ‘float’ object cannot be interpreted as an integer

vi. hex()
The hex() function returns the hexadecimal value of a number.

1. >>> hex(255)

‘0xff’

1. >>> hex(0)

‘0x0’

1. >>> hex(0)

‘0x0’

8. Python Decimal Module

Let’s try out adding 1.1 and 2.2 in the shell, and let’s compare it with 3.3.

1. >>> (1.1+2.2)==3.3

False

Why did it return False? Let’s try printing the sum.

1. >>> 1.1+2.2

3.3000000000000003

Woah, how did this happen? Well, this is duly attributed to hardware limitations, and is not a flaw of Python.
Because the hardware stores decimals as binary fractions, it isn’t possible to store it very accurately. Let’s take
an example.
1. >>> 1/3

0.3333333333333333

When we divide 1 by 3, it doesn’t return the full value, which is 0.3333333333333333… Python does provide a
solution to this problem. It has the ‘decimal’ module, which lets us choose precision. We will learn about
modules in a later lesson.

1. >>> import decimal


2. >>> print(decimal.Decimal(0.1))

0.1000000000000000055511151231257827021181583404541015625

Did you see what happened here? The Decimal() function preserved the significance.This was the Decimal
Function Python number type.

9. The fractions Module

Another module that Python provides, the fractions module lets you deal with fractions. The Fraction() function
returns the value in the form of numerator and denominator.

1. >>> from fractions import Fraction


2. >>> print(Fraction(1.5))

3/2

It can also take two arguments.

1. >>> print(Fraction(1,3))

1/3

10. The math Module


Another essential module is the math module. It has all important mathematical functions like exp,
trigonometric functions, logarithmic functions, factorial, and more.

1. >>> import math


2. >>> math.factorial(5)

120

1. >>> math.exp(3)

20.085536923187668

1. >>> math.tan(90)

-1.995200412208242

This was all about the Python number types tutorial.


11. Conclusion – Python Number Types

In this lesson, we learnt about Python number types. We looked at int, float, and complex numbers. We also
looked at how to write numbers in binary, octal, and hexadecimal representations. Then we looked at how to
convert one numeric type into another. We also looked at some important modules- decimal, fractions, math.
Hope you like the Python Number Type Tutorial. Try your own combinations and leave your feedback on
Python number types tutorial in the comments.
Refer Best Books for Python for in depth Python learning.

Python Random Number – Generate Random Numbers With NumPy


by DataFlair Team · September 29, 2018

1. Objective – Python Random Number

Today, in this Python tutorial, we will talk about Python Random Number. Moreover, we will see ways to
generate Random Number in Python. Also, we will discuss generating Python Random Number with NumPy.
At last, we will see Import Random Python with the example.
So, let’s begin with Python Random Number.

Python Random Number – Generate Random Numbers With NumPy

2. Need of Python Random Number

A Random Number in Python is any number in a range we decide. From initializing weights in an ANN to
splitting data into random train and test sets, the need for generating random numbers is apparent. Another use-
case could be the random shuffling of a training dataset in stochastic gradient descent. So today, we will discuss
pseudorandom generators in Python. We will also try doing that with the standard Python library and with
NumPy.

3. How to Generate Python Random Number?

What we really generate is pseudorandom numbers. There are numbers that appear nearly random but are
actually something we generate with a deterministic process.
A process of Generating Python Random Number

You must read about Python Libraries


Python uses the Mersenne Twister pseudorandom number generator. The process of generating random
numbers involves deterministically generating sequences and seeding with an initial number. The default for the
seed is the current system time in seconds/ milliseconds. A different seed will produce a different sequence of
random numbers.

a. Import Python Random


Before we can begin, let’s first import the module random from the Python Standard Library. You can directly
import it-
import random
To import a piece of functionality from it- say, random, you can:
from random import random
Or for seed, you can:
from random import seed

b. Random Floating Point Numbers


Let’s take an example of generation Python Random Number.

1. >>> from random import seed


2. >>> from random import random
3. >>> seed(7)
4. >>> random(),random(),random(),random()

(0.32383276483316237, 0.15084917392450192, 0.6509344730398537, 0.07243628666754276)


Have a look at Python Packages
Works for us. Now, what if we reseed to the same value and call the random() functions/methods again?

1. >>> seed(7)
2. >>> random(),random(),random(),random()
(0.32383276483316237, 0.15084917392450192, 0.6509344730398537, 0.07243628666754276)
You’ll find it gives us the same thing as it did earlier.

 Working with minimum values and multiplying the floats-

Some days, you may not want to generate Random Number in Python values between 0 and 1. In the following
piece of code, 2 is the minimum value, and we multiple the random number generated by 10.

1. >>> seed(7)
2. >>> 2+10*random()

5.238327648331624

c. Python Random Integers


We use the randint() function to get integers instead, randomly. It takes two arguments- the start and the top,
and then draws a random value from a uniform distribution. Each value has an equal chance of being picked.

1. >>> from random import randint


2. >>> seed(7)
3. >>> randint(0,9),randint(0,9),randint(0,9)

(5, 2, 6)
We asked for three random values, this gave us 5, 2, and 6.
Let’s learn Python Debugger

d. Getting Integers Randomly from a Range


randrange() randomly selects an element from range(start,stop,step).

1. >>> from random import randrange


2. >>> randrange(-2,4)

-1

1. >>> randrange(-2,4)

1. >>> randrange(-2,4)

1. >>> randrange(-2,4)

-1

1. >>> randrange(-2,4)

2
1. >>> randrange(-2,4)

-2

e. Random Gaussian Values


The gauss() function takes in two arguments- the mean and the standard deviation. This gives us a real-valued
distribution.

1. >>> from random import


gauss 2. >>> seed(7)
3. >>> gauss(0,1),gauss(0,1),gauss(0,1)

(-0.2558802884476004, 0.511431512516514, -0.2260961647831047)

f. Choosing Randomly From Lists


It is possible to randomly pick values from our own custom lists. We have the choice() function/method for this.

1. >>> list=[2,4,3,9,6,2,1,0,7,4,3,5,3,6,8]
2. >>> from random import choice
3. >>> seed(7)
4. >>> choice(list),choice(list),choice(list),choice(list),choice(list),choice(list)

(2, 3, 1, 3, 2, 4)
For a choice of multiple values, you can use choices() instead.
Let’s take a tour to Python Network Programming

1. >>> from random import choices


2. >>> choices(list,k=4)

[7, 2, 9, 7]

g. Randomly Choosing a Subset from a List


Once sample() puts an item from a list into the sublist, it does not add it back to the original list for picking
from. This is selection without replacement. Note that this does not modify the original list. This function/
method also takes the size of the subset to create.

1. >>> list

[2, 4, 3, 9, 6, 2, 1, 0, 7, 4, 3, 5, 3, 6, 8]

1. >>> from random import sample


2. >>> sample(list,6)

[6, 7, 4, 2, 4, 2]

h. Shuffling a List Randomly


We can shuffle a list like a deck of cards with the shuffle() function/ method. This shuffles the list in-place. In
other words, it does not need to create a new list to put shuffled items into one by one.

1. >>> list

[2, 4, 3, 9, 6, 2, 1, 0, 7, 4, 3, 5, 3, 6, 8]

1. >>> from random import shuffle


2. >>> shuffle(list)
3. >>> list

[6, 3, 2, 3, 6, 5, 0, 3, 4, 1, 4, 2, 9, 7, 8]
Note that this modifies the list.
Let’s revise Image Processing with NumPy and SciPy

4. How to Generate Python Random Number with NumPy?

With the seed() and rand() functions/ methods from NumPy, we can generate random numbers. The
functionality is the same as above.

1. >>> from numpy.random import seed


2. >>> from numpy.random import rand
3. >>> seed(7)
4. >>> rand(3)

array([0.07630829, 0.77991879, 0.43840923])

1. >>> seed(7)
2. >>> rand(3)

array([0.07630829, 0.77991879, 0.43840923])


So, this was all about Generating Python Random Number. Hope you like our explanation.

5. Conclusion – Python Random Number

Now you know how to generate random numbers in Python. We used two modules for this- random and numpy.
Moreover, we discussed the process of generating Python Random Number with examples. Tell us what you
think about the article Python Random Number. Got a topic you want us to write us on? Let us know in the
comments.

The Best Tutorial on Python Variables and Python Data Types


by DataFlair Team · June 19, 2019

1. Python Variables and Python Data Types

In this Python tutorial on Python Variables and Python Data Types, we will learn about at Python variables and
data types being used in Python. Since we know that Python is a dynamically-typed language, we don’t specify
the type of a variable when declaring one. We will also learn about converting one data type to another in
Python and local and global variables in Python. So, let’s begin with Python variables and Python Data Type
Tutorial.
The Best Tutorial on Python Variables and Python Data Types

2. What is Python Variables?

Let us now proceed towards Python variables and Python data types. Before starting, let us revise syntax in
python.

A variable is a container for a value. It can be assigned a name, you can use it to refer to it later in the program.
Based on the value assigned, the interpreter decides its data type. You can always store a different type in a
variable.

For example, if you store 7 in a variable, later, you can store ‘Dinosaur’.

a. Python Variables Naming Rules


There are certain rules to what you can name a variable(called an identifier).

 Python variables can only begin with a letter(A-Z/a-z) or an underscore(_).

1. >>> 9lives=9

SyntaxError: invalid syntax

1. >>> flag=0
2. >>> flag

1. >>> _9lives='cat'
2. >>> _9lives

‘cat’
 The rest of the identifier may contain letters(A-Z/a-z), underscores(_), and numbers(0-9).

1. >>> year2='Sophomore'
2. >>> year2

‘Sophomore’

1. >>> _$$=7

SyntaxError: invalid syntax

 Python is case-sensitive, and so are Python identifiers. Name and name are two different identifiers.

1. >>> name='Ayushi'
2. >>> name

‘Ayushi’

1. >>> Name

Traceback (most recent call last):


File “<pyshell#21>”, line 1, in <module>
Name
NameError: name ‘Name’ is not defined

 Reserved words (keywords) cannot be used as identifier names.

and def False import not True


as del finally in or try
assert elif for is pass while
break else from lambda print with
class except global None raise yield
continue exec if nonlocal return

b. Assigning and Reassigning Python Variables


To assign a value to Python variables, you don’t need to declare its type. You name it according to the rules
stated in section 2a, and type the value after the equal sign(=).

1. >>> age=7
2. >>> print(age)

1. >>> age='Dinosaur'
2. >>> print(age)

Dinosaur

However, age=Dinosaur doesn’t make sense. Also, you cannot use python variables before assigning it a value.
1. >>> name

Traceback (most recent call last):


File “<pyshell#8>”, line 1, in <module>
name
NameError: name ‘name’ is not defined

You can’t put the identifier on the right-hand side of the equal sign, though. The following code causes an error.

1. >>> 7=age

SyntaxError: can’t assign to literal

Neither can you assign python variables to a keyword.

1. >>> False=choice

SyntaxError: can’t assign to keyword

c. Multiple Assignment
You can assign values to multiple python variables in one statement.

1. >>> age,city=21,'Indore'
2. >>> print(age,city)

21 Indore

Or you can assign the same value to multiple python variables.

1. >>> age=fav=7
2. >>> print(age,fav)

77

This is how you assign values to Python Variables

d. Swapping variables
Swapping means interchanging values. To swap Python variables, you don’t need to do much.

1. >>> a,b='red','blue'
2. >>> a,b=b,a
3. >>> print(a,b)

blue red

e. Deleting variables
You can also delete python variables using the keyword ‘del’.
1. >>> a='red'
2. >>> del a
3. >>> a

Traceback (most recent call last):


File “<pyshell#39>”, line 1, in <module>
a
NameError: name ‘a’ is not defined

This is How you can delete Python Variables

Python Variables and Python Data Types

3. Python Data Types

Although we don’t have to declare type for python variables, a value does have a type. This information is vital
to the interpreter. Python supports the following Python data types.

a. Python Numbers
There are four numeric Python data types.

1. int– int stands for integer. This Python Data Type holds signed integers. We can use
the type() function to find which class it belongs to.

1. >>> a=-7
2. >>> type(a)

<class ‘int’>
An integer can be of any length, with the only limitation being the available memory.

1. >>> a=9999999999999999999999999999999
2. >>> type(a)

<class ‘int’>

2. float– This Python Data Type holds floating point real values. An int can only store
the number 3, but float can store 3.25 if you want.

1. >>> a=3.0
2. >>> type(a)

<class ‘float’>

3. long – This Python Data Types holds a long integer of unlimited length. But this construct does not exist in
Python 3.x.

4. complex- This Python Data Types holds a complex number. A complex number looks like this: a+bj Here, a
and b are the real parts of the number, and j is imaginary.

1. >>> a=2+3j
2. >>> type(a)

<class ‘complex’>

Use the isinstance() function to tell if python variables belong to a particular class. It takes two parameters- the
variable/value, and the class.

1. >>> print(isinstance(a,complex))

True

b. Strings
A string is a sequence of characters. Python does not have a char data type, unlike C++ or Java. You can delimit
a string using single quotes or double quotes.

1. >>> city='Ahmedabad'
2. >>> city

‘Ahmedabad’

1. >>> city="Ahmedabad"
2. >>> city

‘Ahmedabad’

1. Spanning a string across lines – To span a string across multiple lines, you
can use triple quotes.
1. >>> var="""If
2. only"""
3. >>> var

‘If\n\tonly’

1. >>> print(var)

If
Only

1. >>> """If
2. only"""

‘If\n\tonly’

As you can see, the quotes preserved the formatting (\n is the escape sequence for newline, \t is for tab).

2. Displaying part of a string– You can display a character from a string using its
index in the string. Remember, indexing starts with 0.

1. >>> lesson='disappointment'
2. >>> lesson[0]

‘d’

You can also display a burst of characters in a string using the slicing operator [].

1. >>> lesson[5:10]

‘point’

This prints the characters from 5 to 9.

3. String Formatters– String formatters allow us to print characters and values at once.
You can use the % operator.

1. >>> x=10;
2. >>> printer="Dell"
3. >>> print("I just printed %s pages to the printer %s" % (x,

printer)) Or you can use the format method.

1. >>> print("I just printed {0} pages to the printer {1}".format(x, printer))
2. >>> print("I just printed {x} pages to the printer {printer}".format(x=7,

printer="Dell")) A third option is to use f-strings.

1. >>> print(f"I just printed {x} pages to the printer {printer}")

4. String Concatenation– You can concatenate(join) strings.


1. >>> a='10'
2. >>> print(a+a)

1010

However, you cannot concatenate values of different types.

1. >>> print('10'+10)

Traceback (most recent call last):

File “<pyshell#89>”, line 1, in <module>;

print(’10’+10)

TypeError: must be str, not int

c. Python Lists
A list is a collection of values. Remember, it may contain different types of values. To define a list, you must
put values separated with commas in square brackets. You don’t need to declare a type for a list either.

1. >>> days=['Monday','Tuesday',3,4,5,6,7]
2. >>> days

[‘Monday’, ‘Tuesday’, 3, 4, 5, 6, 7]

1. Slicing a list – You can slice a list the way you’d slice a string- with the slicing operator.

1. >>> days[1:3]

[‘Tuesday’, 3]

Indexing for a list begins with 0, like for a string. A Python doesn’t have arrays.

2. Length of a list– Python supports an inbuilt function to calculate the length of a list.

1. >>> len(days)

3. Reassigning elements of a list– A list is mutable. This means that you can
reassign elements later on.

1. >>> days[2]='Wednesday'
2. >>> days

[‘Monday’, ‘Tuesday’, ‘Wednesday’, 4, 5, 6, 7]

4. Multidimensional lists– A list may have more than one dimension. We will look
further into this in the tutorial on Python Lists.
1. >>> a=[[1,2,3],[4,5,6]]
2. >>> a

[[1, 2, 3], [4, 5, 6]]

d. Python Tuples
A tuple is like a list. You declare it using parentheses instead.

1. >>> subjects=('Physics','Chemistry','Maths')
2. >>> subjects

(‘Physics’, ‘Chemistry’, ‘Maths’)

1. Accessing and Slicing a Tuple– You access a tuple the same way as you’d access a list. The same goes for
slicing it.

1. >>> subjects[1]

‘Chemistry’

1. >>> subjects[0:2]

(‘Physics’, ‘Chemistry’)

2. A tuple is immutable– However, it is immutable. Once declared, you can’t change


its size or elements.

1. >>> subjects[2]='Biology'

Traceback (most recent call last):


File “<pyshell#107>”, line 1, in <module>
subjects[2]=’Biology’
TypeError: ‘tuple’ object does not support item assignment

1. >>> subjects[3]='Computer Science'

Traceback (most recent call last):


File “<pyshell#108>”, line 1, in <module>
subjects[3]=’Computer Science’
TypeError: ‘tuple’ object does not support item assignment

e. Dictionaries
A dictionary holds key-value pairs. Declare it in curly braces, with pairs separated by commas. Separate keys
and values by a colon(:).

1. >>> person={'city':'Ahmedabad','age':7}
2. >>> person

{‘city’: ‘Ahmedabad’, ‘age’: 7}


The type() function works with dictionaries too.

1. >>> type(person)

<class ‘dict’>

1. Accessing a value– To access a value, you mention the key in square brackets.

1. >>> person['city']

‘Ahmedabad’

2. Reassigning elements– You can reassign a value to a key.

1. >>> person['age']=21
2. >>> person['age']

21

3. List of keys– Use the keys() function to get a list of keys in the dictionary.

1. >>> person.keys()

dict_keys([‘city’, ‘age’])

f. bool
A Boolean value can be True or False.

1. >>> a=2>1
2. >>> type(a)

<class ‘bool’>

g. Sets
A set can have a list of values. Define it using curly braces.

1. >>> a={1,2,3}
2. >>> a

{1, 2, 3}

It returns only one instance of any value present more than once.

1. >>> a={1,2,2,3}
2. >>> a

{1, 2, 3}

However, a set is unordered, so it doesn’t support indexing.


1. >>> a[2]

Traceback (most recent call last):


File “<pyshell#127>”, line 1, in <module>
a[2]
TypeError: ‘set’ object does not support indexing

Also, it is mutable. You can change its elements or add more. Use the add() and remove() methods to do so.

1. >>> a={1,2,3,4}
2. >>> a

{1, 2, 3, 4}

1. >>> a.remove(4)
2. >>> a

{1, 2, 3}

1. >>> a.add(4)
2. >>> a

{1, 2, 3, 4}

4. Type Conversion

Since Python is dynamically-typed, you may want to convert a value into another type. Python supports a list of
functions for the same.

a. int()
It converts the value into an int.

1. >>> int(3.7)

3
Notice how it truncated 0.7 instead of rounding the number off to 4. You can also turn a Boolean into an int.

1. >>> int(True)

1. >>> int(False)

However, you cannot turn a string into an int. It throws an error.

1. >>> int("a")

Traceback (most recent call last):


File “<pyshell#135>”, line 1, in <module>;
int(“a”)
ValueError: invalid literal for int() with base 10: ‘a’
However, if the string has only numbers, then you can.

1. >>> int("77")

77

b. float()
It converts the value into a float.

1. >>> float(7)

7.0

1. >>> float(7.7)

7.7

1. >>> float(True)

1.0

1. >>> float("11")

You can also use ‘e’ to denote an exponential number.


11.0

1. >>> float("2.1e-2")

0.021

1. >>> float(2.1e-2)

0.021
However, this number works even without the float() function.

1. >>> 2.1e-2

0.021

c. str()
It converts the value into a string.

1. >>> str(2.1)

‘2.1’

1. >>> str(7)
‘7’

1. >>> str(True)

‘True’

You can also convert a list, a tuple, a set, or a dictionary into a string.

1. >>> str([1,2,3])

‘[1, 2, 3]’

d. bool()
It converts the value into a boolean.

1. >>> bool(3)

True

1. >>> bool(0)

False

1. >>> bool(True)

True

1. >>> bool(0.1)

True

You can convert a list into a Boolean.

1. >>> bool([1,2])

True

The function returns False for empty constructs.

1. >>> bool()

False

1. >>> bool([])

False

1. >>> bool({})

False
None is a keyword in Python that represents an absence of value.

1. >>> bool(None)

False

e. set()
It converts the value into a set.

1. >>> set([1,2,2,3])

{1, 2, 3}

1. >>> set({1,2,2,3})

{1, 2, 3}

f. list()
It converts the value into a list.

1. >>> del list


2. >>> list("123")

[‘1’, ‘2’, ‘3’]

1. >>> list({1,2,2,3})

[1, 2, 3]

1. >>> list({"a":1,"b":2})

[‘a’, ‘b’]

However, the following raises an error.

1. >>> list({a:1,b:2})

Traceback (most recent call last):


File “<pyshell#173>”, line 1, in <module>;
list({a:1,b:2})
TypeError: unhashable type: ‘set’

g. tuple()
It converts the value into a tuple.

1. >>> tuple({1,2,2,3})

(1, 2, 3)
You can try your own combinations. Also try composite functions.

1. >>> tuple(list(set([1,2])))

(1, 2)

5. Python Local and Python Global Variables

Another classification of python variables is based on scope.

a. Python Local variables


When you declare a variable in a function, class, or so, it is only visible in that scope. If you call it outside of
that scope, you get an ‘undefined’ error.

1. >>> def func1():


2. uvw=2
3. print(uvw)
4. >>> func1()

1. >>> uvw

Traceback (most recent call last):


File “<pyshell#76>”, line 1, in <module>
uvw
NameError: name ‘uvw’ is not defined[/php]

Here, the variable uvw is local to function func1().

b. Global variables
When you declare a variable outside any context/scope, it is visible in the whole program.

1. >>> xyz=3
2. >>> def func2():
3. xyz=0
4. xyz+=1
5. print(xyz)
6. >>> func2()

1. >>> xyz

3
You can use the ‘global’ keyword when you want to treat a variable as global in a local scope.
1. >>> foo=1
2. >>> def func2():
3. global foo
4. foo=3
5. print(foo)
6. >>> func2()

1. >>> foo

This was all about the Python Variables and Python data type tutorial

6. Python Variables and Python Data Types – Conclusion

In this tutorial on Python Variables and Python Data Types, we learnt about different python variables and data
types with examples. We looked at the naming rules, and defining and deleting them. Then we saw different
types of data- numbers, strings, lists, dictionaries, tuples, sets, and many more. We also learnt how to convert
one variable type into another and local and global variables in python. Don’t forget to try out your own
combinations.

If you have any queries the Python Variables and Python Data Type Tutorial, Please drop a comment.

Python Variable Scope – Local, Global, Built-in, Enclosed


by DataFlair Team · November 15, 2018

1. Objective

In our previous article on Python Namespace and Scope. Today, we will discuss Python Variable Scope. Here,
we will learn different types of variable scope in Python, Python Global Keyword and Python Non-local
keywords.

So, let’s start the Python Variable Scope.


Python Variable Scope – Introduction

2. What is Python Variable Scope?

The scope of a variable in python is that part of the code where it is visible. Actually, to refer to it, you don’t
need to use any prefixes then. Let’s take an example, but before let’s revise python Syntax.

1. >>> b=8
2. >>> def func():
3. a=7
4. print(a)
5. print(b)
6. >>> func()

7
8

1. >>> a

Traceback (most recent call last):

File “<pyshell#6>”, line 1, in <module>

NameError: name ‘a’ is not defined


Also, the duration for which a variable is alive is called its ‘lifetime’.

3. Types of Python Variable Scope

There are 4 types of Variable Scope in Python, let’s discuss them one by one:
Python Variable Scope – Types

a. Local Scope
In the above code, we define a variable ‘a’ in a function ‘func’. So, ‘a’ is local to ‘func’. Hence, we can
read/write it in func, but not outside it. When we try to do so, it raises a NameError.
Look at this code.

1. >>> a=0
2. >>> def func():
3. print(a)
4. a=1
5. print(a)
6. >>> func()

Traceback (most recent call last):

File “<pyshell#79>”, line 1, in <module>

func()

File “<pyshell#78>”, line 2, in func

print(a)

UnboundLocalError: local variable ‘a’ referenced before assignment


Here, we could’ve accessed the global Scope ‘a’ inside ‘func’, but since we also define a local ‘a’ in it, it no
longer accesses the global ‘a’. Then, the first print statement inside ‘func’ throws an error in Python, because
we’re trying to access the local scope ‘a’ before assigning it. However, it is bad practice to try to manipulate
global values from inside local scopes. Try to pass it as a parameter to the function.

1. >>> def func(a=0):


2. a+=1
3. print(a)
4. >>> func()

1
Let’s discuss Error and Exception Handling in Python.

b. Global Scope
We also declare a variable ‘b’ outside any other python Variable scope, this makes it global scope.
Consequently, we can read it anywhere in the program. Later in this article, we will see how to write it inside
func.

c. Enclosing Scope
Let’s take another example.

1. >>> def red():


2. a=1
3. def blue():
4. b=2
5. print(a)
6. print(b)
7. blue()
8. print(a)
9. >>> red()

1
2
1
In this code, ‘b’ has local scope in Python function ‘blue’, and ‘a’ has nonlocal scope in ‘blue’. Of course, a
python variable scope that isn’t global or local is nonlocal. This is also called enclosing scope.

d. Built-in Scope
Finally, we talk about the widest scope. The built-in scope has all the names that are loaded into python variable
scope when we start the interpreter. For example, we never need to import any module to access functions like
print() and id().
Now that we’ve discussed different types of python variable scopes, let’s see how to deal with them.

3. Global Keyword in Python

So far, we haven’t had any kind of a problem with global scope. So let’s take an example.

1. >>> a=1
2. >>> def counter():
3. a=2
4. print(a)
5. >>> counter()
2
Now, when we make a reference to ‘a’ outside this function, we get 1 instead of 2.

1. >>> a

1
Why does this happen? Well, this is because when we set ‘a’ to 2, it created a local variable ‘a’ in the local
scope of ‘counter’. This didn’t change anything for the global ‘a’. Now, what if you wanted to change the global
version of ‘a’? We use the ‘global’ keyword in python for this.

1. >>> a=1
2. >>> def counter():
3. global
a 4. a=2
5. print(a)
6. >>> counter()

1. >>> a

2
What we do here is, we declare that the ‘a’ we’re going to use in this function is from the global scope. After
this, whenever we make a reference to ‘a’ inside ‘counter’, the interpreter knows we’re talking about the global
‘a’. In this example, it changed the value of the global ‘a’ to 2.

4. Nonlocal Keyword

Like the ‘global’ keyword, you want to make a change to a nonlocal variable, you must use the ‘nonlocal’
keyword. Let’s first try this without the keyword.

1. >>> def red():


2. a=1
3. def blue():
4. a=2
5. b=2
6. print(a)
7. print(b)
8. blue()
9. print(a)
10. >>> red()

2
2
1
As you can see, this did not change the value of ‘a’ outside function ‘blue’. To be able to do that, we use
‘nonlocal’.

1. >>> def red():


2. a=1
3. def blue():
4. nonlocal a
5. a=2
6. b=2
7. print(a)
8. print(b)
9. blue()
10. print(a)
11. >>> red()

2
2
2
See? This works perfectly fine.

So, this was all about Python Variable Scope. Hope you like our explanation.

5. Conclusion

Hence, we hope that the Python variable scope is clearer to you. We saw four types of scope- local scope,
enclosed scope, global scope, and built-in scope. We also saw two keywords- ‘global’ and ‘nonlocal’. Hope you
had fun, see you again. Tell us in a comment box, is this information is worth or not.

Identifiers in Python – Naming Rules & Best Practices


by DataFlair Team · November 19, 2018

1. Objective
In our last Python tutorial, we discussed Python Subprocess Module. Today, in this Python tutorial, we will
learn about identifiers in Python and how to name them. Moreover, we will see the rules, best practices,
reserved classes in Python Identifiers. Also, we will test the validity of identifiers in Python.
So, let’s start Identifiers in Python.
Identifiers in Python – Naming Rules & Best Practices

2. Ways to Define Identifiers in Python


We can define identifiers in Python in a few ways:
“An identifier is a user-defined name to represent a variable, a function, a class, a module, or any other object.”
“It is a programmable entity in Python- one with a name.”
“It is a name given to the fundamental building blocks in a program.”
You must read about Python Tuples

3. Python Identifier Naming Rules

a. Rules in Identifiers in Python


So we know what a Python Identifier is. But can we name it anything? Or do certain rules apply? Well, we do
have five rules to follow when naming identifiers in Python:
a. A Python identifier can be a combination of lowercase/ uppercase letters, digits, or an underscore. The
following characters are valid:

 Lowercase letters (a to z)
 Uppercase letters (A to Z)
 Digits (0 to 9)
 Underscore (_)

Have a look at Python Number Types


Some valid names are:

 myVar
 var_3
 this_works_too

b. An identifier cannot begin with a digit.


Some valid names:

 _9lives
 lives9

An invalid name:

 9lives

Identifiers in Python – Naming Rules

c. We cannot use special symbols in the identifier name. Some of these are:
!
@
#
$
%
.

Identifiers in Python – Naming Rules in Python

d. We cannot use a keyword as an identifier. Keywords are reserved names in Python and using one of those as
a name for an identifier will result in a SyntaxError.

Identifiers in Python – Identifiers Naming Rules

Naming Rules in Python Identifiers

e. An identifier can be as long as you want. According to the docs, you can have an identifier of infinite length.
However, the PEP-8 standard sets a rule that you should limit all lines to a maximum of 79 characters.
Do you know about Python Variables
b. Lexical Definitions in Python Identifiers
To sum those rules up lexically, we can say:
identifier ::= (letter | “_”) (letter | digit | “_”)* #It has to begin with a letter or an underscore; letters, digits,
or/and underscores may follow
letter ::= lowercase | uppercase #Anything from a-z and from A-Z
lowercase ::= “a” … “z” #Lowercase letters a to z
uppercase ::= “A” … “Z” #Uppercase letters A to Z
digit ::= “0” … “9” #Integers 0 to 9

4. Best Practices in Identifiers in Python


While it’s mandatory to follow the rules, it is also good to follow some recommended practices:

 Begin class names with an uppercase letter, begin all other identifiers with a lowercase letter
 Begin private identifiers with an underscore (_); Note that this doesn’t make a variable private, but
discourages the user from attempting to access it
 Put around names of magic methods (use leading and trailing double underscores), avoid doing this
to anything else. Also, built-in types already use this notation.
 Use leading double underscores only when dealing with mangling.

Let’s discuss Python Iterator

 Prefer using names longer than one character- index=1 is better than i=1
 Use underscores to combine words in an identifier, like in this_is_an_identifier
 Since Python is case-sensitive, name and Name are two different identifiers.
 Use camel case for naming. Let’s just clear the air here by saying camel case is myVarOne and
Pascal case is MyVarOne.

5. Testing the Validity of Identifiers in Python


While it is great to follow the rules and guidelines, we can test an identifier’s validity just to be sure. For this,
we make use of the keyword.iskeyword() function.
Have a look at Python Network Programming
The keyword module lets us determine whether a string is a keyword. It has two functions:

 keyword.iskeyword(s)- If s is a Python keyword, return true


 Keyword.kwlist- Return a sequence holding all keywords the interpreter understands. This includes
even those that are active only when certain future statements are in effect.

Coming back to iskeyword(s), it returns True if the string s is a reserved keyword. Else, it returns False. Let’s
import this module.

1. >>> import keyword


2. >>> keyword.iskeyword('_$$_')

False

1. >>> keyword.iskeyword('return')
True
Also, the str.isidentifier() function will tell us if a string is a valid identifier. This is available since Python 3.0.

1. >>> ' $$ '.isidentifier()

False

1. >>> ' 99 '.isidentifier()

True

1. >>> '9lives'.isidentifier()

False

1. >>> '9.5okay'.isidentifier()

False
Let’s discuss Python Flask

6. Reserved Classes of Python Identifiers


Finally, let us talk about classes of identifiers. Some classes have special meanings and to identify them, we use
patterns of leading and trailing underscores:

a. Single Leading Underscore (_*)


We use this identifier to store the result of the last evaluation in the interactive interpreter. This result is stored
in the builtin module. Importing a module as from module import * does not import such private variables.

b. Leading and Trailing Double Underscores ( * )


These are system-defined names (by the interpreter). A class can implement operations to be invoked by
special syntax using methods with special names. Consider this an attempt at operator overloading in a Pythonic
fashion. One such special/ magic method is getitem (). Then, x[i] is equivalent to x. getitem (i). In the
near future, the set of names of this class by Python may be extended.
Have a look at Python SciPy Tutorial

c. Leading Double Underscores ( *)


These are class-private names. Within a class definition, the interpreter rewrites (mangles) such a name to avoid
name clashes between the private attributes of base and derived classes.
So, this was all in Identifiers in Python tutorial. Hope you like our explanation.

7. Conclusion – Identifiers in Python


Hence, in this Python Identifiers, we discussed the meaning of Identifiers in Python. Moreover, we learned
naming rules and best practices in Python Identifiers. Also, we discussed reserved classes in Python Identifier.
Still, if you have any doubt, ask in the comment tab.

Python String Tutorial – Python String Functions & Operations


by DataFlair Team · November 15, 2018

1. Python String Tutorial

In this Python String tutorial, we will discuss what is Python string and its examples. Moreover, we will learn how to
declare and slice a string in python and also look at the Python String functions and Python String operations. At last, we
cover escape sequences in Python. As we saw earlier, you don’t need to mention the data type when declaring a string.

So, let’s start the Python String Tutorial.

Python Strings Tutorial – Functions and Operations

2. What is Python String?

A Python string is a sequence of characters. There is a built-in class ‘str’ for handling Python string. You can
prove this with the type() function.

1. >>> type('Dogs are love')

<class ‘str’>

Python doesn’t have the char data-type like C++ or Java does.
3. How to Declare Python String?

You can declare a Python string using either single quotes or double quotes.

1. >>> a='Dogs are love'


2. >>> print(a)

Dogs are love

1. >>> a="Dogs are love"


2. >>> print(a)

Dogs are love

However, you cannot use a single quote to begin a string and a double quote to end it, and vice-versa.

1. >>> a='Dogs are love"

SyntaxError: EOL while scanning string literal

4. How to Use Quotes inside Python String?

Since we delimit strings using quotes, there are some things you need to take care of when using them inside a
string.

1. >>> a="Dogs are "love""

SyntaxError: invalid syntax

If you need to use double quotes inside a Python string, delimit the string with single quotes.

1. >>> a='Dogs are "love"'


2. >>> print(a)

Dogs are “love”

And if you need to use single quotes inside a string, delimit it with double quotes.

1. >>> a="Dogs are 'love'"


2. >>> print(a)

Dogs are ‘love’

You can use as many quotes as you want, then.

1. >>> a="'Dogs' 'are' 'love'"


2. >> print(a)

‘Dogs’ ‘are’ ‘love’

Also refer to section 9 for how to escape quotes.


Learn: Python Namespace and Variable Scope – Local and Global Variables

5. Spanning a String Across Lines

When you want to span a Python string across multiple lines, you can use triple quotes.

1. <pre data-enlighter-language="php" class="EnlighterJSRAW">>>> a="""Hello


2. Welcome"""
3. >>> print(a)</pre>

Hello
Welcome
It preserves newlines too, unlike using a backward slash for the same.

1. >>> a="Hello\
2. Welcome"
3. >>> print(a)

Hello Welcome

6. How to Access Python String?

A string is immutable; it can’t be changed.

1. >>> a="Dogs"
2. >>> a[0]="H"

Traceback (most recent call last):

File “<pyshell#22>”, line 1, in <module>

a[0]=”H”

TypeError: ‘str’ object does not support item assignment

But you can access a string.

1. >>> a="Dogs are love"


2. >>> a

‘Dogs are love’

1. >>> print(a)

Dogs are love

i. Displaying a single character


To display a single character from a string, put its index in square brackets. Indexing
begins at 0.
1. >>> a[1]

‘o’

b. Slicing a string
Sometimes, you may want to display only a part of a string. For this, use the slicing
operator [].

1. >>> a[3:8]

‘s are’

Here, it printed characters 3 to 7, with the indexing beginning at 0.

1. >>> a[:8]

‘Dogs are’

This prints characters from the beginning to character 7.

1. >>> a[8:]

‘ love’

This prints characters from character 8 to the end of the string.

1. >>> a[:]

‘Dogs are love’

This prints the whole string.

1. >>> a[:-2]

‘Dogs are lo’

This prints characters from the beginning to two characters less than the end of the string.

1. >>> a[-2:]

‘ve’

This prints characters from two characters from the end to the end of the string.

1. >>> a[-3:-2]

‘o’

This prints characters from three characters from the string’s end to two characters from it.
The following codes return empty strings.

1. >>> a[-2:-2]

1. >>> a[2:2]

7. Python String Concatenation

Concatenation is the operation of joining stuff together. Python Strings can join using the concatenation
operator +.

1. >>> a='Do you see this, '


2. >>> b='$$?'
3. >>> a+b

‘Do you see this, $$?’

Let’s take another example.

1. >>> a='10'
2. >>> print(2*a)

1010

Multiplying ‘a’ by 2 returned 1010, and not 20, because ‘10’ is a string, not a number. You cannot concatenate a
string to a number.

1. >>> '10'+10

Traceback (most recent call last):

File “<pyshell#49>”, line 1, in <module>

’10’+10

TypeError: must be str, not int

8. Python String Formatters

Sometimes, you may want to print variables along with a string. You can either use commas, or use string
formatters for the same.

1. >>> city='Ahmedabad'
2. >>> print("Age",21,"City",city)

Age 21 City Ahmedabad


i. f-strings
The letter ‘f’ precedes the string, and the variables are mentioned in curly braces in their
places.

1. >>> name='Ayushi'
2. >>> print(f"It isn't {name}'s birthday")

It isn’t Ayushi’s birthday

Notice that because we wanted to use two single quotes in the string, we delimited the entire string with double
quotes instead.

ii. format() method


You can use the format() method to do the same. It succeeds the string, and has the
variables as arguments separated by commas. In the string, use curly braces to posit
the variables. Inside the curly braces, you can either put 0,1,.. or the variables. When
doing the latter, you must assign values to them in the format method.

1. >>> print("I love {0}".format(a))

I love dogs

1. >>> print("I love {a}".format(a='cats'))

I love cats

The variables don’t have to defined before the print statement.

1. >>> print("I love {b}".format(b='ferrets'))

I love ferrets

c. % operator
The % operator goes where the variables go in a string. %s is for string. What follows the
string is the operator and variables in parentheses/in a tuple.

1. >>> b='ferrets'
2. >>> print("I love %s and %s" %(a,b))

I love dogs and cats

Other options include:

%d – for integers

%f – for floating-point numbers


9. Escape Sequences in Python

In a Python string, you may want to put a tab, a linefeed, or other such things. Escape sequences allow us to do
this. An escape sequence is a backslash followed by a character, depending on what you want to do. Python
supports the following sequences.

 \n – linefeed
 \t – tab

1. >>> print("hell\to")

hell o

 \\ – backslash

Since a backslash may be a part of an escape sequence, so, a backslash must be escaped by a backslash too.

 \’ – A single quote can be escaped by a backslash. This lets you use single quotes freely in a string.
 \” – Like the single quote, the double quote can be escaped too.

Any Doubt yet in Python String and Python String Operations and Functions? Please Comment.

10. Python String Functions

Python provides us with a number of functions that we can apply on strings or to create strings.

a. len()
The len() function returns the length of a string.

1. >>> a='book'
2. >>> len(a)

You can also use it to find how long a slice of the string is.

1. >>> len(a[2:])

b. str()
This function converts any data type into a string.

1. >>> str(2+3j)

‘(2+3j)’

1. >>> str(['red','green','blue'])
“[‘red’, ‘green’, ‘blue’]”

c. lower() and upper()


These methods return the string in lowercase and uppercase, respectively.

1. >>> a='Book'
2. >>> a.lower()

‘book’

1. >>> a.upper()

‘BOOK’

d. strip()
It removes whitespaces from the beginning and end of the string.

1. >>> a=' Book '


2. >>> a.strip()

‘Book’

e. isdigit()
Returns True if all characters in a string are digits.

1. >>> a='777'
2. >> a.isdigit()

True

1. >>> a='77a'
2. >>> a.isdigit()

False

f. isalpha()
Returns True if all characters in a string are characters from an alphabet.

1. >>> a='abc'
2. >>> a.isalpha()

True

1. >>> a='ab7'
2. >>> a.isalpha()
False

g. isspace()
Returns True if all characters in a string are spaces.

1. >>> a=' '


2. >>> a.isspace()

True

1. >>> a=' \' '


2. >>> a.isspace()

False

h. startswith()
It takes a string as an argument, and returns True is the string it is applied on begins
with the string in the argument.

1. >>> a.startswith('un')

True

i. endswith()
It takes a string as an argument, and returns True if the string it is applied on ends with
the string in the argument.

1. >>> a='therefore'
2. >>> a.endswith('fore')

True

j. find()
It takes an argument and searches for it in the string on which it is applied. It then
returns the index of the substring.

1. >>> 'homeowner'.find('meow')

If the string doesn’t exist in the main string, then the index it returns is 1.

1. >>> 'homeowner'.find('wow')
-1
k. replace()
It takes two arguments. The first is the substring to be replaced. The second is the
substring to replace with.

1. >>> 'banana'.replace('na','ha')

‘bahaha’

l. split()
It takes one argument. The string is then split around every occurrence of the argument
in the string.

1. >>> 'No. Okay. Why?'.split('.')

[‘No’, ‘ Okay’, ‘ Why?’]

m. join()
It takes a list as an argument and joins the elements in the list using the string it is
applied on.

1. >>> "*".join(['red','green','blue'])

‘red*green*blue’

11. Python String Operations

Python String Operations

a. Comparison
Python Strings can compare using the relational operators.
1. >>> 'hey'<'hi'

True

‘hey’ is lesser than ‘hi lexicographically (because i comes after e in the dictionary)

1. >>> a='check'
2. >>> a=='check'

True

1. >>> 'yes'!='no'

True

b. Arithmetic
Some arithmetic operations can be applied on strings.

1. >>> 'ba'+'na'*2

‘banana’

c. Membership
The membership operators of Python can be used to check if string is a substring to another.

1. >>> 'na' in 'banana'

True

1. >>> 'less' not in 'helpless'

False

d. Identity
Python’s identity operators ‘is’ and ‘is not’ can be used on strings.

1. >>> 'Hey' is 'Hi'

False

1. >>> 'Yo' is not 'yo'

True

e. Logical
Python’s and, or, and not operators can be applied too. An empty string has a Boolean value of False.
1. and- If the value on the left is True it returns the value on the right. Otherwise, the
value on the left is False, it returns False.

1. >>> '' and '1'

1. >>> '1' and ''


2. or- If the value on the left is True, it returns True. Otherwise, the value on the right
is returned.

3. not- As we said earlier, an empty string has a Boolean value of False.

1. >>> not('1')

False

1. >>> not('')

True

This was all about the tutorial on Python strings. Hope you like the Python strings tutorial.

12. Python String – Conclusion

In this Python String tutorial, we learned about python string with string functions and Operators , and how to
declare and access them. Then we learned about python string concatenation and formatters in python. We also
learned about Python string functions. Lastly, we looked at operations that we can perform on strings. Hope you
enjoyed today’s lesson. Leave your feedback in the comments if any query on Python strings.

What is Python Interpreter – Environment, Invoking & Working


by DataFlair Team · May 17, 2019

1. Python Interpreter Tutorial – Objective


In our previous tutorial, we studied Python Matplotlib Tutorial. In this Python Interpreter tutorial, we will see
how to work with the Python interpreter. Moreover, we will discuss the environment and features of Interpreter
of Python Programming Langauge.
So, let’s start the Python Interpreter Tutorial.
What is Python Interpreter – Environment, Invoking & Working

2. Python Interpreter & its Environment (Source Code Encoding)

The default encoding for a Python source file is UTF-8. This is a Unicode Standard variable-width character
encoding; it can encode 1,112,064 valid code points in Unicode using up to four 8-bit bytes. Using this
encoding, we can use characters of most languages – we can use these in string literals, comments, and
identifiers. Since the standard library makes use of ASCII characters only, you must declare the use of this
encoding to your editor. This is to ensure that all such characters display without a problem. The font should be
such that supports all characters in the file.
We add this comment as the first line of the file we want to use it in-

1. # -*- coding: encoding -*-

In this, encoding is a valid codec that Python supports. Similarly, when you want to use the Windows-1252
encoding, you can use this as the first line of code:

1. # -*- coding: cp1252 -*-

However, when you want to begin code with a UNIX shebang line, you can put the comment for encoding
second-

1. #!/usr/bin/env python3
2. # -*- coding: cp1252 -*-

Do you know about Python Iterables and Python Itertools

3. How to Invoke the Python Interpreter?


On your machine, you can find your interpreter at an address like:
C:\Python36
Or it may reside on the location you selected at the time of installation. Add path using this command:
1. set path=%path%;C:\python36

How to Invoke the Python Interpreter?

a. Start the Python Interpreter


On Windows, when you want to run the Python interpreter in the shell, you can type the following:

1. $python

To get out of the interpreter in disassembling the Bytecode shell, you can type:

1. >>> quit()

Bye
Let’s Discuss Python Multiple Inheritance – Python MRO (Method Resolution Order)
Alternately, you can use an end-of-file character at the prompt. Python interpreter exits with a zero exit status.
You can use it in a REPL (Read-Evaluate-Print-Loop) fashion. But if you want, you can save your Python code
as a script and execute it using the interpreter:

1. $python demo.py

To enter interactive mode after running a script, you can pass –i before the script.
The command python -c command [arg] … executes statements in command, and python -m module [arg] …
executes the source file for module.

b. Features of Python Interpreter


Python interpreter offers some pretty cool features:

 Interactive editing
 History substitution
 Code completion on systems with support for readline

In the first Python prompt, try pressing the following keys:


Ctrl+P
This tells you if your interpreter supports command-line editing. A beep indicates that it does support
command-line editing. Otherwise, it will either perform a no-operation or echo ^p to indicate it isn’t available.

c. Passing Arguments
When you pass a script name and additional arguments to the shell when invoking the Python interpreter, it
turns these into a list of strings. Then, it assigns these to the variable argv in the sys module. The following
command will give us a list of this-

1. import sys

Without a script or arguments, sys.argv[0] denotes an empty string. A script name of ‘-‘ means that it sets
sys.argv[0] to ‘-‘, and with ‘-c’, it is set to ‘-c’. A value of ’-m’ sets sys.argv[0] to the module’s full name. The
command/ module handles the options after ‘-c’ or ‘-m’.
Do you know about Python Collections Module?

d. Interactive Mode
Python interpreter is in an interactive mode when it reads commands from a tty. The primary prompt is the
following:

1. >>>

When it shows this prompt, it means it prompts the developer for the next command. This is the REPL. Before
it prints the first prompt, Python interpreter prints a welcome message that also states its version number and a
copyright notice.
This is the secondary prompt:

1. …

This prompt denotes continuation lines.

1. $ python3.7
2. Python 3.7 (default, Jul 16 2018, 04:38:07)
3. [GCC 4.8.2] on Windows
4. Type "help", "copyright", "credits" or "license" for more
information. 5. >>>

You will find continuation lines when working with a multi-line construct:

1. >>> it_rains =True


2. >>> if it_rains:
3. print("The produce will be good")

The produce will be good


You can also use the Python interpreter as a calculator:
1. >>> 2*7
2. 14
3. >>> 4/2
4. 2.0

4. How Does Python Interpreter Works?

Well, internally, four things happen in a REPL:


i. Lexing- The lexer breaks the line of code into tokens.
ii. Parsing- The parser uses these tokens to generate a structure, here, an Abstract Syntax Tree, to depict the
relationship between these tokens.
iii. Compiling- The compiler turns this AST into code object(s).
iv. Interpreting- The interpreter executes each code object.
Have a look at Python Operators with Syntax and Examples

How Does Python Interpreter Works?

a. Function Objects & Code Objects


When we talk of function objects, we mean to say that in Python, functions are first-class objects (functions
indeed are objects). You can pass them around and talk about them without making a call to them.

1. >>> def bar(a):


2. x=3
3. return x+a
4. >>> bar

<function bar at 0x107ef7aa2>

Now bar. code returns a code object:


1. >>> bar. code
2. <code object bar at 0x107eeccb2, file "<stdin>", line 1>

So, we conclude that a code object is an attribute of a function object. The dir() function will tell us more about
the function:

1. >>> dir(bar. code )

[‘ class ’, ‘ cmp ’, ‘ delattr ’, ‘ doc__’, ‘ eq ’, ‘ format ’, ‘ ge ’,


‘ getattribute ’, ‘ gt ’, ‘ hash ’, ‘ init ’, ‘ le ’, ‘ lt ’, ‘ ne ’, ‘ new ’,
‘ reduce ’, ‘ reduce_ex ’, ‘ repr ’, ‘ setattr ’, ‘ sizeof ’, ‘ str ’,
‘ subclasshook ’, ‘co_argcount’, ‘co_cellvars’, ‘co_code’, ‘co_consts’, ‘co_filename’,
‘co_firstlineno’, ‘co_flags’, ‘co_freevars’, ‘co_lnotab’, ‘co_name’, ‘co_names’, ‘co_nlocals’,
‘co_stacksize’, ‘co_varnames’]
Let’s revise Recursion in Python with Examples
This gives us the attributes of the code object. Values of some more attributes:

1. >>> bar. code .co_varnames

(‘a’, ’x’)

1. >>> bar. code .co_consts

(None, 3)

1. >>> bar. code .co_argcount

b. The Bytecode
The following command gives us the bytecode:

1. >>> bar. code .co_code

‘d\x01\x00}\x01\x00|\x01\x00|\x00\x00\x17S’

This is a series of bytes, each of which the interpreter loops through and then makes an execution.

c. Disassembling the Bytecode


We will use the dis() method from the dis module to understand what’s going on- this isn’t part of what the
interpreter does.

1. >>>import dis
2. >>> dis.dis(bar. code__)

2 0 LOAD_CONST 1 (3)
3 STORE_FAST 1 (x)
3 6 LOAD_FAST 1 (x)
9 LOAD_FAST 0 (a)
12BINARY_ADD
13RETURN_VALUE
In this, the first set of numbers is the line numbers in the actual code. The second one depicts offsets of the
bytecode. Then comes the set of names for the bytes- for human readability. The next column depicts the
arguments and the last column lists the constants and names in the fourth column.

1. >>> bar. code .co_consts[1]

1. >>> bar. code .co_varnames[1]

‘x’
So, this was all about Python Interpreter Tutorial. Hope you like our explanation.

5. Conclusion

Hence, we can say the compiler for Python generates bytecode for the interpreter. The Python interpreter uses
this with the virtual machine. The same bytecode doesn’t always end up doing the same things. This is another
thing that makes Python dynamic. Also, the default prompt for the interpreter is >>>. If we miss anything, feel
free to share with us in a comment section.

Python Operator – Types of Operators in Python


by DataFlair Team · September 24, 2019

Python Operator – Objective

In this Python Operator tutorial, we will discuss what is an operator in Python Programming Language. On the
other hand, we will learn different types of Python Operators: Arithmetic, Relational, Assignment, Logical,
Membership, Identity, and Bitwise Operators with their syntax and examples.

Python operator is a symbol that performs an operation on one or more operands. An operand is a variable or a
value on which we perform the operation.

Before starting with operators in python, let us revise the basics of Python.

So, let’s start the Python Operator Tutorial.


Python Operator – Types of Operators in Python

Introduction to Python Operator


Python Operator falls into 7 categories:

 Python Arithmetic Operator


 Python Relational Operator
 Python Assignment Operator
 Python Logical Operator
 Python Membership Operator
 Python Identity Operator
 Python Bitwise Operator

It is recommended to check the Python master guide before we start with the operator in Python.

Python Arithmetic Operator

These Python arithmetic operators include Python operators for basic mathematical operations.
Arithmetic Operators in Python

a. Addition(+)

Adds the values on either side of the operator.

1. >>> 3+4

Output: 7

b. Subtraction(-)

Subtracts the value on the right from the one on the left.

1. >>> 3-4

Output: -1

c. Multiplication(*)

Multiplies the values on either side of the operator.

1. >>> 3*4

Output: 12

d. Division(/)

Divides the value on the left by the one on the right. Notice that division results in a floating-point value.

1. >>> 3/4
Output: 0.75

e. Exponentiation(**)

Raises the first number to the power of the second.

1. >>> 3**4

Output: 81

f. Floor Division(//)

Divides and returns the integer value of the quotient. It dumps the digits after the decimal.

1. >>> 3//4
2. >>> 4//3

Output: 1

1. >>> 10//3

Output: 3

g. Modulus(%)

Divides and returns the value of the remainder.

1. >>> 3%4

Output: 3

1. >>> 4%3

Output: 1

1. >>> 10%3

Output: 1

1. >>> 10.5%3

Output: 1.5

If you face any query in Python Operator with examples, ask us in the comment.

Python Relational Operator

Let’s see Python Relational Operator.


Relational Operators in Python

Relational Python Operator carries out the comparison between operands. They tell us whether an operand is
greater than the other, lesser, equal, or a combination of those.

a. Less than(<)

This operator checks if the value on the left of the operator is lesser than the one on the right.

1. >>> 3<4

Output: True

b. Greater than(>)

It checks if the value on the left of the operator is greater than the one on the right.

1. >>> 3>4

Output: False

c. Less than or equal to(<=)

It checks if the value on the left of the operator is lesser than or equal to the one on the right.

1. >>> 7<=7

Output: True

d. Greater than or equal to(>=)

It checks if the value on the left of the operator is greater than or equal to the one on the right.
1. >>> 0>=0

Output: True

e. Equal to(= =)

This operator checks if the value on the left of the operator is equal to the one on the right. 1 is equal to the
Boolean value True, but 2 isn’t. Also, 0 is equal to False.

1. >>> 3==3.0

Output: True

1. >>> 1==True

Output: True

1. >>> 7==True

Output: False

1. >>> 0==False

Output: True

1. >>> 0.5==True

Output: False

f. Not equal to(!=)

It checks if the value on the left of the operator is not equal to the one on the right. The Python operator <> does
the same job, but has been abandoned in Python 3.

When the condition for a relative operator is fulfilled, it returns True. Otherwise, it returns False. You can use
this return value in a further statement or expression.

1. >>> 1!=-1.0

Output: False

1. >>> -1<>-1.0

#This causes a syntax error

Python Assignment Operator


Assignment Operators in Python

Assignment Python Operator explained –

An assignment operator assigns a value to a variable. It may manipulate the value by a factor before assigning
it. We have 8 assignment operators- one plain, and seven for the 7 arithmetic python operators.

a. Assign(=)

Assigns a value to the expression on the left. Notice that = = is used for comparing, but = is used for assigning.

1. >>> a=7
2. >>> print(a)

Output: 7

b. Add and Assign(+=)

Adds the values on either side and assigns it to the expression on the left. a+=10 is the same as a=a+10.

The same goes for all the next assignment operators.

1. >>> a+=2
2. >>> print(a)

Output: 9

c. Subtract and Assign(-=)

Subtracts the value on the right from the value on the left. Then it assigns it to the expression on the left.

1. >>> a-=2
2. >>> print(a)

Output: 7

d. Divide and Assign(/=)

Divides the value on the left by the one on the right. Then it assigns it to the expression on the left.

1. >>> a/=7
2. >>> print(a)

Output: 1.0

e. Multiply and Assign(*=)

Multiplies the values on either sides. Then it assigns it to the expression on the left.

1. >>> a*=8
2. >>> print(a)

Output: 8.0

f. Modulus and Assign(%=)

Performs modulus on the values on either side. Then it assigns it to the expression on the left.

1. >>> a%=3
2. >>> print(a)

Output: 2.0

g. Exponent and Assign(**=)

Performs exponentiation on the values on either side. Then assigns it to the expression on the left.

1. >>> a**=5
2. >>> print(a)

Output: 32.0

h. Floor-Divide and Assign(//=)

Performs floor-division on the values on either side. Then assigns it to the expression on the left.

1. >>> a//=3
2. >>> print(a)

Output: 10.0

This is one of the important Python Operator.


Python Logical Operator

These are conjunctions that you can use to combine more than one condition. We have three Python logical
operator – and, or, and not that come under python operators.

Logical Operators in Python

a. and

If the conditions on both the sides of the operator are true, then the expression as a whole is true.

1. >>> a=7>7 and 2>-1


2. >>> print(a)

Output: False

b. or

The expression is false only if both the statements around the operator are false. Otherwise, it is true.

1. >>> a=7>7 or 2>-1


2. >>> print(a)

Output: True

‘and’ returns the first False value or the last value; ‘or’ returns the first True value or the last value

1. >>> 7 and 0 or 5

Output: 5

c. not
This inverts the Boolean value of an expression. It converts True to False, and False to True. As you can see
below, the Boolean value for 0 is False. So, not inverts it to True.

1. >>> a=not(0)
2. >>> print(a)

Output: True

Membership Python Operator

These operators test whether a value is a member of a sequence. The sequence may be a list, a string, or a
tuple. We have two membership python operators- ‘in’ and ‘not in’.

a. in

This checks if a value is a member of a sequence. In our example, we see that the string ‘fox’ does not belong to
the list pets. But the string ‘cat’ belongs to it, so it returns True. Also, the string ‘me’ is a substring to the string
‘disappointment’. Therefore, it returns true.

1. >>> pets=[‘dog’,’cat’,’ferret’]
2. >>> ‘fox’ in pets

Output: False

1. >>> ‘cat’ in pets

Output: True

1. >>> ‘me’ in ‘disappointment’

Output: True

b. not in

Unlike ‘in’, ‘not in’ checks if a value is not a member of a sequence.

1. >>> ‘pot’ not in ‘disappointment’

Output: True

In doubt yet in any Python operator with examples? Please comment.

Don’t you know about the trending Python Project at DataFlair? Here it is – Gender and Age Detection
with Python

Python Identity Operator


Let us proceed towards identity Python Operator.

These operators test if the two operands share an identity. We have two identity operators- ‘is’ and ‘is not’.
a. is

If two operands have the same identity, it returns True. Otherwise, it returns False. Here, 2 is not the same as
20, so it returns False. Also, ‘2’ and “2” are the same. The difference in quotes does not make them different.
So, it returns True.

1. >>> 2 is 20

Output: False

1. >>> ‘2’ is “2”

Output: True

b. is not

2 is a number, and ‘2’ is a string. So, it returns a True to that.

1. >>> 2 is not ‘2’

Output: True

Python Bitwise Operator


Let us now look at Bitwise Python Operator.

Bitwise Operators in Python

On the operands, these operate bit by bit.

a. Binary AND(&)

It performs bit by bit AND operation on the two values. Here, binary for 2 is 10, and that for 3 is 11. &-ing
them results in 10, which is binary for 2. Similarly, &-ing 011(3) and 100(4) results in 000(0).
1. >>> 2&3

Output: 2

1. >>> 3&4

Output: 0

b. Binary OR(|)

It performs bit by bit OR on the two values. Here, OR-ing 10(2) and 11(3) results in 11(3).

1. >>> 2|3

Output: 3

c. Binary XOR(^)

It performs bit by bit XOR(exclusive-OR) on the two values. Here, XOR-ing 10(2) and 11(3) results in 01(1).

1. >>> 2^3

Output: 1

d. Binary One’s Complement(~)

It returns the one’s complement of a number’s binary. It flips the bits. Binary for 2 is 00000010. Its one’s
complement is 11111101. This is binary for -3. So, this results in -3. Similarly, ~1 results in -2.

1. >>>~-3

Output: 2

Again, one’s complement of -3 is 2.

e. Binary Left-Shift(<<)

It shifts the value of the left operand the number of places to the left that the right operand specifies. Here,
binary of 2 is 10. 2<<2 shifts it two places to the left. This results in 1000, which is binary for 8.

1. >>> 2<<2

Output: 8

f. Binary Right-Shift(>>)

It shifts the value of the left operand the number of places to the right that the right operand specifies. Here,
binary of 3 is 11. 3>>2 shifts it two places to the right. This results in 00, which is binary for 0. Similarly, 3>>1
shifts it one place to the right. This results in 01, which is binary for 1.

1. >>> 3>>2
2. >>> 3>>1

Output: 1

This was all about the Python Operator Tutorial.

Conclusion – Python Operator

Finally, in this lesson, we looked at seven different classes of Python operator. We executed them in the Python
Shell(IDLE) to find out how they work. We can further use this operator in conditions, and to combine them.
Go ahead and practice some combinations.
Hope you like the Python Operator tutorial by DataFlair. If you have any queries on Python operator, please
leave a comment.

Python Bitwise Operators with Syntax and Example


by DataFlair Team · February 27, 2019

1. Python Bitwise Operators

Previously, in our tutorial on Python Operators., Today, in this Python Bitwise Operators Tutorial, we will
discuss Python Bitwise AND, OR, XOR, Left-shift, Right-shift, and 1’s complement Bitwise Operators in
Python Programming. Along with this, we will discuss syntax and example of Python Bitwise Operators.

So, let’s start the Python Bitwise Operators Tutorial.

Python Bitwise Operators with Syntax and Example

Learn: Python Functions with Syntax and Examples

2. Introduction to Python Bitwise Operators


Python Bitwise Operators take one to two operands, and operates on it/them bit by bit, instead of whole. To take
an example, let’s see the ‘and’ and ‘&’ operators for the same thing.

Let’s take two numbers- 5 and 7. We’ll show you their binary equivalents using the function bin().

1. >>> bin(5)

‘0b101’

1. >>> bin(7)

‘0b111’

Now let’s try applying ‘and’ and ‘&’ to 5 and 7.

1. >>> 5 and 7

1. >>> 5&7

You would have expected them to return the same thing, but they’re not the same. One acts on the whole value,
and one acts on each bit at once.

Actually, ‘and’ sees the value on the left. If it has a True Boolean value, it returns whatever value is on the right.
Otherwise, it returns False. So, here, 5 and 7 is the same as True and 7. Hence, it returns 7. However, 5&7 is the
same as 101&111. This results in 101, which is binary for 5. Let’s look at each of these operators bit by bit (pun
intended).

Learn: Loops in Python with Syntax and Examples

Let’s move ahead with next Python Bitwise Operator

3. Python Bitwise AND (&) Operator

1 has a Boolean value of True, and 0 has that of False. Take a look at the following code.

1. >>> True/2

0.5

1. >>> False*2

This proves something. Now, the binary and (&) takes two values and performs an AND-ing on each pair of
bits. Let’s take an example.

1. >>> 4 & 8
Binary for 4 is 0100, and that for 8 is 1000. So when we AND the corresponding bits, it gives us 0000, which is
binary for 0. Hence, the output.

The following are the values when &-ing 0 and 1.

Table.1 Python Bitwise Operators – AND Operators

0&0 0
0&1 0
1&0 0
1&1 1

As you can see, an &-ing returns 1 only if both bits are 1.

You cannot, however, & strings.

1. >>> '$'&'%'

Traceback (most recent call last):

File “<pyshell#30>”, line 1, in <module>

‘$’&’%’

TypeError: unsupported operand type(s) for &: ‘str’ and ‘str’

Since Boolean values True and False have equivalent integer values of 1 and 0, we can & them.

1. >>> False&True

False

1. >>> True&True

True

Let’s try a few more combinations.

1. >>> 1&True

1. >>> 1.0&1.0

Traceback (most recent call last):

File “<pyshell#36>”, line 1, in <module>

1.0&1.0

TypeError: unsupported operand type(s) for &: ‘float’ and ‘float’


You can also type your numbers directly in binary, as we discussed in section 6a in our Python Numbers
tutorial.

1. >>> 0b110 & 0b101

Here, 110 is binary for 6, and 101 for 5. &-ing them, we get 100, which is binary for 4.

4. Python Bitwise OR (|) Operators

Now lets discuss Python Bitwise OR (|) Operator

Compared to &, this one returns 1 even if one of the two corresponding bits from the two operands is 1.

Table.2 Python Bitwise Operators – OR Operators

0|0 0
0|1 1
1|0 1
1|1 1

1. >>> 6|1

This is the same as the following.

1. >>> 0b110|0b001

Let’s see some more examples.

1. >>> True|False

True

Lets move to another Python Bitwise Operator

5. Python Bitwise XOR (^) Operator

XOR (eXclusive OR) returns 1 if one operand is 0 and another is 1. Otherwise, it returns 0.

Table.1 Python Bitwise Operators – XOR Operators

0^0 0
0^1 1
1^0 1
1^1 0
Let’s take a few examples.

1. >>> 6^6

Here, this is the same as 0b110^0b110. This results in 0b000, which is binary for 0.

1. >>> 6^0

This is equivalent to 0b110^0b000, which gives us 0b110. This is binary for 6.

1. >>> 6^3

Here, 0b110^0b011 gives us 0b101, which is binary for 5.

Now lets discuss Bitwise 1’s Complement (~)

6. Bitwise 1’s Complement (~)


This one is a bit different from what we’ve studied so far. This operator takes a number’s binary, and returns its
one’s complement. For this, it flips the bits until it reaches the first 0 from right. ~x is the same as -x-1.

1. >>> ~2

-3

1. >>> bin(2)

‘0b10’

1. >>> bin(-3)

‘-0b11’

To make it clear, we mention the binary values of both. Another example follows.

1. >>> ~45

-46

1. >>> bin(45)

‘0b101101’

1. >>> bin(-46)

‘-0b101110’
7. Python Bitwise Left-Shift Operator (<<)

Finally, we arrive at left-shift and right-shift operators. The left-shift operator shifts the bits of the number by
the specified number of places. This means it adds 0s to the empty least-significant places now. Let’s begin with
an unusual example.

1. >>> True<<2

Here, True has an equivalent integer value of 1. If we shift it by two places to the left, we get 100. This is binary
for 4.

Now let’s do it on integers.

1. >>> 2<<1

10 shifted by one place to the left gives us 100, which is, again, 4.

1. >>> 3<<2

12

Now, 11 shifted to the left by two places gives us 1100, which is binary for 12.

Now lets move to Next Python Bitwise Operator

8. Python Bitwise Right-Shift Operator (>>)


Now we’ll see the same thing for right-shift. It shifts the bits to the right by the specified number of places. This
means that those many bits are lost now.

1. >>> 3>>1

3 has a binary value of 11, which shifted one place to the right returns 1. But before closing on this tutorial,
we’ll take one last example.

Let’s check what’s the decimal value for 11111.

1. >>> int(0b11111)

31

Now, let’s shift it three places to the right.

1. >>> 31>>3
3

As you can see, it gives us 3, whose binary is 11. Makes sense, doesn’t it?

This was all about the Python Bitwise Operators.

9. Conclusion

While they’re not so common in real-world programming, Python Bitwise Operators do find their use in places
like encryption, compression, and byte manipulation. If you have any doubts regarding Python Bitwise
Operators, leave them in the comments.
Hope you like the Python Bitwise Operators.

Python Comparison Operators with Syntax and Examples


by DataFlair Team · November 21, 2018

1. Python Comparison Operators

In our previous article, we talked about Python bitwise operators. Today, we focus our words on Python
Comparison Operators. These are also called relational operators in Python. Along with this, we will learn
different types of Comparison Operators in Python: less than, greater than, less than, greater than, equal to, and
not equal to with their syntax and examples.

So, let’s start the Python Comparison Operators Tutorial.

Python Comparison Operators with Syntax and Examples

2. Python Comparison Operators


A comparison operator in python, also called python relational operator, compares the values of two operands
and returns True or False based on whether the condition is met. We have six of these, including and limited to-
less than, greater than, less than or equal to, greater than or equal to, equal to, and not equal to. So, let’s begin
with the Python Comparison operators.

3. Python Less Than (<) Operator

The first comparison operator in python we’ll see here is the less than operator. Denoted by <, it checks if the
left value is lesser than that on the right.

1. >>> 3<6

Output: True

Since 3 is lesser than 6, it returns True.

1. >>> 3<3

Output: False

Because 3 is equal to 3, and not less than it, this returns False.

But let’s see if we can apply it to values other than ints.

1. >>> 3<3.0

Output: False

Here, 3 is an int, and 3.0 is a float, but 3 isn’t lesser than 3.0, or vice versa.

1. >>> 3.0<3

Output: False

Now, let’s try it on strings.

1. >>> 'Ayushi'<'ayushi'

Output: True

This one results in True because when comparing strings, their ASCII values are compared. The ASCII value
for ‘A’ is 65, but that for ‘a’ is 97. Hence, ‘A’ is lesser than ‘a’. Likewise, ‘Ayushi’ is lesser than ‘ayushi’.

But does it work with Python Booleans?

1. >>> 0.9999999<True

Output: True

Yes, it does. But what’s fascinating is that it works on containers like tuples as well. Let’s see some of these.
1. >>> (1,2,3)<(1,2,3,4)

Output: True

1. >>> (1,3,2)<(1,2,3)

Output: False

1. >>> (1,2,3)<(1,3,2)

Output: True

1. >>> ()<(0,)

Output: True

But you can’t compare tuples with different kinds of values.

1. >>> (1,2)<('One','Two')

Traceback (most recent call last):

File “<pyshell#84>”, line 1, in <module>

(1,2)<(‘One’,’Two’)

TypeError: ‘<‘ not supported between instances of ‘int’ and ‘str’

However, if you get comparable elements at the same indices, it is possible to compare two tuples.

Must Check – Python Tuples vs Lists

1. >>> (1,'one')<(2,'two')

Output: True

And when we say same indices, we mean it.

1. >>> (1,'one')<('two',2)

Traceback (most recent call last):

File “<pyshell#86>”, line 1, in <module>

(1,’one’)<(‘two’,2)

TypeError: ‘<‘ not supported between instances of ‘int’ and ‘str’

Finally, these work on lists, and set, but not dictionaries.

1. >>> [0]<[False]
Output: False

1. >>> {1,2,3}<{1,3,2}

Output: False

Here, because the other set rearranges itself to {1,2,3}, the two sets are equal. Consequently, it returns False.

1. >>> {1:'one',2:'two'}<{1:'three',2:'four'}

Traceback (most recent call last):

File “<pyshell#91>”, line 1, in <module>

{1:’one’,2:‘two‘}<{1:‘three‘,2:‘four‘}

TypeError: ‘<‘ not supported between instances of ‘dict‘ and ‘dict‘

If you face any doubt in Python Comparison Operators? Please Comment.

4. Python Greater Than (>) Operator

Let’s see the Greater than Python Comparison Operator

Now that we’ve seen which constructs we can apply these operators to, we will focus on the operators now on.
The greater than an operator, denoted by >, checks whether the left value is greater than the one on the right.

We recommend you to read Python Decision Making

1. >>> 0.5>False

Output: True

1. >>> 3,4,5>3,4,5.0

Output: (3, 4, True, 4, 5.0)

Hey, this created a tuple, when all we wanted to do was compare. This is because it took 5>3 as a value (True).
It put this as a value in the tuple. So let’s try to find our way around this.

1. >>> 3,4,5 > 3,4,5.0

Output: (3, 4, True, 4, 5.0)

So we see that spaces didn’t do it. Let’s try something else.

1. >>> 3,4,5>(3,4,5.0)

Traceback (most recent call last):

File “<pyshell#96>”, line 1, in <module>


3,4,5>(3,4,5.0)

TypeError: ‘>’ not supported between instances of ‘int’ and ‘tuple’

Hmm, we think we need to put parentheses around both tuples.

1. >>> (3,4,5)>(3,4,5.0)

Output: False

Yes, it works now. We told you earlier that it’s okay to skip parentheses while declaring a tuple. But in this
situation, it took 3, 4, and 5 to be ints, and believed that we were declaring a tuple, and not comparing two. You
should take care of such situations by coding carefully.

5. Less Than or Equal To (<=) Operator

We guess the next two operators won’t be much of a problem with you. We will quickly learn how to write less
than or equal to in Python.

The less than or equal to operator, denoted by <=, returns True only if the value on the left is either less than or
equal to that on the right of the operator.

1. >>> a=2
2. >>> a<=a*2

Output: True

6. Equal To or Greater Than – Python (>=) Operator

Likewise, this operator returns True only if the value on the left is greater than or equal to that on the right.

1. >>> from math import pi


2. >>> 3.14>=pi

Output: False
Any doubt in Python Comparison Operators? Please Ask us in the comment.

7. Python Equal To (==) Operator

The final two operators we’ll be looking at are equal to (==) and not equal to (!=).

The equal to operator returns True if the values on either side of the operator are equal.

1. >>> 3=='3'

Output: False

As we know, 3 is an integer, and ‘3’ is a string. Hence, they’re unequal. Let’s take about a couple more
examples.

1. >>> {1,3,2}=={1,2,3}
Output: True

Like you know, a set rearranges itself. This is why this returns True.

1. >>> 0==False

Output: True

Of course, False has an integer value of 0. Therefore, it returns True.

8. Python Not Equal Operator (!=) Operator

Finally, we’ll discuss the not equal to operator. Denoted by !=, this does the exact opposite of the equal to
operator. It returns True if the values on either side of the operator are unequal.

1. >>> 3!=3.0

Output: False

1. >>> 3==3.0

Output: True

Note that the operator <> for the same purpose is no longer functional.

This is all about the Python Comparison Operators.

9. Conclusion: Python Comparison Operators

Concluding for today, we learned six comparison operator in python. These are- python less than, python
greater than, Less Than or Equal To, Equal to or greater than, Python Equal To and Python Not Equal Operator.
Their functioning is actually very easy to understand, but feel free to ask a doubt or add to the article in the
comments. Hope you like the Python Comparison Operators Tutorial. See you again.

Python Operator Overloading and Python Magic Methods


by DataFlair Team · September 26, 2018

1. Python Operator Overloading

In this Python tutorial, we are going to discuss Python Operator Overloading, examples of operator overloading
in python, and python magic methods with some operators: python binary operator, python comparison
operator, python unary operators, and python extended assignments. In the programming world, operator
overloading is also called Operator Ad-hoc Polymorphism. Indeed, it is a case of polymorphism where
different operators have different implementations based on their arguments. This is either defined by the
programmer, by the programming language, or both.

So, let’s start the Python Magic Methods Tutorial.


Python Operator Overloading and Python Magic Methods

2. What is Python Operators Overloading?

In Python, an operator lets us perform an operation/procedure on one or more operands(values). Read up on our
article on Python Operators. But for now, let’s take an example.

1. >>> 42+1

43
Here, we performed the addition of two numbers using the addition operator. You know that we can apply this
operator to Python string too. In that case, we call it the concatenation operator. Let’s discuss Python
Syntax before proceeding.

1. >>> '42'+'1'

‘421’

1. >>> 'hello'+' '+'world'

‘hello world’
And then when we do this to Python list, we concatenate two lists.

1. >>> [1,2,3]+[4,5,6]

[1, 2, 3, 4, 5, 6] Python does this implicitly, but what for when you want to apply this operator to your own
class? Can we? Let’s give it a try.
In this python operator overloading tutorial, we take a class ‘myfloat’ to represent floating-point numbers.

1. >>> class myfloat:


2. def init (self,whole,fraction):
3. self.whole=whole
4. self.fraction=fraction
5. def shownumber(self):
6. print(f"I am {self.whole}.{self.fraction}")
7. >>> obj1=myfloat(3,7)
8. >>> obj1.shownumber()

I am 3.7

1. >>> obj2=myfloat(3,3)
2. >>> obj2.shownumber()

I am 3.3
Now, let’s try adding two objects.

1. >>> obj1+obj2

Traceback (most recent call last):

File “<pyshell#24>”, line 1, in <module> obj1+obj2

TypeError: unsupported operand type(s) for +: ‘myfloat’ and ‘myfloat’


As you can see, this raised a TypeError. But don’t fret; we can do this, we’ll discuss in a later section.

3. Python Magic Methods

We observe that python methods have double underscores before and after their names. These are special
methods and are also called ‘dunders’. These help us implement functionality that a normal method can’t
represent.
By now, we have come across only one magic method- init (). But we can, in fact, define our own magic
methods to implement operator overloading in Python. With this, we can define these operators to work on our
custom classes. Some of these are-

a. Python Binary Operators


add for +

sub for –

mul for *

truediv for /

floordiv for //

mod for %

pow for **

and for &


xor for ^

or for |

lshift for <<

rshift for >>

In our article on Python Methods, we discussed these.

b. Python Extended Assignments


iadd for +=

isub for -=

imul for *=

idiv for /=

ifloordiv for //=

imod for %=

ipow for **=

ilshift for <<=

irshift for >>=

iand for &=

ixor for ^=

ior for |=

c. Python Unary Operators


neg for –

pos for +

abs for abs()

invert for ~

complex for complex()

int for int()

long for long()


float for float()

oct for oct()

hex for hex()

d. Python Comparison Operators


lt for <

le for <=

eq for ==

ne for !=

ge for >=

gt for >

Read up on what we have to say about Python Variables and Python Numbers.
Others include radd for reverse add.

1. >>> class myclass:


2. def init (self,age):
3. self.age=age
4. def add (self,other):
5. return self.age+other
6. def radd (self,other):
7. return self.age+other
8. >>> a=myclass(1)
9. >>> a+2

1. >>> 2+a

3
If the interpreter cannot add left to right, it will call radd () instead. Here, radd is in reverse/reflected add.

4. Python Operator Overloading Example


To be able to add our Python objects obj1 and obj2 for class ‘myfloat’, we can do the following.

1. >>> class myfloat:


2. def init (self,whole,fraction):
3. self.whole=whole
4. self.fraction=fraction
5. def shownumber(self):
6. print(f"I am {self.whole}.{self.fraction}")
7. def add (self,other):
8. if (self.fraction+other.fraction)>9:
9. return myfloat(self.whole+other.whole+1,self.fraction+other.fraction-10) return
myfloat(self.whole+other.whole,self.fraction+other.fraction)

Here, we added another method add , that takes two parameters (‘self’ and ‘other’) for the two objects.
Then, it checks if the sum of the fraction parts of both objects is greater than 9. In that case, it transfers a 10 to
the ‘whole’ part as a 1. This is for the carry. It then returns an object with the sums of the whole and fraction
parts of both objects. However, if the condition isn’t met, it simply returns an object with the sums.
Let’s create objects obj1 and obj2 again, and try adding them.

1. >>> obj1=myfloat(3,7)
2. >>> obj1.shownumber()

I am 3.7

1. >>> obj2=myfloat(3,3)
2. >>> obj2.shownumber()

I am 3.3

1. >>> result=obj1+obj2
2. >>> print(f"I am {result.whole}.{result.fraction}")

I am 7.0
As you can see, it works absolutely fine now and lets us add two objects of class ‘myfloat’.

1. >>> result

< main .myfloat object at 0x0572FD10>

This is the resulting object of adding obj1 and obj2.

Here, the interpreter translates obj1+obj2 to obj1. add (obj2).

5. More Examples of Python Operator Overloading

To really understand something, once is never enough. So, let’s take another example of Operator overloading
in Python.

1. >>> class itspower:


2. def init (self,x):
3. self.x=x
4. def pow (self,other):
5. return self.x**other.x
6. >>> a=itspower(2)
7. >>> b=itspower(10)
8. >>> a**b

1024
In this, we take a class ‘itspower’ and two methods init and pow .
pow takes two objects and returns the ‘x’ of first raised to the power of the ‘x’ of the second. When we
type a**b, the interpreter converts it implicitly to a. pow (b).
Now, let’s take another example to demonstrate few more such magic methods.

1. >>> class Person:


2. def init (self,name,age):
3. self.name=name
4. self.age=age
5. def gt (self,other):
6. if self.age>other.age:
7. return True
8. return False
9. def abs (self):
10. return abs(self.age)
11. def iadd (self,other):
12. return self.age+other.age
13. >>> Nick=Person('Nick',7)
14. >>> Angela=Person('Angela',5)
15. >>> Nick>Angela

True

1. >>> Kim=Person('Kim',-8)
2. >>> abs(Kim)

1. >>> Tom=Person('Tom',7)
2. >>> Mikayla=Person('Mikayla',3)
3. >>> Tom+=Mikayla
4. >>> Tom

10
To leave this lesson on an engaging note, we would just like to leave this code here:

1. >>> '1'. add ('1')

’11’

1. >>> 1. add (1)

SyntaxError: invalid syntax

1. >>> [1,2,3]. add ([4,5,6])

[1, 2, 3, 4, 5, 6]

So, this was all about Python Operator overloading and Python Magic Method Tutorial. Hope you like it.

6. Conclusion
Hence, we studied Python Operator overloading, in-effect, is pure syntactic sugar. Through it, we override a
magic method to be able to use an operator on a custom class. Furthermore, if you have any doubt/query, feel
free to ask in the comment section.

Python Ternary Operator – 5 Ways To Implement Ternary Operators


by DataFlair Team · May 17, 2019

1. Objective – Ternary Operator in Python

Today, we will see Python Ternary Operator. Moreover, we will discuss the example and syntax of Ternary
Operator in Python. Also, we will learn before and nested Python Ternary Operators. At last, we will discuss
ways for implementing Ternary operators in Python.
So, let’s start Python Ternary Operator.

Python Ternary Operator – Implementation With Example

2. Python Ternary Operator Example

Ternary operators in Python are terse conditional expressions. These are operators that test a condition and
based on that, evaluate a value. This was made available since PEP 308 was approved and is available ever
since version 2.4. This operator, if used properly, can reduce code size and enhance readability.
Do you know about Python Comparison Operator

a. Python if-else code


Let’s write code to compare two integers.

1. >>> a,b=2,3
2. >>> if a>b:
3. print("a")
4. else:
5. print("b")

b. Equivalent code with Ternary operator


So let’s try doing the same with ternary operators:

1. >>> a,b=2,3
2. >>> print("a" if a>b else "b")
b
Voila! Done in one line. Python first evaluates the condition. If true, it evaluates the first expression; otherwise,
it evaluates the second. There is a lazy evaluation. It also evaluates the conditions left to right.
You must learn about Python Data Structures

3. The syntax for Python Ternary Operator


Now, let’s learn a little the syntax for Python Ternary Operator.

1. [on_true] if [expression] else [on_false]

In C++, it looks like this:

1. max=(a>b)?a:b

But this isn’t quite Pythonic, so Guido, Python’s BDFL (a status from which he has resigned permanently),
rejected it. Another reason for the veto is that we already have many uses for the colon(:).
One more example of Python ternary Operators:

1. >>> from random import random


2. >>> a,b=random(),random()
3. >>> res="a" if a>b else "b"
4. >>> res

‘b’

1. >>> a,b

(0.009415785735741311, 0.9675879478005226)

4. Ways to Implement Ternary Operator

Below, we are discussing different ways of implementing Python Ternary Operator:


Ways to Implement Ternary Operator

a. Using Python Tuples


We can use tuples to specify what to do if the condition is True/False.
Before moving on, you must learn a little about Python Tuples

1. >>> a,b=random(),random()
2. >>> (b,a)[a>b]

0.8182650892806171
This is equivalent to:

1. >>> (b,a)[True]

But we’re confused which this is- a or b. Let’s try tweaking this.

1. >>> (f"b:{b}",f"a:{a}")[a>b]

‘b:0.8182650892806171’
That’s more like it. Looking at the code, you’ll reckon the first argument in the tuple corresponds to a Boolean
value of False; the second- True. This is because of False=0 and True=1. The condition resides within the [ ].
Note that this method evaluates both elements of the tuple, and hence is less efficient. This happens because it
must first build the tuple before it can look for an index.

1. >>> condition=True
2. >>> 2 if condition else 1/0 #Follows the normal if-else logic tree

2
1. >>> (1/0,2)[condition]

Traceback (most recent call last):


File “<pyshell#48>”, line 1, in <module>
(1/0,2)[condition]
ZeroDivisionError: division by zero

b. Using Python Dictionaries


Likewise, we can make this happen using dictionaries with the same logic.
You must read about Python Dictionaries

1. >>> a,b=random(),random()
2. >>> {False:f"b:{b}",True:f"a:{a}"}[a>b]

‘a:0.37237928632774675’
Since we specify what to do when here, we can interchange the positions of key-value pairs.

1. >>> {True:f"a:{a}",False:f"b:{b}"}[a>b]

‘a:0.37237928632774675’

c. Using Lambdas
We can also make use of Python Lambda Functions to act as a ternary operator.

1. >>> (lambda :f"b:{b}",lambda :f"a:{a}")[a>b]()

‘b:0.5955717855531699’

5. Nested Python Ternary Operator

Let’s try chaining these operators, shall we?

1. >>> a=random()
2. >>> "Less than zero" if a<0 else "Between 0 and 1" if a>=0 and a<=1 else "Greater than one"

‘Between 0 and 1’
Have a look at Python Closure

1. >>> a

0.8537574133103878
Here, we check for the value of a. If it falls shorter than 0, we print “Less than zero”; if between 0 and 1, we
print “Between 0 and 1”. Else, we print “Greater than one”. Notice how we nested them.

6. Before Ternary Operators in Python

Before this was a thing with Python, this is what we did (we used a common idiom):

1. >>> a,b=2,3
2. >>> a<b and a or b

2
So how does this work? Let’s see.

 a is 2 and b is 3
 It checks if a<b
 If true, it gives us True and a or b
 This gives us a or b
 It checks a
 If false, it gives us False or b
 This gives us b

This method, however, doesn’t work for a=0. This is because that would be True and 0 or b, which is True and
False or b, which is False or b, which is b. Oops!
Now why don’t you try formulating an expression for a>b and try explaining it to yourself?
Let’s learn about Python Data Science
It could also be beneficial to use the and/or logic when one of our expressions is the same as the condition:

1. >>> def sayhello(): print('Hello')


2. >>> sayhello() if sayhello() else 'Bye'

Hello
Hello
True

1. >>> sayhello() or 'Bye'

Hello
True
So, this was all in Python Ternary Operator. Hope you like our explanation.

7. Conclusion – Python Ternary Operator


Phew! That’s all. Through this Python Ternary Operator blog, we tried our best to bring to you all there is to
know about the ternary operator in Python. Moreover, we discussed the implementation of Ternary Operators in
Python. Also, we saw Python Ternary Operators example and syntax. We curated our content from the best
sources. Like this tutorial? If you’d like us to write about something that has to do with Python (and we haven’t
already), please let us know in the comments below. We are excited to hear from you!

Python Operator Precedence – PEMDAS & Short Circuiting


by DataFlair Team · November 19, 2018

1. Objective
In our last Python tutorial, we discussed Python sys Module. Today, we will see Python Operator Precedence.
Given an expression of multiple operators, how do you go about it? What is 2+3*4%5-1? 13 or 3? To answer
such questions, you will need to know what comes first. In this Python Operator Precedence tutorial, we address
this issue. Moreover, we will learn PEMDAS and short-circuiting in python. At last, we will discuss the
associativity of Python Operators.
So, let’s start the Python Operator Precedence tutorial.

Python Operator Precedence – PEMDAS & Short Circuiting

First, let’s revise a little about Python Operators.

2. Python Operator Precedence Table


Take a look at the following table of Python Operator Precedence:

Operator Description
() (Highest precedence) Parentheses (grouping)
f(args…) Function call
(expressions…), [expressions…], {key: value…}, Binding or tuple display, list display, dictionary display, set
{expressions…} display
x[index], x[index:index], x(arguments), x.attribute Subscription, slicing, call, attribute reference
await x Await expression
** Exponentiation
+x, –x, ~x Positive, negative, bitwise NOT
*, @, /, //, % Multiplication, division, remainder
+, – Addition, subtraction
<<, >> Bitwise shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
in, not in, is, is not, <, <=, >, >=,
<>, !=, == Comparisons, membership, identity
not x Boolean NOT
and Boolean AND
or Boolean OR
if- else Conditional expression
lambda (Lowest precedence) Lambda expression

In here, the operators in one cell evaluate left to right and exponentiation groups right to left. The lowest
Precedence in Python Operator is the least binding and the highest Precedence in Python Operator is the most. It
is also true that we observe the same precedence for comparisons, membership tests, and identity tests. These
also have a left-to-right chaining feature.\
Have a look at Python Syntax and Semantics

3. What is Python Expression?


Before we can tell you about which operator comes first, you’d want to be introduced to expressions. An
expression is a combination of values, variables, operators, and function calls. Notably, the Python interpreter
can evaluate a valid expression. Why don’t we take an example?

1. >>> 4+3

7
4+3 is an expression with one operator. We can also put in more than one. The precedence rules show us the
way to follow an order. The divisionn has a higher precedence than addition.
You must read about Python Statements

1. >>> 3+3/3

4.0
When we use parentheses, however, we can alter the order of execution here.

1. >>> (3+3)/3

2.0
What we conclude here is that using parentheses, we can force the operators of lower precedence to run first. Or
we can say that when two operators share an operand, the one with the higher precedence gets to go first.

4. Python Operator Precedence – PEMDAS


If you’re on this page reading about Python, you sure have heard about BODMAS somewhere in your journey
so far (mathematics, school). In Python, however, we come across PEMDAS:
Parentheses
Exponentiation
Multiplication
Division
Addition
Subtraction
Let’s revise Python Iterables
A mnemonic to remember that will be “Please Excuse My Dear Aunt Susie”.
Let’s take an example.

1. >>> ((((13+5)*2)-4)/2)-13

3.0
How did that happen? Let’s work it out.
13+5 gives us 18
18*2 gives us 36
36-4 gives us 32
32/2 gives us 16.0 #Note that division gives us floats!
16-13 gives us 3.0

5. Python Operator Precedence – Short Circuiting


Python always evaluates the left operand before the right- even in function arguments. For expressions with
and or operations, it uses short-circuiting. This means it evaluates the second operand only until it is needed.
Because of this, such statements can work reliably:

Python Operator Precedence – Short Circuiting

Do you know about Python Closure

1. >>> if(s!=None) and (len(s)<10): pass

To short-circuit is to stop executing the Boolean operation if we have already arrived at the truth value of the
expression. Let’s take a look at this:

 X or Y- Evaluates Y only if X is false; otherwise, returns X


 X and Y- Evaluates Y only if X is true; otherwise, returns X
a. Short Circuiting with and/or
See what this gives us:

1. >>> 0 or "Hello" and 1

1
This doesn’t give us “Hello”, but 1, because:
0 or “Hello” gives us “Hello”
“Hello” and 1 gives us 1
Let’s discuss the Python Multiple Inheritance

b. Short-Circuiting with all()/any()


This also works with the all() and any() functions.

1. >>> def check(i):


2. return i
3. >>> all(check(i) for i in [1,1,0,0,3])

False
This stops at the first False it gets (the 0 at the third position) and returns False.

1. >>> any(check(i) for i in [0,0,0,1,3])

True
This stops at the first True it gets (the 1 at the fourth position) and returns True.

c. Short Circuiting with Conditional Operators


Watch how this unfurls with conditional operators like > and <.
Have a look at Python Bitwise Operator

1. >>> 7>8>check(4)

False
This stops at 7>8 and returns False.

d. Short-Circuiting with Ternary Operators


Now, consider the following expression which is a ternary operator:

1. >>> print("One") if print("Two") else print("Three")

Two
Three
What happens here? Let’s find out.
Python first checks the condition print(“Two”). In evaluating this, it prints “Two”. Also, the Boolean value for
this is False:

1. >>> bool(print("Two"))

Two
False
Since it is False, it does not evaluate print(“One”) and simply evaluates print(“Three”).
Hence, the final output we get is:
Two
Three
Let’s take a tour to Python Sets and Booleans

6. Associativity of Operators in Python


In that table above, many cells had more than one operator. These share precedence. So then, which to evaluate
first? Associativity comes to the rescue here. Many operators have left-to-right associativity.

a. Associative Operators
 Multiplication (*) and Floor Division (//)

For an example, let’s consider the operators multiplication(*) and floor division(//). Watch how the left operand
evaluates first:

1. >>> 3*5//4

1. >>> 3*(5//4)

3
While both give us the same result, they do that in different ways. Watch how:
For the first example:
3*5 gives us 15
15//4 gives us 3
For the second example:
5//4 gives us 1
3*1 gives us 3

 Exponentiation (**)

Now, let’s try this on exponentiation:

1. >>> (2**3)**2

64
You must read Python about Python Functions
And now without parentheses:
1. >>> 2**3**2

512
This is because this is equivalent to:
2**(3**2)
This gives us 2**9
This gives us 512

b. Non-Associative Operators
Assignment and comparison operators are not associative. What this means is that x<y<z is none of the
following:
(x<y)<z
x<(y<z)
This expression is actually equivalent to (and this evaluates left-to-right):
x<y and y<z
Let’s revise Python Strings
So, this was all in Python Operator Precedence. Hope you like our explanation.

7. Conclusion – Python Operator Precedence


Hence, in this Python Operator Precedence tutorial, we learned about operator precedence, PEMDAS, and
short-circuiting. Also, we discussed expressions and associativity in Python Operator Precedence. What would
you like to read from DataFlair? Do let us know in the comments below.

Python Namespace and Variable Scope – Local and Global Variables


by DataFlair Team · May 17, 2019

1. Python Namespace

In this Python Tutorial, we discuss Python Namespace, Types of Namespace in python and Python Variable
Scope, with their examples and python Syntax.
Python Namespace and Variable Scope – Local and Global Variables

Try this: type ‘import this’ in the interpreter.

1. >>> import this

The Zen of Python, by Tim Peters

Beautiful is better than ugly.


Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one– and preferably only one –obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea — let’s do more of those!

2. What is Python Name?

Before we move on to namespaces in python, let’s talk about names in python. A Python name is an identifier-
something we use to access a Python object and in Python, everything’s an object.

We’ll take an example.


1. >>> rank=1

Here, ‘rank’ is the name associated with the Python object 1. To get this object’s address in RAM, we use the
id() function.

1. >>> id(rank)

492979856

1. >>> id(1)

492979856

To take a slightly more complex example, we store 2 in a name ‘a’. Then, we increment it by 1 and associate
the name ‘b’ to the object 2. We keep checking the id as we go.

1. >>> a=2
2. >>> id(a)

492979872

1. >>> a+=1
2. >>> id(a)

492979888

1. >>> b=2
2. >>> id(b)

492979872

1. >>>
2. >>> id(2)

492979872

1. >>> id(3)

492979888

So what’s actually happening? We’ll illustrate.


Java Namespace – Python Name

As you can see, when we set ‘a’ to 3 and set ‘b’ to 2, ‘b’ starts pointing to the object ‘a’ once pointed to. Isn’t
that quite efficient? It does not have to create another object to hold 2 for b. This dynamic name binding is
powerful.

Also, a name can hold any kind of value.

1. >>> a=1
2. >>> a='one'

Finally, since everything is an object, so are Python functions. Consequently, you can associate them with
names.

1. >>> identity=id
2. >>> identity(2)

492979872

Here, we associate the name ‘identity’ with the built-in function id().

Bonus Question- Check the following code and figure out what’s happening.

1. >>> def sayhello(): print('Hello')


2. >>> hi=sayhello()

Hello

1. >>> hi
2. >>> type(hi)

<class ‘NoneType’>

Well, since the function does not return anything, we get an object of class ‘NoneType’. Of course, None is an
object that indicates no value. Did function sayhello() return a value, things would be different. Let’s take
another example.
1. >>> def func1():
2. print("Hi")
3. return 1
4. >>> func2=func1()

Hi

1. >>> func2

1. >>> type(func2)

<class ‘int’>

3. What is Python Namespaces?


A namespace in python is a collection of names. So, a namespace is essentially a mapping of names to
corresponding objects. At any instant, different python namespaces can coexist completely isolated- the
isolation ensures that there are no name collisions. Simply speaking, two namespaces in python can have the
same name without facing any problem. A namespace is implemented as a Python dictionary.

When we start the interpreter, a python namespace is created for as long as we don’t exist. This holds all built-in
names. It is due to this that python functions like print() and id() are always available. Also, each module
creates its own global namespace in python.

When you call a function, a local python namespace is created for all the names in it. A module has a global
namespace. The built-in namespace encloses this. Take a look at the following figure to get a clearer
understanding.

Types of Python Namespace


4. What is Python Variable Scope?

Through various python namespaces, not each can be accessed from every part of the program. A namespace is
in variable scope in a part of a program, if it lets you access the python namespace without having to use a
prefix.

At any instant, we have at least three nested python scopes:

1. Current function’s variable scope- has local names


2. Module’s variable scope- has global names
3. The outermost variable scope- has built-in names

This in accordance with the three kinds of namespaces in python, we just discussed. This also decides the order
of searching for when a reference is made. The order is- the local Python namespace, the global namespace, the
built-in namespace. Also, a nested function creates a nested variable scope inside the outer function’s scope.

5. Few Python Namespace Example

To further what we said, let’s take an example.

1. >>> a=1
2. >>> def func1():
3. b=2
4. def func2():
5. c=3

In this code, ‘a’ is in the global namespace in python. ‘b’ is in the local namespace of func1, and ‘c’ is in the
nested local python namespace of func2.

To func2, ‘c’ is local, ‘b’ is nonlocal, and ‘a’ is global. By nonlocal, we mean it isn’t global, but isn’t local
either. Of course, here, you can write ‘c’, and read both ‘b’ and ‘c’. But you can’t access ‘a’, that would create a
new local variable ‘a’. See this example,

1. >>> a=1
2. >>> def func1():
3. b=2
4. def func3():
5. a=2
6. b=3
7. c=3
8. print(f"a={a}, b={b}, c={c}")
9. func3()
10. print(f"b={b}")
11. >>> func1()
12. a=2, b=3, c=3
13. b=2
14. >>> a

1
To deal with this situation, we can use the ‘global’ and ‘nonlocal’ keywords.
1. >>> a=1
2. >>> def func1():
3. b=2
4. def func3():
5. global
a 6. a=2
7. nonlocal b
8. b=3
9. c=3
10. print(f"a={a}, b={b}, c={c}")
11. func3()
12. print(f"b={b}")
13. >>> func1()
14. a=2, b=3, c=3
15. b=3
16. >>> a

6. Conclusion

There are three types of Python namespaces- global, local, and built-in. It’s the same with a variable scope in
python. Also, the ‘global’ keyword lets us refer to a name in a global scope. Likewise, the ‘nonlocal’ keyword
lets us refer to a name in a nonlocal scope. If you don’t get something, ask us in the comments.

Python Decision Making Statements – Python If, If-else, Nested


Statements
by DataFlair Team · May 17, 2019

1. Python Decision Making Statements

Today, we talk about Python decision making constructs. This includes Python if statements, if else
statements, elif statements, nested if conditions and single statement conditions. We will understand these with
syntax and example to get a clear understanding.

So, let’s start the Python Decision Making Tutorial.


Python Decision Making Statements – Python If, If-else, Nested Statements

2. Python Decision Making Statements

Before we begin with python decision making expressions, let us revise Python concepts.

Sometimes, in a program, we may want to make a decision based on a condition. We know that an expression’s
value can be True or False. We may want to do something only when a certain condition is true. For example,
assume variables a and b. If a is greater, then we want to print “a is greater”. Otherwise, we want to print “b is
greater”. For this, we use an if-statement. Also, operators come in handy when you want to join conditions to
make a composite one.

Let us see at various python decision making expressions in details with syntax and example. So let’s install
python on Windows first and revise Python syntax for programming in Python.

Learn: Operators in Python

3. Python if Statements

An if statement in python takes an expression with it. If the expression amounts to True, then the block of
statements under it is executed. If it amounts to False, then the block is skipped and control transfers to the
statements after the block. But remember to indent the statements in a block equally. This is because we don’t
use curly braces to delimit blocks. Also, use a colon(:) after the condition.
Python Decision Making – Python if Statement

Before starting with the example, let us see various types of variables and data types in Python as it will help in
better programming.

1. a=7
2. if a>6:
3. print(f"{a} is good")

7 is good

Here, since 7>6, the condition is true. So, it prints the given string.

1. if 1:
2. print("yay")

yay

We know, 1 has a Boolean value of True. So, the condition is true, and it prints ‘yay’.

1. if(1==1):
2. print("1")

1. >>>
You can also write the condition in parentheses. It does not cause a syntax error.

4. Python if-else Statements

What happens when the condition is untrue? We can mention that it in the block after the else statement. An
else statement comes right after the block after ‘if’.

Python Decision Making – Python if else Statement

1. if 2<1:
2. print("2")
3. else:
4. SyntaxError: Invalid syntax
5. if 2<1:
6. print("2")
7. else:
8. print("1")

Pay attention to the indent. The else keyword does not appear in the if-block. Press Backspace to undo the
automatic indent. Here, 2 is not less than 1. So, the statements in the else-block are executed. It prints 1.

1. if 2<1:
2. print("2")
3. else:
4. print("1")
5. else:
6. SyntaxError: invalid syntax
7. >>>
As appears in the above example, you cannot posit two else statements under an if. It causes a syntax error.

5. Chained Conditionals (elif ladder)

Python allows the elif keyword as a replacement to the else-if statements in Java or C++. When we have more
than one condition to check, we can use it. If condition 1 isn’t True, condition 2 is checked. If it isn’t true,
condition 3 is checked.

Python Decision Making Statements – Python Chained operators

1. if 2<1:
2. print("2")
3. else if 3<1:
4. SyntaxError: invalid syntax
5. if 2<1:
6. print("2")
7. elif 1<3:
8. print("1")

1. if 2<1:
2. print("2")
3. elif 3<1:
4. print("3")
5. else:
6. print("1")

1. >>>

As we saw, else if causes a syntax error. We must use elif. Here, 2 is not less than 1, so, the condition with elif
is checked. Since it is true (1<3), it prints 1. Also, you can put an else statement after your elif statements if you
want. Since in the last example, the first two conditions are false, the else is executed. So, it prints 1.

6. Nested if Statements in Python


You can put an if statement in the block under another if statement. This is to implement further checks.

Python Decision Making – Nested if Statements in Python

1. >>>a=1
2. >>>b=2
3. >>>if a==1:
4. if b==2:
5. print("a is 1 and b is 2")

a is 1 and b is 2

1. >>>

Here, a is 1. So, b is checked. Since it is 2, it prints the given string. Not every if block has to have statements
though.

7. Single Statement Condition in Python


If you only need to write a single statement under if, you can write it in the same line using single statement
python decision making constructs.

1. a=7
2. if a>4: print("Greater")

Greater

1. >>>

Here, we wrote it in one line, but it works without a problem.

1. if a>4: print("Hi"); print("Works")

Hi
Works

1. >>>

You can also use semicolons to write more than one statement in the same line as the condition. However, this
may affect the readability of your code.

So, this was all about Python Decision Making Statements. Hope you like our explanation.

8. Conclusion

In this lesson, we learnt about the Python decision-making constructs. These include Python if, else, elif, and
nested-if statements. We have discussed all these statements with syntax and examples for better understanding.
They allow us to make decisions in python so that we can choose a set of statements to execute. Don’t forget to
try your own combinations in the shell. Furthermore, if you have any query, feel free to share with us!

Python Loop Tutorial – Python For Loop, Nested For Loop


by DataFlair Team · May 17, 2019

1. Python Loop – Objective


In this Python Loop Tutorial, we will learn about different types of Python Loop. Here, we will study Python
For Loop, Python While Loop, Python Loop Control Statements, and Nested For Loop in Python with their
subtypes, syntax, and examples.

So, let’s start Python Loop Tutorial.

2. Introduction to Python Loop

When you want some statements to execute a hundred times, you don’t repeat them 100 times. Think of when
you want to print numbers 1 to 99. Or that you want to say Hello to 99 friends. In such a case, you can use loops
in python.

Here, we will discuss 4 types of Python Loop:

 Python For Loop


 Python While Loop
 Python Loop Control Statements
 Nested For Loop in Python

3. Python While Loop

A while loop in python iterates till its condition becomes False. In other words, it executes the statements under
itself while the condition it takes is True.
When the program control reaches the while loop, the condition is checked. If the condition is true, the block of
code under it is executed. Remember to indent all statements under the loop equally. After that, the condition is
checked again. This continues until the condition becomes false. Then, the first statement, if any, after the loop
is executed.

1. >>> a=3
2. >>> while(a>0):
3. print(a)
4. a-=1

3
2
1
This loop prints numbers from 3 to 1. In Python, a—wouldn’t work. We use a-=1 for the same.

a. An Infinite Loop
Be careful while using a while loop. Because if you forget to increment the counter variable in python, or write
flawed logic, the condition may never become false. In such a case, the loop will run infinitely, and the
conditions after the loop will starve. To stop execution, press Ctrl+C. However, an infinite loop may actually be
useful. This in cases when a semaphore is needed, or for client/server programming. A semaphore is a variable
used solely for synchronization in accessing shared resources.

b. The else statement for while loop


A while loop may have an else statement after it. When the condition becomes false, the block under the else
statement is executed. However, it doesn’t execute if you break out of the loop or if an exception is raised.

1. >>> a=3
2. >>> while(a>0):
3. print(a)
4. a-=1
5. else:
6. print("Reached 0")

3
2
1

Reached 0

In the following code, we put a break statement in the body of the while loop for a==1. So, when that happens,
the statement in the else block is not executed.

1. >>> a=3
2. >>> while(a>0):
3. print(a)
4. a-=1
5. if a==1: break;
6. else:
7. print("Reached 0")

3
2

c. Single Statement while


Like an if statement, if we have only one statement in while’s body, we can write it all in one line.

1. >>> a=3
2. >>> while a>0: print(a); a-=1;

3
2
1
You can see that there were two statements in while’s body, but we used semicolons to separate them. Without
the second statement, it would form an infinite loop.

3. Python For Loop


Python for loop can iterate over a sequence of items. The structure of a for loop in Python is different than that
in C++ or Java. That is, for(int i=0;i<n;i++) won’t work here. In Python, we use the ‘in’ keyword. Lets see a
Python for loop Example

Python Loop Tutorial – Python for Loop

1. >>> for a in range(3):


2. print(a)

0
1
2
If we wanted to print 1 to 3, we could write the following code.

1. >>> for a in range(3):


2. print(a+1)

1
2
3
a. The range() function
This function yields a sequence of numbers. When called with one argument, say n, it creates a sequence of
numbers from 0 to n-1.

1. >>> list(range(10))

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

We use the list function to convert the range object into a list object.

Calling it with two arguments creates a sequence of numbers from the first to the second.

1. >>> list(range(2,7))

[2, 3, 4, 5, 6]

You can also pass three arguments. The third argument is the interval.

1. >>> list(range(2,12,2))

[2, 4, 6, 8, 10]

Remember, the interval can also be negative.

1. >>> list(range(12,2,-2))

[12, 10, 8, 6, 4]

However, the following codes will return an empty list.


1. >>> list(range(12,2))

[]

1. >>> list(range(2,12,-2))

[]

1. >>> list(range(12,2,2))

[]

b. Iterating on lists or similar constructs


You aren’t bound to use the range() function, though. You can use the loop to iterate on a list or a similar
construct.

1. >>> for a in [1,2,3]:


2. print(a)

1
2
3

1. >>> for i in {2,3,3,4}:


2. print(i)

2
3
4
You can also iterate on a string.

1. >>> for i in 'wisdom':


2. print(i)

w
i
s
d
o
m

c. Iterating on indices of a list or a similar construct


The len() function returns the length of the list. When you apply the range() function on that, it returns the
indices of the list on a range object. You can iterate on that.

1. >>> list=['Romanian','Spanish','Gujarati']
2. >>> for i in range(len(list)):
3. print(list[i])
Romanian
Spanish
Gujarati

d. The else statement for for-loop


Like a while loop, a for-loop may also have an else statement after it. When the loop is exhausted, the block
under the else statement executes.

1. >>> for i in range(10):


2. print(i)
3. else:
4. print("Reached else")

0
1
2
3
4
5
6
7
8
9
Reached else
Like in the while loop, it doesn’t execute if you break out of the loop or if an exception is raised.

1. >>> for i in range(10):


2. print(i)
3. if(i==7): break
4. else: print("Reached else")

0
1
2
3
4
5
6
7

4. Nested for Loops Python

You can also nest a loop inside another. You can put a for loop inside a while, or a while inside a for, or a for
inside a for, or a while inside a while. Or you can put a loop inside a loop inside a loop. You can go as far as
you want.

1. >>> for i in range(1,6):


2. for j in range(i):
3. print("*",end=' ')
4. print()
*
**
***
****
*****
Let’s look at some nested while loops to print the same pattern.

1. >>> i=6
2. >>> while(i>0):
3. j=6
4. while(j>i):
5. print("*",end=' ')
6. j-=1
7. i-=1
8. print()

*
**
***
****
*****

5. Loop Control Statements in Python

Sometimes, you may want to break out of normal execution in a loop. For this, we have three keywords in
Python- break, continue, and pass.

Python Loop Tutorial –


Loop Control Statements in Python

a. break statement
When you put a break statement in the body of a loop, the loop stops executing, and control shifts to the first
statement outside it. You can put it in a for or while loop.

1. >>> for i in 'break':


2. print(i)
3. if i=='a': break;

b
r
e
a

b. continue statement
When the program control reaches the continue statement, it skips the statements after ‘continue’. It then shifts
to the next item in the sequence and executes the block of code for it. You can use it with both for and while
loops.

1. >>> i=0
2. >>> while(i<8):
3. i+=1
4. if(i==6): continue
5. print(i)

1
2
3
4
5
7
8
If here, the iteration i+=1 succeeds the if condition, it prints to 5 and gets stuck in an infinite loop. You can
break out of an infinite loop by pressing Ctrl+C.

1. >>> i=0
2. >>> while(i<8):
3. if(i==6): continue
4. print(i)
5. i+=1

5
Traceback (most recent call last):
File “<pyshell#14>”, line 1, in <module>
while(i<8):
KeyboardInterrupt

c. pass statement
In Python, we use the pass statement to implement stubs. When we need a particular loop, class, or function in
our program, but don’t know what goes in it, we place the pass statement in it. It is a null statement. The
interpreter does not ignore it, but it performs a no-operation (NOP).

1. >>> for i in 'selfhelp':


2. pass
3. >>> print(i)

p
To run this code, save it in a .py file, and press F5. It causes a syntax error in the shell.

6. Conclusion

In this tutorial on Python Loops, we learnt about while and for loops in Python. We also learnt how to nest
loops, and use the range() function to iterate through a sequence of items. Lastly, we learnt about break,
continue, and pass statements to control loops. So, try out your own combinations in the shell, and don’t forget
to leave your feedback in the comments.

Python Function Tutorial – Type of Functions in Python(With Example)


by DataFlair Team · May 27, 2019

1. Python Function – Objective

In our tutorial, we discussed dictionaries in python. Now, we forward to deeper parts of the language, let’s
read about Python Function. Moreover, we will study the different types of functions in Python: Python built-in
functions, Python recursion function, Python lambda function, and Python user-defined functions with their
syntax and examples.

So, let’s start the Python Function Tutorial.


Python Function Tutorial – Type of Functions in Python(With Example)

Learn: Range Function in Python – Range() in Python

2. An Introduction to Function in Python

Python function in any programming language is a sequence of statements in a certain order, given a name.
When called, those statements are executed. So we don’t have to write the code again and again for each [type
of] data that we want to apply it to. This is called code re-usability.

3. User-Defined Functions in Python

For simplicity purposes, we will divide this lesson into two parts. First, we will talk about user-defined
functions in Python. Python lets us group a sequence of statements into a single entity, called a function. A
Python function may or may not have a name. We’ll look at functions without a name later in this tutorial.

a. Advantages of User-defined Functions in Python


1. This Python Function help divide a program into modules. This makes the code easier to manage,
debug, and scale.
2. It implements code reuse. Every time you need to execute a sequence of statements, all you need to do is
to call the function.
3. This Python Function allow us to change functionality easily, and different programmers can work on
different functions.

b. Defining a Function in Python


To define your own Python function, you use the ‘def’ keyword before its name. And its name is to be followed
by parentheses, before a colon(:).

1. >>> def hello():


2. print("Hello")

The contents inside the body of the function must be equally indented.

As we had discussed in our article on Python syntax, you may use a docstring right under the first line of a
function declaration. This is a documentation string, and it explains what the function does.

1. >>> def hello():


2. """
3. This Python function simply prints hello to the screen
4. """
5. print("Hello")

You can access this docstring using the doc attribute of the function.

1. >>> def func1():


2. """
3. This is the docstring
4. """
5. print("Hello")
1. >>> func1. doc
2. '\n\tThis is the docstring\n\t'

However, if you apply the attribute to a function without a docstring, this happens.

1. >>> sum. doc


2. >>> type(sum. doc )
3. <class 'NoneType'>
4. >>> bool(sum. doc )

False

If you don’t yet know what to put in the function, then you should put the pass statement in its body. If you
leave its body empty, you get an error “Expected an indented block”.

1. >>> def hello1():


2. pass
3. >>> hello1()

You can even reassign a function by defining it again.

c. Rules for naming python function (identifier)


We follow the same rules when naming a function as we do when naming a variable.

1. It can begin with either of the following: A-Z, a-z, and underscore(_).
2. The rest of it can contain either of the following: A-Z, a-z, digits(0-9), and underscore(_).
3. A reserved keyword may not be chosen as an identifier.

It is good practice to name a Python function according to what it does.

d. Python Function Parameters


Sometimes, you may want a function to operate on some variables, and produce a result. Such a function may
take any number of parameters. Let’s take a function to add two numbers.

1. >>> def sum(a,b):


2. print(f"{a}+{b}={a+b}")

1. >>> sum(2,3)

2+3=5

Here, the function sum() takes two parameters- a and b. When we call the function, we pass numbers 2 and 3.
These are the arguments that fit a and b respectively. We will describe calling a function in point f. A function
in Python may contain any number of parameters, or none.

In the next example, we try adding an int and a float.

1. >>> def sum2(a,b):


2. print(f"{a}+{b}={a+b}")
3. >>> sum2(3.0,2)

3.0+2=5.0

However, you can’t add incompatible types.

1. >>> sum2('Hello',2)

Traceback (most recent call last):

File “<pyshell#39>”, line 1, in <module>

sum2(‘Hello’,2)

File “<pyshell#38>”, line 2, in sum2

print(f”{a}+{b}={a+b}”)

TypeError: must be str, not int

e. Python return statement


A Python function may optionally return a value. This value can be a result that it produced on its execution. Or
it can be something you specify- an expression or a value.

1. >>> def func1(a):


2. if a%2==0:
3. return 0
4. else:
5. return 1
6. >>> func1(7)

As soon as a return statement is reached in a function, the function stops executing. Then, the next statement
after the function call is executed. Let’s try returning an expression.

1. >>> def sum(a,b):


2. return a+b
3. >>> sum(2,3)

1. >>> c=sum(2,3)

This was the Python Return Function

f. Calling a Python function


To call a Python function at a place in your code, you simply need to name it, and pass arguments, if any. Let’s
call the function hello() that we defined in section b.
1. >>> hello()

Hello

We already saw how to call python function with arguments in section e.

g. Scope and Lifetime of Variables in Python


A variable isn’t visible everywhere and alive every time. We study this in functions because the scope and
lifetime for a variable depend on whether it is inside a function.

1. Scope

A variable’s scope tells us where in the program it is visible. A variable may have local or global scope.

 Local Scope- A variable that’s declared inside a function has a local scope. In other words, it is local to
that function.

1. >>> def func3():


2. x=7
3. print(x)
4. >>> func3()

If you then try to access the variable x outside the function, you cannot.

1. >>> x

Traceback (most recent call last):

File “<pyshell#96>”, line 1, in <module>

NameError: name ‘x’ is not defined

 Global Scope- When you declare a variable outside python function, or anything else, it has global
scope. It means that it is visible everywhere within the program.

1. >>> y=7
2. >>> def func4():
3. print(y)
4. >>> func4()

However, you can’t change its value from inside a local scope(here, inside a function). To do so, you must
declare it global inside the function, using the ‘global’ keyword.

1. >>> def func4():


2. global y
3. y+=1
4. print(y)
5. >>> func4()

1. >>> y

As you can see, y has been changed to 8.

2. Lifetime

A variable’s lifetime is the period of time for which it resides in the memory.

A variable that’s declared inside python function is destroyed after the function stops executing. So the next
time the function is called, it does not remember the previous value of that variable.

1. >>> def func1():


2. counter=0
3. counter+=1
4. print(counter)
5. >>> func1()

1. >>> func1()

As you can see here, the function func1() doesn’t print 2 the second time.

h. Deleting Python function


Till now, we have seen how to delete a variable. Similarly, you can delete a function with the ‘del’ keyword.

1. >>> def func7():


2. print("7")
3. >>> func7()

1. >>> del func7


2. >>> func7()

Traceback (most recent call last):

File “<pyshell#137>”, line 1, in <module>


func7()

NameError: name ‘func7’ is not defined

When deleting a function, you don’t need to put parentheses after its name.

Different Python Function Explained Below.

4. Python Built-in Functions


In various previous lessons, we have seen a range of built-in functions by Python. This Python function apply
on constructs like int, float, bin, hex, string, list, tuple, set, dictionary, and so. Refer to those lessons to revise
them all.

5. Python Lambda Expressions

As we said earlier, a function doesn’t need to have a name. A lambda expression in Python allows us to create
anonymous python function, and we use the ‘lambda’ keyword for it. The following is the syntax for a lambda
expression.

lambda arguments:expression

It’s worth noting that it can have any number of arguments, but only one expression. It evaluates the value of
that expression, and returns the result. Let’s take an example.

1. >>> myvar=lambda a,b:(a*b)+2


2. >>> myvar(3,5)

17

This code takes the numbers 3 and 5 as arguments a and b respectively, and puts them in the expression
(a*b)+2. This makes it (3*5)+2, which is 17. Finally, it returns 17.

Actually, the function object is assigned to the identifier myvar.

Any Doubt yet in Python Function? Please Comment.

6. Python Recursion Function

A very interesting concept in any field, recursion is using something to define itself. In other words, it is
something calling itself. In Python function, recursion is when a function calls itself. To see how this could be
useful, let’s try calculating the factorial of a number. Mathematically, a number’s factorial is:

n!=n*n-1*n-2*…*2*1

To code this, we type the following.

1. >>> def facto(n):


2. if n==1:
3. return 1
4. return n*facto(n-1)
5. >>> facto(5)

120

1. >>> facto(1)

1. >>> facto(2)

1. >>> facto(3)

This was all about recursion function in Python

Isn’t this handy? Tell us where else would you use recursion. However, remember that if you don’t mention the
base case (the case which converges the condition), it can result in an infinite execution.

This was all about the Python Function

7. Conclusion: Python Function

It is important to revise in order to retain information. In this lesson, we learned about the Python function.
First, we saw the advantages of a user-defined function in Python. Now we can create, update, and delete a
function. And we know that a function may take arguments and may return a value. We also looked at the scope
and lifetime of a variable. Hope you like the Python Function Tutorial.

Don’t forget to revise the various built-in functions supported by Python. Refer to our tutorials for the same.

Python Function Arguments with Types, Syntax and Examples


by DataFlair Team · November 15, 2018

1. Python Function Argument

Previously, we have covered Functions in Python. In this Python Function Arguments tutorial, we will learn
about what function arguments used in Python and its type: Python Keyword Arguments, Default Arguments in
Python, and Python Arbitrary Arguments.

So, let’s start Python Function Arguments.


Python Function Arguments with Types, Syntax and Examples

2. What is Python Function?

Python function is a sequence of statements that execute in a certain order, we associate a name with it.
This lets us reuse code.

We define a function using the ‘def’ keyword. Let’s take an example.

1. >>> def sayhello():


2. """
3. This prints Hello
4. """
5. print("Hello")

Then to call this, we simply use the function’s name with parentheses. Also, notice the docstring.

1. >>> sayhello()

Hello
This one takes no arguments. Now, let’s see one with python function arguments.

1. >>> def sum(a,b):


2. return a+b
3. >>> sum(2,3)

5
To this, if we pass only one argument, the interpreter complains.

1. >>> sum(3)
2. Traceback (most recent call last):
3. File "<pyshell#44>", line 1, in <module>
4. sum(3)

TypeError: sum() missing 1 required positional argument: ‘b’


To deal with such situations, we see different types of arguments in python functions.
Learn: Recursion in Python with Examples

3. Types of Python Function Arguments

There are various types of Python arguments functions. Let’s learn them one by one:

a. Default Argument in Python


Python Program arguments can have default values. We assign a default value to an argument using the
assignment operator in python(=). When we call a function without a value for an argument, its default value
(as mentioned) is used.

1. >>> def greeting(name='User'):


2. print(f"Hello, {name}")
3. >>> greeting('Ayushi')

Hello, Ayushi

1. >>> greeting()

Hello, User

Here, when we call greeting() without an argument, the name takes on its default value- ‘User’.

Any number of arguments can have a default value. But you must make sure to not have a non-default argument
after a default argument. In other words, if you provide a default argument, all others succeeding it must have
default values as well. The reason is simple. Imagine you have a function with two parameters. The first
argument has a default value, but the second doesn’t. Now when you call it(if it was allowed), you provide only
one argument. The interpreter takes it to be the first argument. What happens to the second argument, then? It
has no clue.

1. >>> def sum(a=1,b):


2. return a+b

SyntaxError: non-default argument follows default argument


This was all about the default arguments in Python

b. Python Keyword Arguments


With keyword arguments in python, we can change the order of passing the arguments without any
consequences. Let’s take a function to divide two numbers, and return the quotient.

1. >>> def divide(a,b):


2. return a/b
3. >>> divide(3,2)

1.5
We can call this function with arguments in any order, as long as we specify which value goes into what.

1. >>> divide(a=1,b=2)

0.5

1. >>> divide(b=2,a=1)

0.5
As you can see, both give us the same thing. These are keyword python function arguments.
But if you try to put a positional argument after a keyword argument, it will throw Python exception of
SyntaxError.

1. >>> divide(b=2,1)

SyntaxError: positional argument follows keyword argument in python.


Learn how to do Exception Handling in Python.
Any Doubt yet in Python Function Arguments

c. Python Arbitrary Arguments


You may not always know how many arguments you’ll get. In that case, you use an asterisk(*) before an
argument name.

1. >>> def sayhello(*names):


2. for name in names:
3. print(f"Hello, {name}")

And then when you call the function with a number of arguments, they get wrapped into a Python tuple. We
iterate over them using the for loop in python.

1. >>> sayhello('Ayushi','Leo','Megha')

Hello, Ayushi
Hello, Leo
Hello, Megha
Learn: Python Applications – Python Use Cases in Real World
This was all about the Python Function Arguments.

4. Conclusion: Python Function Arguments

Hence, we conclude that Python Function Arguments and its three types of arguments to functions. These are-
default, keyword, and arbitrary arguments. Where default arguments help deal with the absence of values,
keyword arguments let us use any order. Finally, arbitrary arguments in python save us in situations where
we’re not sure how many arguments we’ll get. Furthermore, if you have a query, feel free to ask in the comment
box
Top python Books to learn Python programming language.
Python Built-In Functions with Syntax and Examples
by DataFlair Team · May 27, 2019

We have talked about Functions in Python. In that tutorial of Python Functions, we discussed user-defined
functions in Python. But that isn’t all, a list of Python built-in functions that we can toy around with. In this
tutorial on Built-in functions in Python, we will see each of those; we have 67 of those in Python 3.6 with their
Python Syntax and examples.

So, let’s start Python Built-In Functions.

Python Built-In Functions with Syntax and Examples

Python Built-In Functions

1. abs()
The abs() is one of the most popular Python built-in functions, which returns the absolute value of a number. A
negative value’s absolute is that value is positive.

1. >>> abs(-7)

1. >>> abs(7)

1. >>> abs(0)
2. all()
The all() function takes a container as an argument. This Built in Functions returns True if all values in a python
iterable have a Boolean value of True. An empty value has a Boolean value of False.

1. >>> all({'*','',''})

False

1. >>> all([' ',' ',' '])

True

3. any()
Like all(), it takes one argument and returns True if, even one value in the iterable has a Boolean value of True.

1. >>> any((1,0,0))

True

1. >>> any((0,0,0))

False

4. ascii()
It is important Python built-in functions, returns a printable representation of a python object (like a string or a
Python list). Let’s take a Romanian character.

1. >>> ascii('ș')

“‘\\u0219′”

Since this was a non-ASCII character in python, the interpreter added a backslash (\) and escaped it using
another backslash.

1. >>>

ascii('ușor')

“‘u\\u0219or'”

Let’s apply it to a list.

1. >>> ascii(['s','ș'])

“[‘s’, ‘\\u0219’]”

5. bin()
bin() converts an integer to a binary string. We have seen this and other functions in our article on Python
Numbers.

1. >>> bin(7)

‘0b111’

We can’t apply it on floats, though.

1. >>> bin(7.0)

Traceback (most recent call last):

File “<pyshell#20>”, line 1, in <module>

bin(7.0)

TypeError: ‘float’ object cannot be interpreted as an integer

6. bool()
bool() converts a value to Boolean.

1. >>> bool(0.5)

True

1. >>> bool('')

False

1. >>> bool(True)

True

7.bytearray()
bytearray() returns a python array of a given byte size.

1. >>> a=bytearray(4)
2. >>> a

bytearray(b’\x00\x00\x00\x00′)

1. >>> a.append(1)
2. >>> a

bytearray(b’\x00\x00\x00\x00\x01′)

1. >>> a[0]=1
2. >>> a
bytearray(b’\x01\x00\x00\x00\x01′)

1. >>> a[0]

Let’s do this on a list.

1. >>> bytearray([1,2,3,4])

bytearray(b’\x01\x02\x03\x04′)

8. bytes()
bytes() returns an immutable bytes object.

1. >>> bytes(5)

b’\x00\x00\x00\x00\x00′

1. >>> bytes([1,2,3,4,5])

b’\x01\x02\x03\x04\x05′

1. >>> bytes('hello','utf-8')

b’hello’

Here, utf-8 is the encoding.

Both bytes() and bytearray() deal with raw data, but bytearray() is mutable, while bytes() is immutable.

1. >>> a=bytes([1,2,3,4,5])
2. >>> a

b’\x01\x02\x03\x04\x05′

1. >>> a[4]=

Traceback (most recent call last):

File “<pyshell#46>”, line 1, in <module>

a[4]=3

TypeError: ‘bytes’ object does not support item assignment

Let’s try this on bytearray().


1. >>> a=bytearray([1,2,3,4,5])
2. >>> a

bytearray(b’\x01\x02\x03\x04\x05′)

1. >>> a[4]=3
2. >>> a

bytearray(b’\x01\x02\x03\x04\x03′)

9. callable()
callable() tells us if an object can be called.

1. >>> callable([1,2,3])

False

1. >>> callable(callable)

True

1. >>> callable(False)

False

1. >>> callable(list)

True

A function is callable, a list is not. Even the callable() python Built In function is callable.

10. chr()
chr() Built In function returns the character in python for an ASCII value.

1. >>> chr(65)

‘A’

1. >>> chr(97)

‘a’

1. >>> chr(9)

‘\t’

1. >>> chr(48)

‘0’
11. classmethod()
classmethod() returns a class method for a given method.

1. >>> class fruit:


2. def sayhi(self):
3. print("Hi, I'm a fruit")
4.
5. >>> fruit.sayhi=classmethod(fruit.sayhi)
6. >>> fruit.sayhi()

Hi, I’m a fruit

When we pass the method sayhi() as an argument to classmethod(), it converts it into a python class method one
that belongs to the class. Then, we call it like we would call any static method in python without an object.

12. compile()
compile() returns a Python code object. We use Python in built function to convert a string code into object
code.

1. >>> exec(compile('a=5\nb=7\nprint(a+b)','','exec'))

12

Here, ‘exec’ is the mode. The parameter before that is the filename for the file form which the code is read.
Finally, we execute it using exec().

13. complex()
complex() function creates a complex number. We have seen this is our article on Python Numbers.

1. >>> complex(3)

(3+0j)

1. >>> complex(3.5)

(3.5+0j)

1. >>> complex(3+5j)

(3+5j)

14. delattr()
delattr() takes two arguments- a class, and an attribute in it. It deletes the attribute.

1. >>> class fruit:


2. size=7
3.
4. >>> orange=fruit()
5. >>> orange.size

1. >>> delattr(fruit,'size')
2. >>> orange.size

Traceback (most recent call last):

File “<pyshell#95>”, line 1, in <module>

orange.size

AttributeError: ‘fruit’ object has no attribute ‘size’

15. dict()
dict(), as we have seen it, creates a python dictionary.

1. >>> dict()

{}

1. >>> dict([(1,2),(3,4)])

{1: 2, 3: 4}

This was about dict() Python Built In function

16. dir()
dir() returns an object’s attributes.

1. >>> class fruit:


2. size=7
3. shape='round'
4. >>> orange=fruit()
5. >>> dir(orange)

[‘ class ’, ‘ delattr__’, ‘ dict ’, ‘ dir ’, ‘ doc ’, ‘ eq ’, ‘__format ’, ‘ ge ’,


‘ getattribute ’, ‘ gt ’, ‘ hash ’, ‘ init ’, ‘ init_subclass ’, ‘ le ’, ‘ lt ’, ‘ module ’,
‘ ne ’, ‘ new ’, ‘__reduce ’, ‘ reduce_ex ’, ‘ repr ’, ‘ setattr ’, ‘ sizeof ’, ‘ str ’,
‘ subclasshook ’, ‘ weakref ’, ‘shape’, ‘size’]

17. divmod()
divmod() in Python built-in functions, takes two parameters, and returns a tuple of their quotient and remainder.
In other words, it returns the floor division and the modulus of the two numbers.
1. >>> divmod(3,7)

(0, 3)

1. >>> divmod(7,3)

(2, 1)
If you encounter any doubt in Python Built-in Function, Please Comment.

18. enumerate()
This Python Built In function returns an enumerate object. In other words, it adds a counter to the iterable.

1. >>> for i in enumerate(['a','b','c']):


2. print(i)

(0, ‘a’)
(1, ‘b’)
(2, ‘c’)

19. eval()
This Function takes a string as an argument, which is parsed as an expression.

1. >>> x=7
2. >>> eval('x+7')

14

1. >>> eval('x+(x%2)')

20. exec()
exec() runs Python code dynamically.

1. >>> exec('a=2;b=3;print(a+b)')

1. >>> exec(input("Enter your program"))

Enter your programprint(2+3)

21. filter()
Like we’ve seen in python Lambda Expressios, filter() filters out the items for which the condition is True.
1. >>> list(filter(lambda x:x%2==0,[1,2,0,False]))

[2, 0, False]

22. float()
This Python Built In function converts an int or a compatible value into a float.

1. >>> float(2)

2.0

1. >>> float('3')

3.0

1. >>> float('3s')

Traceback (most recent call last):

File “<pyshell#136>”, line 1, in <module>

float(‘3s’)

ValueError: could not convert string to float: ‘3s’

1. >>> float(False)

0.0

1. >>> float(4.7)

4.7

23. format()
We have seen this Python built-in function, one in our lesson on Python Strings.

1. >>> a,b=2,3
2. >>> print("a={0} and b={1}".format(a,b))

a=2 and b=3

1. >>> print("a={a} and b={b}".format(a=3,b=4))

a=3 and b=4

24. frozenset()
frozenset() returns an immutable frozenset object.
1. >>> frozenset((3,2,4))

frozenset({2, 3, 4})

Read Python Sets and Booleans for more on frozenset.

25. getattr()
getattr() returns the value of an object’s attribute.

1. >>> getattr(orange,'size')

26. globals()
This Python built-in functions, returns a dictionary of the current global symbol table.

1. >>> globals()

{‘ name ’: ‘ main ’, ‘ doc ’: None, ‘ package ’: None, ‘ loader ’: <class


‘_frozen_importlib.BuiltinImporter’>, ‘ spec ’: None, ‘ annotations ’: {}, ‘ builtins ’: <module
‘builtins’ (built-in)>, ‘fruit’: <class ‘ main .fruit’>, ‘orange’: < main .fruit object at 0x05F937D0>, ‘a’:
2, ‘numbers’: [1, 2, 3], ‘i’: (2, 3), ‘x’: 7, ‘b’: 3}

27. hasattr()
Like delattr() and getattr(), hasattr() Python built-in functions, returns True if the object has that attribute.

1. >>> hasattr(orange,'size')

True

1. >>> hasattr(orange,'shape')

True

1. >>> hasattr(orange,'color')

False

28. hash()
hash() function returns the hash value of an object. And in Python, everything is an object.

1. >>> hash(orange)

6263677

1. >>> hash(orange)
6263677

1. >>> hash(True)

1. >>> hash(0)

1. >>> hash(3.7)

644245917

1. >>> hash(hash)

25553952

This was all about hash() Python In Built function

29. help()
To get details about any module, keyword, symbol, or topic, we use the help() function.

1. >>> help()
2.
3. Welcome to Python 3.6's help utility!
4.
5. If this is your first time using Python, you should definitely check out the tutorial on the Internet at
http://docs.python.org/3.6/tutorial/.
6.
7. Enter the name of any module, keyword, or topic to get help on writing Python programs and using
Python modules. To quit this help utility and return to the interpreter, just type "quit".
8.
9. To get a list of available modules, keywords, symbols, or topics, type "modules", "keywords",
"symbols", or "topics". Each module also comes with a one-line summary of what it does; to list the
modules whose name or summary contain a given string such as "spam", type "modules spam".
10.
11. help> map
12. Help on class map in module builtins:
13. class map(object)
14. | map(func, *iterables) --> map object
15. |
16. | Make an iterator that computes the function using arguments from
17. | each of the iterables. Stops when the shortest iterable is exhausted.
18. |
19. | Methods defined here:
20. |
21. | getattribute (self, name, /)
22. | Return getattr(self, name).
23. |
24. | iter (self, /)
25. | Implement iter(self).
26. |
27. | new (*args, **kwargs) from builtins.type
28. | Create and return a new object. See help(type) for accurate signature.
29. |
30. | next (self, /)
31. | Implement next(self).
32. |
33. | reduce (...)
34. | Return state information for pickling.
35. help> You are now leaving help and returning to the Python interpreter.
36. If you want to ask for help on a particular object directly from the
37. interpreter, you can type "help(object)". Executing "help('string')"
38. has the same effect as typing a particular string at the help> prompt.
39. >>>

30. hex()
Hex() Python built-in functions, converts an integer to hexadecimal.

1. >>> hex(16)

‘0x10’

1. >>> hex(False)

‘0x0’

31. id() Function

id() returns an object’s identity.


1. >>> id(orange)

100218832

1. >>> id({1,2,3})==id({1,3,2})

True

32. input()
Input() Python built-in functions, reads and returns a line of string.

1. >>> input("Enter a number")

Enter a number7
‘7’
Note that this returns the input as a string. If we want to take 7 as an integer, we need to apply the int() function
to it.

1. >>> int(input("Enter a number"))

Enter a number7

33. int()
int() converts a value to an integer.

1. >>> int('7')

34. isinstance()
We have seen this one in previous lessons. isinstance() takes a variable and a class as arguments. Then, it
returns True if the variable belongs to the class. Otherwise, it returns False.

1. >>>

isinstance(0,str) False

1. >>> isinstance(orange,fruit)

True

35. issubclass()
This Python Built In function takes two arguments- two python classes. If the first class is a subclass of the
second, it returns True. Otherwise, it returns False.

1. >>> issubclass(fruit,fruit)

True

1. >>> class fruit:


2. pass
3. >>> class citrus(fruit):
4. pass

1. >>> issubclass(fruit,citrus)

False

36. iter()
Iter() Python built-in functions, returns a python iterator for an object.

1. >>> for i in iter([1,2,3]):


2. print(i)

1
2
3

37. len()
We’ve seen len() so many times by now. It returns the length of an object.

1. >>> len({1,2,2,3})

Here, we get 3 instead of 4, because the set takes the value ‘2’ only once.

38. list()
list() creates a list from a sequence of values.

1. >>> list({1,3,2,2})

[1, 2, 3]

39. locals()
This function returns a dictionary of the current local symbol table.

1. >>> locals()

{‘ name ’: ‘ main ’, ‘ doc ’: None, ‘ package ’: None, ‘ loader ’: <class


‘_frozen_importlib.BuiltinImporter’>, ‘ spec ’: None, ‘ annotations ’: {}, ‘ builtins ’: <module
‘builtins’ (built-in)>, ‘fruit’: <class ‘ main .fruit’>, ‘orange’: < main .fruit object at 0x05F937D0>, ‘a’:
2, ‘numbers’: [1, 2, 3], ‘i’: 3, ‘x’: 7, ‘b’: 3, ‘citrus’: <class ‘ main .citrus’>}

40. map()
Like filter(), map() Python built-in functions, takes a function and applies it on an iterable. It maps True or False
values on each item in the iterable.

1. >>> list(map(lambda x:x%2==0,[1,2,3,4,5]))

[False, True, False, True, False]

41. max()
A no-brainer, max() returns the item, in a sequence, with the highest value of all.
1. >>> max(2,3,4)

1. >>> max([3,5,4])

1. >>> max('hello','Hello')

‘hello’

42. memoryview()
memoryview() shows us the memory view of an argument.

1. >>> a=bytes(4)
2. >>> memoryview(a)

<memory at 0x05F9A988>

1. >>> for i in memoryview(a):


2. print(i)

43. min()
min() returns the lowest value in a sequence.

1. >>> min(3,5,1)

1. >>> min(True,False)

False

44. next()
This Python Built In function returns the next element from the iterator.

1. >>> myIterator=iter([1,2,3,4,5])
2. >>> next(myIterator)

1. >>> next(myIterator)

1. >>> next(myIterator)
3

1. >>> next(myIterator)

1. >>> next(myIterator)

Now that we’ve traversed all items, when we call next(), it raises StopIteration.

1. >>> next(myIterator)

Traceback (most recent call last):

File “<pyshell#392>”, line 1, in <module>

next(myIterator)

StopIteration

45. object()
Object() Python built-in functions, creates a featureless object.

1. >>> o=object()
2. >>> type(o)

<class ‘object’>

1. >>> dir(o)

[‘ class ’, ‘ delattr__’, ‘ dir ’, ‘ doc ’, ‘ eq ’, ‘ format ’, ‘ ge ’, ‘ getattribute ’,


‘ gt ’, ‘ hash ’, ‘__init ’, ‘ init_subclass ’, ‘ le ’, ‘ lt ’, ‘ ne ’, ‘ new ’, ‘ reduce ’,
‘ reduce_ex ’, ‘ repr ’, ‘ setattr ’, ‘ sizeof ’, ‘ str ’, ‘ subclasshook ’] Here, the function
type() tells us that it’s an object. dir() tells us the object’s attributes. But since this does not have the dict
attribute, we can’t assign to arbitrary attributes.

46. oct()
oct() converts an integer to its octal representation.

1. >>> oct(7)

‘0o7’

1. >>> oct(8)

‘0o10’
1. >>> oct(True)

‘0o1’

47. open()
open() lets us open a file. Let’s change the current working directory to Desktop.

1. >>> import os
2. >>>

os.chdir('C:\\Users\\lifei\\Desktop') Now, we

open the file ‘topics.txt’.

1. >>> f=open('topics.txt')
2. >>> f

<_io.TextIOWrapper name=’topics.txt’ mode=’r’ encoding=’cp1252′>

1. >>> type(f)

<class ‘_io.TextIOWrapper’>
To read from the file, we use the read() method.

1. >>> print(f.read())
2. DBMS mappings
3. projection
4. union
5. rdbms vs dbms
6. doget dopost
7. how to add maps
8. OOT
9. SQL queries
10. Join
11. Pattern programs

Output

Default constructor in inheritance

48. ord()
The function ord() returns an integer that represents the Unicode point for a given Unicode character.

1. >>> ord('A')

65

1. >>> ord('9')

57
This is complementary to chr().
1. >>> chr(65)

‘A’

49. pow()
pow() takes two arguments- say, x and y. It then returns the value of x to the power of y.

1. >>> pow(3,4)

81

1. >>> pow(7,0)

1. >>> pow(7,-1)

0.14285714285714285

1. >>> pow(7,-2)

0.02040816326530612

50. print()
We don’t think we need to explain this anymore. We’ve been seeing this function since the beginning of this
article.

1. >>> print("Okay, next function,

please!") Okay, next function, please!

51. property()
The function property() returns a property attribute. Alternatively, we can use the syntactic sugar @property.
We will learn this in detail in our tutorial on Python Property.

52. range()
We’ve taken a whole tutorial on this. Read up range() in Python.

1. >>> for i in range(7,2,-2):


2. print(i)

7
5
3

53. repr()
repr() returns a representable string of an object.

1. >>> repr("Hello")

“‘Hello'”

1. >>> repr(7)

‘7’

1. >>> repr(False)

‘False’

54. reversed()
This functions reverses the contents of an iterable and returns an iterator object.

1. >>> a=reversed([3,2,1])
2. >>> a

<list_reverseiterator object at 0x02E1A230>

1. >>> for i in a:
2. print(i)

1
2
3

1. >>> type(a)

<class ‘list_reverseiterator’>

55. round()
round() rounds off a float to the given number of digits (given by the second argument).

1. >>> round(3.777,2)

3.78

1. >>> round(3.7,3)

3.7

1. >>> round(3.7,-1)

0.0

1. >>> round(377.77,-1)
380.0
The rounding factor can be negative.

56. set()
Of course, set() returns a set of the items passed to it.

1. >>> set([2,2,3,1])

{1, 2, 3}
Remember, a set cannot have duplicate values, and isn’t indexed, but is ordered. Read on Sets and Booleans for
the same.

57. setattr()
Like getattr(), setattr() sets an attribute’s value for an object.

1. >>> orange.size

1. >>> orange.size=8
2. >>> orange.size

58. slice()
slice() returns a slice object that represents the set of indices specified by range(start, stop, step).

1. >>> slice(2,7,2)

slice(2, 7, 2)
We can use this to iterate on an iterable like a string in python.

1. >>> 'Python'[slice(1,5,2)]

‘yh’

59. sorted()
Like we’ve seen before, sorted() prints out a sorted version of an iterable. It does not, however, alter the
iterable.

1. >>> sorted('Python')

[‘P’, ‘h’, ‘n’, ‘o’, ‘t’, ‘y’]

1. >>> sorted([1,3,2])
[1, 2, 3]

60. staticmethod()

staticmethod() creates a static method from a function. A static method is bound to a class rather than to an
object. But it can be called on the class or on an object.

1. >>> class fruit:


2. def sayhi():
3. print("Hi")
4. >>> fruit.sayhi=staticmethod(fruit.sayhi)
5. >>> fruit.sayhi()

Hi
You can also use the syntactic sugar @staticmethod for this.

1. >>> class fruit:


2. @staticmethod
3. def sayhi():
4. print("Hi")
5. >>> fruit.sayhi()

Hi

61. str()
str() takes an argument and returns the string equivalent of it.

1. >>> str('Hello')

‘Hello’

1. >>> str(7)

‘7’

1. >>> str(8.7)

‘8.7’

1. >>> str(False)

‘False’

1. >>> str([1,2,3])

‘[1, 2, 3]’

62. sum()
The function sum() takes an iterable as an argument, and returns the sum of all values.
1. >>> sum([3,4,5],3)

15

63. super()
super() returns a proxy object to let you refer to the parent class.

1. >>> class person:


2. def init (self):
3. print("A person")
4. >>> class student(person):
5. def init (self):
6. super(). init ()
7. print("A student")
8. >>> Avery=student()

A person

A student

64. tuple()
As we’ve seen in our tutorial on Python Tuples, the function tuple() lets us create a tuple.

1. >>> tuple([1,3,2])

(1, 3, 2)

1. >>> tuple({1:'a',2:'b'})

(1, 2)

65. type()
We have been seeing the type() function to check the type of object we’re dealing with.

1. >>> type({})

<class ‘dict’>

1. >>> type(set())

<class ‘set’>

1. >>> type(())

<class ‘tuple’>

1. >>> type((1))
<class ‘int’>

1. >>> type((1,))

<class ‘tuple’>

66. vars()
vars() function returns the dict attribute of a class.

1. >>> vars(fruit)

mappingproxy({‘ module ’: ‘ main ’, ‘size’: 7, ‘shape’: ’round’, ‘ dict ’: <attribute ‘ dict ’ of


‘fruit’ objects>, ‘ weakref ’: <attribute ‘ weakref ’ of ‘fruit’ objects>, ‘ doc ’: None})

67. zip()
zip() returns us an iterator of tuples.

1. >>> set(zip([1,2,3],['a','b','c']))

{(1, ‘a’), (3, ‘c’), (2, ‘b’)}

1. >>> set(zip([1,2],[3,4,5]))

{(1, 3), (2, 4)}

1. >>> a=zip([1,2,3],['a','b','c'])

To unzip this, we write the following code.

1. >>> x,y,z=a
2. >>> x

(1, ‘a’)

1. >>> y

(2, ‘b’)

1. >>> z

(3, ‘c’)
Isn’t this just like tuple unpacking?

So, this was all about Python Built-in Functions. Hope you like our explanation.

3. Conclusion
Phew, was that too much for once? It may be overwhelming at once, but as you will get using these python
Built-in functions, you will get used to them. If you have any query regarding Python built-in functions, Please
Comment.

Python Method – Classes, Objects and Functions in Python


by DataFlair Team · May 27, 2019

1. Python Method – Objective

In our last tutorial, we discussed functions in Python. Today, in this Python Method Tutorial, we will discuss
what is a method in Python Programming Language. Moreover, we will learn Python Class Method and Python
Object. Along with this, we will study the python functions.

So, let’s start Python Class and Object.

Python Method

2. Introduction to Python Method

You are aware of the fact that Python is an object-oriented language, right? This means that it can deal with
classes and objects to model the real world. A Python method is a label that you can call on an object; it is a
piece of code to execute on that object. But before we begin getting any deeper, let’s take a quick look at classes
and objects and wherever you encounter any doubt in the Python Method, please ask in the comment.

3. Python Class Method

A Python Class is an Abstract Data Type (ADT). Think of it like a blueprint. A rocket made from referring to
its blueprint is according to plan. It has all the properties mentioned in the plan, and behaves accordingly.
Likewise, a class is a blueprint for an object. To take an example, we would suggest thinking of a car. The class
‘Car’ contains properties like brand, model, color, fuel, and so. It also holds behavior like start(), halt(), drift(),
speedup(), and turn(). An object Hyundai Verna has the following properties then.

brand: ‘Hyundai’

model: ‘Verna’

color: ‘Black’

fuel: ‘Diesel’

Here, this is an object of the class Car, and we may choose to call it ‘car1’ or ‘blackverna’.

1. >>> class Car:


2. def init (self,brand,model,color,fuel):
3. self.brand=brand
4. self.model=model
5. self.color=color
6. self.fuel=fuel
7. def start(self):
8. pass
9. def halt(self):
10. pass
11. def drift(self):
12. pass
13. def speedup(self):
14. pass
15. def turn(self):
16. pass

4. Python Objects

A Python object is an instance of a class. It can have properties and behavior. We just created the class Car.
Now, let’s create an object blackverna from this class. Remember that you can use a class to create as many
objects as you want.

1. >>> blackverna=Car('Hyundai','Verna','Black','Diesel')

This creates a Car object, called blackverna, with the aforementioned attributes. We did this by calling the class
like a function (the syntax). Now, let’s access its fuel attribute. To do this, we use the dot operator in Python(.).

1. >>> blackverna.fuel

‘Diesel’

5. Python Method

A Python method is like a Python function, but it must be called on an object. And to create it, you must put it
inside a class. Now in this Car class, we have five methods, namely, start(), halt(), drift(), speedup(), and turn().
In this example, we put the pass statement in each of these, because we haven’t decided what to do yet. Let’s
call the drift() Python method on blackverna.

1. >>> blackverna.drift()
2. >>>

Like a function, a method has a name, and may take parameters and have a return statement. Let’s take an
example for this.

1. >>> class Try:


2. def init (self):
3. pass
4. def printhello(self,name):
5. print(f"Hello, {name}")
6. return name
7. >>> obj=Try()
8. >>> obj.printhello('Ayushi')

Hello, Ayushi

‘Ayushi’

Here, the method printhello() has a name, takes a parameter, and returns a value.

 An interesting discovery– When we first defined the class Car, we did not pass the ‘self’ parameter to
the five methods of the class. This worked fine with the attributes, but when we called the drit() method
on blackverna, it gave us this error:

Traceback (most recent call last):

File “<pyshell#19>”, line 1, in <module>

blackverna.drift()

TypeError: drift() takes 0 positional arguments but 1 was given

From this error, we figured that we were missing the ‘self’ parameter to all those methods. Then we added it to
all of them, and called drift() on blackverna again. It still didn’t work.

Finally, we declared the blackverna object again, and then called drift() on it. This time, it worked without an
issue. Make out of this information what you will.

6. init ()

If you’re familiar with any other object-oriented language, you know about constructors. In C++, a constructor
is a special function, with the same name as the class, used to initialize the class’ attributes. Here in Python,
init () is the method we use for this purpose. Let’s see the init part of another class.

1. >>> class Animal:


2. def init (self,species,gender):
3. self.species=species
4. self.gender=gender
5. >>> fluffy=Animal('Dog','Female')
6. >>> fluffy.gender

‘Female’

Here, we used init to initialize the attributes ‘species’ and ‘gender’.

However, you don’t need to define this function if you don’t need it in your code.

1. >>> class Try2:


2. def hello(self):
3. print("Hello")
4. >>> obj2=Try2()
5. >>> obj2.hello()

Init is a magic method, which is why it has double underscores before and after it. We will learn about magic
methods in a later section in this article.

7. Python Self Parameter

You would have noticed until now that we’ve been using the ‘self’ parameter with every method, even the
init (). This tells the interpreter to deal with the current object. It is like the ‘this’ keyword in Java. Let’s
take another code to see how this works.

1. >>> class Fruit:


2. def printstate(self,state):
3. print(f"The orange is {state}")
4. >>> orange=Fruit()
5. >>> orange.printstate("ripe")

The orange is ripe

As you can see, the ‘self’ parameter told the method to operate on the current object, that is, orange. Let’s take
another example.

1. >>> class Result:


2. def init (self,phy,chem,math):
3. self.phy=phy
4. self.chem=chem
5. self.math=math
6. def printavg(self):
7. print(f"Average={(self.phy+self.chem+self.math)/3}")
8. >>> rollone=Result(86,95,85)
9. >>> rollone.chem

95

1. >>> rollone.printavg()

Average=88.66666666666667
You can also assign values directly to the attributes, instead of relying on arguments.

1. >>> class LED:


2. def init (self):
3. self.lit=False
4. >>> obj=LED()
5. >>> obj.lit

False

Finally, we’d like to say that ‘self’ isn’t a keyword. You can use any name instead of it, provided that it isn’t a
reserved keyword, and follows the rules for naming an identifier.

1. >>> class Try3:


2. def init (thisobj,name):
3. thisobj.name=name
4. >>> obj1=Try3('Leo')
5. >>> obj1.name

‘Leo’

This was all about the Python Self Parameter

Any doubt yet in Python Method? Please Comment.

8. Python Functions vs Method

We think we’ve learned enough about methods by now to be able to compare them to functions. A function
differs from a method in the following ways.

1. While a method is called on an object, a function is generic.


2. Since we call a method on an object, it is associated with it. Consequently, it is able to access and
operate on the data within the class.
3. A method may alter the state of the object; a function does not, when an object is passed as an argument
to it. We have seen this in our tutorial on tuples.

9. Python Magic Methods

Another construct that Python provides us with is Python magic methods. Such a method is identified by double
underscores before and after its name. Another name for a magic method is a dunder.

A magic method is used to implement functionality that can’t be represented as a normal method. init ()
isn’t the only magic method in Python; we will read more about it in a future lesson. But for now, we’ll just
name some of the magic methods:

add for +

sub for –

mul for *
and for &

The list, however, does not end here.

This was all about the Python Method.

10. Conclusion: Python Method

A Python method, as we know it, is much like a function, except for the fact that it is associated with an object.
Now you know how to define a method, and make use of the init method and the self-parameter, or
whatever you choose to call it. Don’t forget to revise the various methods we discussed in our tutorials on
Python lists, tuples, strings, sets, and dictionaries in python. If you have any doubt regarding Python
Method, Please Ask.

Difference Between Method and Function in Python | Python Method


Vs Function
by DataFlair Team · September 26, 2018

1. Python Method Vs Function – Objective

In our journey with Python, we’ve seen the Python method and function. But don’t they feel the same? Well
then, time to make a comparison between Python function and Method with examples. But before that, let’s
revise both – function and method in Python.

So, let’s start Difference Between Method and Function in Python.

Difference Between Method and Function in Python | Python Method Vs Function

Difference Between methods and function in python


2. Python Functions – A Revision

Python function is a sequence of statements that execute in a certain order, given a name. They let us implement
code reusability. When we talked about Python Functions, we talked about built-in and user-defined functions.

a. User-Defined Functions
Like any other programming language, Python lets us define our own functions. Let’s take an example.

1. >>> def add(a,b):


2. return a+b
3. >>> add(3,-3)

We call this function ‘add’. As expected, it adds two values, which it takes as arguments. When we call it with
values -3 and 3, it returns 0. And as you can see, the ‘return’ statement returns a value from Python function.

These let us create a modular program, which in turn lets us make a change easily whenever we want to.

To learn more about functions, docstrings, and scope and lifetime, read up on Python Functions.

b. Built-in Functions
In our write-up on Python In-Built Functions, we discussed about 66 functions in brief. These are the
functions that Python provides us with, and some of these, we see and use commonly. Let’s take a look at a
program that uses some of these.

1. >>> def demofunc(a,b):


2. """
3. //This function is to demonstrate a few built-in functions in Python
4. """
5. print("Begin")
6. print(max(a,b))
7. print(abs(a),abs(b))
8. print(float(a),b)
9. print(callable(a))
10. print(hash(a),hash(b))
11. print(len('ab'))
12. print(type(a))
13. for i in range(2,4): print(i)
14. >>> demofunc(2,3)

Begin

23

2.0 3
False

23

<class ‘int’>

1. >>> c=lambda :print("Hi")


2. >>> type(c)

<class ‘function’>
Also see, ython Lambda Expressions.

3. Python Methods – A Revision

Python method is like a function, except it is attached to an object. We call a method on an object, and it
possibly makes changes to that object. A method, then, belongs to a class. Let’s take an example.

1. >>> class vehicle:


2. def init (self,color):
3. self.color=color
4. def start(self):
5. print("Starting engine")
6. def showcolor(self):
7. print(f"I am {self.color}")
8. >>> car=vehicle('black')
9. >>> car.start()

Starting engine

1. >>> car.showcolor()

I am black
First, we defined class ‘vehicle’. Then, we created the object ‘car’ from this blueprint. Here, init () is a
magic method that serves as a constructor for the class. Method start() and showcolor() let us do what we
want to. Remember that Python method must have a parameter ‘self’ to allow them to refer to the current
object.

4. Comparison Between Method and Function in Python

Now that we’ve revised the Python method and function, we can compare them. Let’s list down the major
differences.

1. Python method is called on an object, unlike a function. In our example above, we call start() on the
object ‘car’. Conversely, we call Python function quite generically- we don’t call it on any object. Since
we call a method on an object, it can access the data within it.
2. A method may alter an object’s state, but Python function usually only operates on it, and then prints
something or returns a value.

So, this was all about Difference Between Method and Function in Python. Hope you like our explanation

5. Conclusion

After this discussion, we conclude that there’s a thin line between method and function in python with
examples. The only major difference is that we call Python method on an object, but it’s not the same with
functions. Also, methods may modify an object; Python functions don’t.

Python Constructor- Parameterized and Non-Parameterized


by DataFlair Team · May 27, 2019

1. Objective
In our last Python tutorial, we discussed Python Identifiers. Today, we will learn about init (self), the
Python Constructor. Moreover, we will take a look at what we can do for it, and will learn about parameterized
and non-parameterized Python Constructors. Also, we will learn about object creation and initialization and will
investigate if it is possible to overload constructors.
So, let’s start the Python Constructor tutorial.

Python Constructor- Parameterized and Non-Parameterized

2. What is a Constructor in Python?


Python Constructor in object-oriented programming with Python is a special kind of method/function we use
to initialize instance members of that class. We can also use it to ensure we have enough resources. Whenever
we create an object of that class, the constructor definition is the first to execute. The way to initialize the value
of a class attribute without a constructor:

1. >>> class three:


2. val=7
3. >>> three.val

Output – 7
Let’s take a look at Python Slice Constructor
We can also do this inside class functions:

1. >>> class three:


2. def func(self,val):
3. self.val=val
4. >>> t=three()
5. >>> t.func(8)
6. >>> t.val

Output – 8

1. >>> t.func(6) #Also lets us re-initialize attributes


2. >>> t.val

Output – 6
Or we can ask the user for input.

1. >>> class three:


2. def init (self):
3. self.val=input("What value?")
4. >>> t=three()

What value?8

1. >>> t.val

Output – ‘8’

3. Declaring a Python Constructor

a. Object Creation
new is a static class method that lets us control object creation. Whenever we make a call to the class
constructor, it makes a call to new . While this is a default function for every class, we can definitely play
around with it.

1. >>> class demo:


2. def new (self):
3. return 'dataflair'
4. >>> d=demo()
5. >>> type(d)
Output – <class ‘str’>
Let’s learn about Python Syntax

b. Object Initialization (and self-parameter)


A constructor is essentially a class function with its name surrounded by double underscores ( ). We always
call it init (). In C++ or Java, a constructor has the same name as its class, but things aren’t the same with
Python. Constructors let us initialize an object. Let’s take an example.

1. >>> class citrus:


2. def init (self):
3. self.detoxifying=True
4. def show(self):
5. print("I detoxify") if self.detoxifying==True else print("I do not detoxify")
6. >>> kumquat=citrus()
7. >>> kumquat.show()

Output – I detoxify
Now statement by statement, let’s see what’s happening.

 init () is the constructor here.


 It takes the self-keyword to tell the interpreter to work with attributes of this object. It should be the first
parameter.
 It takes no parameters.
 When setting detoxifying to true, we use the self-keyword.
 We have another method show(), we pass self to this too.
 Then, we create an object as kumquat=citrus().
 Finally, we make a call to kumquat.show().

Together, both new and init form a constructor.

c. New Attributes
We can also create a new attribute exclusively for this object and read it when defining values. There is not
much you can do once you have already defined the object.

1. >>> kumquat.color='orange'
2. >>> print("I am ",kumquat.color)

Output – I am orange

4. Not Declaring a Python Constructor


So what happens when we do not explicitly provide a constructor to a class? Can Python handle it? Why don’t
we try that out?

1. >>> class color:


2. def show(self):
3. print("You can see me")
4. >>> orange=color()
5. >>> orange.show()

Output – You can see me


Here, we did not define a constructor, but Python instantiated that object anyway! This must mean it provides a
default constructor that shows up when we do not provide any.
Let’s take a tour to Python Copy

5. Types of Python Constructors


We observe three types of Python Constructors, two of which are in our hands. Let’s begin with the one that
isn’t.

a. Default Constructor in Python


A constructor that Python lends us when we forget to include one. This one does absolutely nothing but
instantiates the object; it is an empty constructor- without a body.

1. >>> class demo:


2. def show(self):
3. print("Thank you for instantiating me :)")
4. >>> d=demo()
5. >>> d.show()

Output – Thank you for instantiating me

b. Non- Parameterized Constructor in Python


When we want a constructor to do something but none of that is to manipulate values, we can use a non-
parameterized constructor.
Let’s try the previous example with this!

1. >>> class demo:


2. def init (self):
3. print("Thank you for instantiating me :)")
4. >>> d=demo()

Output – Thank you for instantiating me


We can also use this constructor to set values we’ve decided. Watch how.

1. >>> class demo:


2. def init (self):
3. self.color='red'
4. self.drink='tea'
5. def hello(self):
6. print(f"Thank you for instantiating me, I'm all {self.color}. Would you like some {self.drink}? :)")
7. >>> d=demo()
8. >>> d.hello()
Output – Thank you for instantiating me, I’m all red. Would you like some tea?

c. Parameterized Constructor in Python


This lets us set custom values for instance variables. We can have any number of these.

1. >>> class demo:


2. def init (self,age,country):
3. self.age=age
4. self.place=country
5. def hello(self):
6. print(f"Hello, I am a {self.age}yo from {self.place}")
7. >>> d=demo(22,'Romania')
8. >>> d.hello()

Output – Hello, I am a 22yo from Romania

6. No Constructor Overloading in Python

a. More than One Python Constructor


If you give it more than one constructor, that does not lead to constructor overloading in Python.

1. >>> class one:


2. def init (self):
3. print("First constructor")
4. def init (self):
5. print("Second
constructor") 6. >>> o=one()

Output – Second constructor

b. Two Different Kinds of Constructors in Python


Not even if you try two different kinds of constructors:

1. >>> class one:


2. def init (self):
3. print("First constructor")
4. def init (self,val):
5. self.val=val
6. print("Second constructor",val)
7. >>> o=one()

Traceback (most recent call last):


File “<pyshell#58>”, line 1, in <module>
o=one()
TypeError: init () missing 1 required positional argument: ‘val’
What this means is Python rebinds the name init to the new method. This means the first declaration of
this method is inaccessible now. Internally, new is the constructor that returns a valid and unpopulated
object on which to call __init .
Have a look at Python Assert Statements

c. Using Default Arguments


Even the following piece of code is simply the use of default arguments, not constructor overloading:

1. >>> class one:


2. def init (self,a=1,b=2):
3. print(a+b)
4. >>> o=one(2)

Output – 4

1. >>> o1=one(2,3)

Output – 5

1. >>> o2=one()

Output – 3
So, this was all in Python Constructor tutorial. Hope you like our explanation.

7. Conclusion – Python Constructor


Who knew there was so much to know about constructors in Python? We learned about parameterized and non-
parameterized Python Constructors, the default Python Constructor, the self-keyword, object creation, and
object initialization. Also, we saw that there is no such thing as constructor overloading in Python. Still, if you
have any query, feel free to ask in the comment tab.

Python Range – Range() Function in Python


by DataFlair Team · August 19, 2019

1. Python Range Function Tutorial

Something you’ve always seen with a for loop, python range() function is a handy feature in Python. Like we
saw in our tutorial on Python Loops, range function in python provides us with a list of numbers to iterate on.
Actually, it returns a range object, which we then convert to a list to iterate on.

So, let’s begin the Python Range Function Tutorial.


Python Range Function

2. Introduction to Range in Python

The range() function is an inbuilt function in Python, and it returns a range object. First, let’s see what it looks
like.

Learn: Python Functions with Syntax and Examples

3. Syntax of Python range() function

The Range function in python takes from one to three arguments. Let’s see how.

a. One Parameter
For an argument n, the function returns integer values from 0 to n-1.

range(stop)

Let’s take an example to be clearer.

1. >>> list(range(3))

[0, 1, 2]

What happens if you provide a negative value?

1. >>> list(range(-3))

[]
The fact that it returned an empty list tells us that range() is internally coded to traverse to the right. And there
are no integers from 0 to the right -3, because -3 falls to the left of 0.

1. >>> list(range(0))

[]

Learn: Python Dictionaries with Methods, Functions and Dictionary Operations

b. Two Parameters
Now, we’ll try different combinations for two parameters.

range(start,stop)

1. >>> list(range(1,7))

[1, 2, 3, 4, 5, 6]

Here, both arguments are positive. Also, 7 falls to the right of 1. So, it prints integers from 1 to 6 (7-1). Hence,
we conclude that it prints integers from the first number to one from the second.

Now we try passing arguments where the first is greater than the second.

1. >>> list(range(7,1))

[] To back what we just said, it returns an empty list because 7 falls to the right of 1, and it traverses to the right
from 7. Therefore, it never reaches 1.

In section a, we saw that we can’t pass a negative argument to range(). But it is indeed possible to pass a
negative value or two when you pass two or more arguments. Let’s see how.

1. >>> list(range(-7,3))

[-7, -6, -5, -4, -3, -2, -1, 0, 1, 2]

1. >>> list(range(-7,-3))

[-7, -6, -5, -4]

1. >>> list(range(-3,-7))

[]

This, again, returns an empty list, for -3 lies to the right of -7.

1. >>> list(range(3,3))

[]

There are no integers between 3 and less than 3.


c. Three Parameters
Finally, the range() function can also take a third parameter. This is for the interval.
range(start,stop,interval)

We’ll see this one by example.

1. >>> list(range(7,1,-1))

[7, 6, 5, 4, 3, 2]

After bragging about how you can’t have the second argument smaller than the first one, now we tell you that
you can. But on one condition- you must specify a negative interval. Here, we used -1 as an interval. We
could’ve used -2 as well.

1. >>> list(range(7,1,-2))

[7, 5, 3]

1. >>> list(range(7,1,-8))

[7]

Here, note that the first integer, 7, is always returned, even though the interval -8 sends it beyond 1. Let’s now
take a look at more examples for three parameters.

1. >>> list(range(1,7,1.5))

Traceback (most recent call last):

File “<pyshell#17>”, line 1, in <module>

list(range(1,7,1.5))

TypeError: ‘float’ object cannot be interpreted as an integer

Note that all three arguments must be integers only.

1. >>> list(range(1,7,2))

[1, 3, 5]

Let’s take another example.

1. >>> list(range(1,7,0))

Traceback (most recent call last):

File “<pyshell#26>”, line 1, in <module>

list(range(1,7,0))
ValueError: range() arg 3 must not be zero

It raised a value error, because the interval cannot be zero if you need to go from one number to another.

Actually, when we provide one or two arguments, the interval is assumed to be +1. This is why we were unable
to have it traverse to the left. Now that you know what’s going on, it is easier to toy with range().

Let’s take one last example to make sure we’re on the right train of thoughts.

1. >>> list(range(12,2,2))

[]

Now this returns an empty list in python because in a positive interval of 2 means traversing to the right, but 2
falls to the left of 12.

4. Python Iterate Function

Now that we know how to use Python range() function, don’t you want to know where to use it? Well, one
application is the for loop.

1. >>> for i in range(6):


2. print(i*2)

0
2
4
6
8
10
So, this was all about Python Range Function. Hope you like our explanation.

5. Conclusion

To sum this tutorial up on Python Range, range function in python is an in-built function, in Python, that lends
us a sequence of integers. We can use this to iterate on using a for loop. Now you know that it’s possible to call
range() in python with one, two, or three arguments. We would like you to come up with a creative use of the
range() function; tell us in the comments.

Python Zip Function With Examples | Python Unzipping values


by DataFlair Team · September 29, 2018

1. Objective – Python Zip Function

In this Python tutorial, we will discuss Python Zip Function. Moreover, we will discuss the built-in zip()
function in Python with the example. Also, we will understand Zip in Python and Python Unzipping Values.

So, let’s start the Python Zip Function tutorial.


Python Zip Function With Examples | Python Unzipping values

2. What is Python Zip Function?

Like we’ve said manifold before, the interpreter for Python has some types and functions built into it; these are
the ones always available to it. zip() is one such function, and we saw a brief on it when we talked Built-in
Functions. Let’s take a quick recap before we can proceed to explain this to you from scratch.

zip() is a built-in Python function that gives us an iterator of tuples. Let’s take a quick example of Python Zip
Function

1. >>> for i in zip([1,2,3],['a','b','c']):


2. print(i)

(1, ‘a’)
(2, ‘b’)
(3, ‘c’)

3. Understanding Python zip()


Like Ziploc in the real world and .zip files in the virtual one, a zip is a kind of a container. Like a .zip file holds
real files within itself, a zip holds real data within. It takes iterable elements as input and returns an iterator on
them (an iterator of tuples). It evaluates the iterables left to right.

Have a look at Python NumPy Tutorial.

a. The syntax for Python Zip Function


Python zip() function has the following syntax-

zip(*iterables)

As arguments, it can take iterables, we see. These can be built-in like the list, string, dict, and user-defined
(objects with the iter method).
b. Python Zip Function Example
 No arguments

What happens when we provide no arguments to zip()?

1. >>> set(zip())

set()
You can see that this returns an empty iterator.

 Single argument

1. >>> for i in zip([1,2,3]):


2. print(i)

(1,)
(2,)
(3,)
This returns tuples holding single values

 Multiple arguments of the same lengths

So, let’s pass this two lists of equal lengths.

>>> for i in zip([1,2,3],['a','b','c']):

1. print(i)

(1, ‘a’)
(2, ‘b’)
(3, ‘c’)
This zips elements together from each list. How about more than two?

1. >>> for i in zip([1,2,3],['a','b','c'],['#','*','$']):


2. print(i)

(1, ‘a’, ‘#’)


(2, ‘b’, ‘*’)
(3, ‘c’, ‘$’)

 Multiple arguments of different lengths

When we provide multiple lists of different lengths, it stops at the shortest one.

1. >>> set(zip([1,2],[3,4,5]))

{(1, 3), (2, 4)}


If you want to keep those, you can borrow zip_longest() from itertools.
1. >>> from itertools import zip_longest as zl
2. >>> set(zl([1,2],[3,4,5]))

{(1, 3), (2, 4), (None, 5)}

4. Unzipping Values in Python

Now we know how to zip values together. But how to unzip them? Well, we use the * character with the zip()
function.

1. >>> z=zip([1,2,3],['a','b','c'],['#','*','$'])
2. >>> a,b,c=zip(*z)
3. >>> a,b,c

((1, 2, 3), (‘a’, ‘b’, ‘c’), (‘#’, ‘*’, ‘$’))


So, this unzips the zip object z into the variables a, b, and c.

1. >>> z=zip([1,2],[3,4,5])
2. >>> a,b=zip(*z)
3. >>> a,b

((1, 2), (3, 4))


Now, notice that this dropped the element 5 because it didn’t zip into anything anyway.
So, this was all in Python Zip Function. Hope you like our explanation.

5. Conclusion – Python Zip Function

Hence, in this Python Zip tutorial, we discussed Python Zip Functions in detail. Moreover, we saw Zip in
Python with Python Zip function example and unzipping values in Python. Furthermore, while learning Python
Zip Function, if you feel any query, ask in comments.

Python eval Function – Examples & Uses


by DataFlair Team · November 15, 2018

1. Objective – Python eval Function

Today, in this Python tutorial, we will see Python eval function. Moreover, we will understand the eval
function in Python with examples. Also, we will look at uses and vulnerabilities in eval().

So, let’s start the Python eval tutorial.


Python eval Function – Examples & Uses

2. What is Python eval Function?

eval() in Python is a built-in function or method, to which we pass an expression. It parses this expression and
runs it as we execute the program. Let’s take a look at the syntax first.

a. The syntax of Python eval() Function


Observe the following syntax for eval function in Python:

1. eval(expression, globals=None, locals=None)

What does this tell us about Python eval()? What are the parameters of Python eval Function?

Before going on you must read the facts about Python Functions

b. Python eval Function with Parameters


 Expression in Python eval()- This is the string to parse and evaluate
 Globals in eval()- This is a dictionary that holds available global methods and variables, and is an
optional parameter
 Python eval Locals- This is a mapping object that holds available local methods and variables, and is an
optional parameter. We know that the standard mapping type in Python is a dictionary.

3. Python eval Example

Let’s take a simple example of Python eval() Function.

1. >>> x=7
2. >>> eval('x**2')
49

In this eval function in Python example, we initialize x to 7. We then pass a string to eval that, we expect, will
square the value of x and stuff it into x. We see that it works fine. eval in Python evaluates the expression x**2
to get to the value 49 and then prints it.
Now, let’s try another Python eval() example.

Have a look at Python Variables

1. >>> eval('[2,3,4][1]')

3
This converts the string to the list [2,3,4] and returns the value at position 1, that is, 3.

However, eval() in Python does not compile, only evaluates:

1. >>> eval('if 3>1: print("Okay")')

Traceback (most recent call last):


File “<pyshell#59>”, line 1, in <module>
eval(‘if 3>1: print(“Okay”)’)
File “<string>”, line 1
if 3>1: print(“Okay”)
^
SyntaxError: invalid syntax

4. Getting the Expression From the User

In the examples so far, we hardcoded the expression. What if we wanted to let the user provide one instead?

1. >>> expr=input('Enter an expression as x')

Enter an expression as x3*x**3+2*x**2+x+6

1. >>> x=int(input('Enter the value of x'))

Enter the value of x2

Do you know about Python Syntax

1. >>> eval(expr)

40

Here, we take the expression from the user, then we take the value of x and convert it to an integer. Finally, we
call eval() on the expression and evaluate it to reach a value of 40.

5. Vulnerabilities With Eval in Python

So this is useful, but it can also be used against us since it executes anything we pass to it(somewhat like SQL
injection). Let’s see how. The user can:
 Call a dangerous function
 Expose hidden values

Vulnerabilities With Python eval Function

a. Exploiting Eval in Python


Imagine having a function in your code that returns some kind of password or other confidential data. A user
can make a call to this function through Python eval() and make their way to the piece of sensitive data.

Clear your concepts for errors and exceptions in Python

1. >>> def let_me_in():


2. password='@dc#431'
3. print("The password is",password)
4. >>> expr=input('Enter an expression as x')

Enter an expression as xlet_me_in()

1. >>> eval(expr)

The password is @dc#431

Did you see how easy it was to extract the password from the code? All it took was one call to a function.

b. Protecting Python Eval from exploitation


Now consider you have imported the os module for some reason. How would you like a user to be able to read
and write your files, or worse, delete them? This is possible using the command os.system(‘rm -rf *’). This
could pose higher risks when working with applications like web apps and kiosk computers.
Have a look at Python Lists with the example

So what do we do? Well, for one, it is possible to pass a list of functions and variables to eval. This means it can
access only these functions and variables. We pass this as a Python eval dictionary. Confused? Take a look:

1. >>> def let_me_in():


2. password='@dc#431'
3. print("The password is",password)
4. >>> expr=input('Enter an expression as x')

Enter an expression as x3*x**3+2*x**2+x+6

1. >>> x=int(input('Enter the value of x'))

Enter the value of x2

1. >>> safe_dict={}
2. >>> safe_dict['x']=x
3. >>> eval(expr,safe_dict)

40

1. >>> expr=input('Enter an expression as x')

Enter an expression as xlet_me_in()

1. >>> eval(expr,safe_dict)

Traceback (most recent call last):


File “<pyshell#56>”, line 1, in <module>
eval(expr,safe_dict)
File “<string>”, line 1, in <module>
NameError: name ‘let_me_in’ is not defined
Do you know about Python Operators
Works fine. Now, let’s talk about the uses of eval.

6. Uses of eval in Python

While used sparingly because of its vulnerabilities, Python eval() manages to find use in some situations-

 To allow users to enter own scriptlets to allow customization of a complex system’s behavior.
 To evaluate mathematical expressions in applications instead of writing an expression parser.

7. A Final Python eval Example

So before we leave, let’s take a rather practical example of Python eval() Function.

Let’s take a tour of Python Iterator

1. >>> def double(n):


2. return n*2
3. >>> def triple(n):
4. return n*3
5. >>> choice=input('What would you like to do?')

What would you like to do?triple

1. >>> num=input('What number?')

What number?7

1. >>> choice+='('+num+')'
2. >>> eval(choice)

21
Here, we provide the user with a choice- to double or triple a number of her/his choice. We use eval to make
this happen.

So, this was all in Python eval Function Tutorial. Hope you like our explanation.

8. Conclusion – Python eval Function

Hence, we discussed the Python eval() function and how and where to use it. Moreover, we saw vulnerability
and uses of Python eval. Also, we understand Python eval() Function with the examples. Next, we will talk
about exec(). Still, if you have any confusion, comment below. We will definitely get back to you.

Python exec Function – Example and Risk


by DataFlair Team · May 27, 2019

1. Objective – Python exec

Over the days, we have begun discussing a few Python built-in functions we see commonly in use. Today, we
will see Python exec tutorial. Moreover, we will see the exact meaning of Python exec. Also, we will discuss
Python exec() example with syntax. At last, we will look at risk with exec in Python.
So, let’s start the Python exec tutorial.
Python exec Function – Example and Risk

2. What is Python exec()?

To say it again, exec() is a built-in function/ method with Python.

1. >>> type(exec)

<class ‘builtin_function_or_method’>
Let’s check the help for this.

1. >>> help(exec)

Help on built-in function exec in module builtins:


exec(source, globals=None, locals=None, /)
Execute the given source in the context of globals and locals.
The source may be a string representing one or more Python statements
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.

a. Python exec Syntax


Let’s see what this means:
The source can be a string that denotes one or more Python statements
The source can be a code object that the compile() function returns
The globals is a dictionary- the current is the default
The locals can be any kind of mapping- the current is the default; dictionary is the common mapping type with
Python
This function executes the source in the context of globals and locals
If we only mention globals, the locals are that by default

b. Using exec() in Python


We use exec() to dynamically execute Python code- this can be a string or some object code. When it is a
string, Python parses it as a set of statements and executes it if there is no syntax error. When it is object code,
Python executes it. But exec() doesn’t return a value; it returns None. Hence, we cannot use return and yield
statements outside function definitions.

3. Python exec Example

Let’s begin with a simple example of Python exec. For now, let’s skip the globals and locals parameters.

1. >>> code='a=7\nprint("a*17=",a*17)'
2. >>> exec(code)

a*17= 119

a. Dynamic Execution With User Input


If we can get the user to provide input at the time of execution, we can dynamically execute Python code. How
cool is that?

1. >>> code=input('What would you like to do today?')

What would you like to do today?[print(x**2) for x in range(7)]

1. >>> exec(code)

0
1
4
9
16
25
36

b. Python exec vs eval:


If we try doing this to create a list with Python exec:

1. >>> exec('[(x**2) for x in range(7)]')


2. >>>

Nothing happens! We must use Python eval instead:

1. >>> eval('[(x**2) for x in range(7)]')


[0, 1, 4, 9, 16, 25, 36]
Let’s discuss Python Forensics

4. Risks With Exec in Python

a. Problem in Python exec


When you give your users the liberty to execute any piece of code with the Python exec() function, you give
them a way to bend the rules. What if you have access to the os module in your session and they borrow a
command from that to run? Say you have imported os in your code.

1. >>> import os
2. >>> code=input('What would you like to do today?')

What would you like to do today?print(os.listdir())

1. >>> exec(code)

[‘DLLs’, ‘Doc’, ‘etc’, ‘hacked.dll’, ‘include’, ‘Lib’, ‘libs’, ‘LICENSE.txt’, ‘man’, ‘NEWS.txt’,
‘opencv_ffmpeg343.dll’, ‘out.log’, ‘python.exe’, ‘python3.dll’, ‘python37.dll’, ‘pythonw.exe’, ‘Scripts’,
‘share’, ‘tcl’, ‘Tools’, ‘vcruntime140.dll’]
Worse, they can corrupt or even delete all your files and directories. Consider we have a directory demo with
three text files:
In the directory four, we have another text file:

1. >>> os.chdir('\\demo') #The path of your demo folder


2. >>> os.listdir()

[‘four’, ‘one.txt’, ‘three.txt’, ‘two.txt’]


Now, what if the user runs this command:

1. >>> code=input('What would you like to do today?')

What would you like to do today?os.system(‘rm -rf *’)

1. >>> exec(code)

This will delete all your files in the current location! Since exec compiles and evaluates any expression you give
it, it is often more risqué than eval and pickle.

b. Solution of Python exec Problem


You can check which variables and methods are available to the user. Use the dir() method for this.

1. >>> dir()

[‘ annotations ’, ‘ builtins ’, ‘ doc ’, ‘ loader ’, ‘ name ’, ‘ package ’, ‘ spec ’]

1. >>> a=7
2. >>> def hello():
print("Hello") 3. >>> dir()

[‘ annotations ’, ‘ builtins ’, ‘ doc ’, ‘ loader ’, ‘ name ’, ‘ package ’, ‘ spec ’, ‘a’,


‘hello’]

1. >>> from os import *


2. >>> dir()

[‘DirEntry’, ‘F_OK’, ‘O_APPEND’, ‘O_BINARY’, ‘O_CREAT’, ‘O_EXCL’, ‘O_NOINHERIT’,


‘O_RANDOM’, ‘O_RDONLY’, ‘O_RDWR’, ‘O_SEQUENTIAL’, ‘O_SHORT_LIVED’,
‘O_TEMPORARY’, ‘O_TEXT’, ‘O_TRUNC’, ‘O_WRONLY’, ‘P_DETACH’, ‘P_NOWAIT’,
‘P_NOWAITO’, ‘P_OVERLAY’, ‘P_WAIT’, ‘R_OK’, ‘SEEK_CUR’, ‘SEEK_END’, ‘SEEK_SET’,
‘TMP_MAX’, ‘W_OK’, ‘X_OK’, ‘ annotations ’, ‘ builtins ’, ‘ doc ’, ‘ loader ’, ‘ name ’,
‘ package ’, ‘ spec ’, ‘_exit’, ‘a’, ‘abort’, ‘access’, ‘altsep’, ‘chdir’, ‘chmod’, ‘close’, ‘closerange’,
‘cpu_count’, ‘curdir’, ‘defpath’, ‘device_encoding’, ‘devnull’, ‘dup’, ‘dup2’, ‘environ’, ‘error’, ‘execl’,
‘execle’, ‘execlp’, ‘execlpe’, ‘execv’, ‘execve’, ‘execvp’, ‘execvpe’, ‘extsep’, ‘fdopen’, ‘fsdecode’,
‘fsencode’, ‘fspath’, ‘fstat’, ‘fsync’, ‘ftruncate’, ‘get_exec_path’, ‘get_handle_inheritable’,
‘get_inheritable’, ‘get_terminal_size’, ‘getcwd’, ‘getcwdb’, ‘getenv’, ‘getlogin’, ‘getpid’, ‘getppid’, ‘hello’,
‘isatty’, ‘kill’, ‘linesep’, ‘link’, ‘listdir’, ‘lseek’, ‘lstat’, ‘makedirs’, ‘mkdir’, ‘name’, ‘open’, ‘os’, ‘pardir’,
‘path’, ‘pathsep’, ‘pipe’, ‘popen’, ‘putenv’, ‘read’, ‘readlink’, ‘remove’, ‘removedirs’, ‘rename’,
‘renames’, ‘replace’, ‘rmdir’, ‘scandir’, ‘sep’, ‘set_handle_inheritable’, ‘set_inheritable’, ‘spawnl’,
‘spawnle’, ‘spawnv’, ‘spawnve’, ‘startfile’, ‘stat’, ‘stat_result’, ‘statvfs_result’, ‘strerror’,
‘supports_bytes_environ’, ‘symlink’, ‘system’, ‘terminal_size’, ‘times’, ‘times_result’, ‘truncate’,
‘umask’, ‘uname_result’, ‘unlink’, ‘urandom’, ‘utime’, ‘waitpid’, ‘walk’, ‘write’]
Let’s talk about Python Closure

c. Globals and Locals Parameters


Using the globals and locals parameters, we can restrict what variables and methods users can access. We can
either provide both, or just the globals, in which case that value suffices for both- globals and locals. At module
level, globals and locals are the same dictionary.
The globals parameter-
Let’s take an example of global and local parameter in Python exec.

1. >>> from math import *


2. >>> exec('print(dir())')

[‘ annotations ’, ‘ builtins ’, ‘ doc ’, ‘ loader ’, ‘ name ’, ‘ package ’, ‘ spec ’,


‘acos’, ‘acosh’, ‘asin’, ‘asinh’, ‘atan’, ‘atan2’, ‘atanh’, ‘ceil’, ‘copysign’, ‘cos’, ‘cosh’, ‘degrees’, ‘e’, ‘erf’,
‘erfc’, ‘exp’, ‘expm1’, ‘fabs’, ‘factorial’, ‘floor’, ‘fmod’, ‘frexp’, ‘fsum’, ‘gamma’, ‘gcd’, ‘hypot’, ‘inf’,
‘isclose’, ‘isfinite’, ‘isinf’, ‘isnan’, ‘ldexp’, ‘lgamma’, ‘log’, ‘log10’, ‘log1p’, ‘log2’, ‘modf’, ‘nan’, ‘pi’,
‘pow’, ‘radians’, ‘remainder’, ‘sin’, ‘sinh’, ‘sqrt’, ‘tan’, ‘tanh’, ‘tau’, ‘trunc’]
And now with an empty dictionary for globals:

1. >>> exec('print(dir())',{})

[‘ builtins ’]
This only lets the builtins be available to the object. Want to know more about builtins ? Check the
help for it:
1. >>> help( builtins )

Help on built-in module builtins:


NAME
builtins – Built-in functions, exceptions, and other objects.
You must read Python Function Arguments
We can confirm the unavailability of the math functions with another example:

1. >>> exec('print(tan(90))')

-1.995200412208242

1. >>> exec('print(tan(90))',{})

Traceback (most recent call last):


File “<pyshell#4>”, line 1, in
exec(‘print(tan(90))’,{})
File “”, line 1, in
NameError: name ‘tan’ is not defined
If, here, we want only the tan function to be available, we can do that too:

1. >>> exec('print(tan(90))',{'tan':tan})

-1.995200412208242
Didn’t we say it was a dictionary? Anyway, we can also call it anything else.

1. >>> exec('print(tanx(90))',{'tanx':tan})

-1.995200412208242
The globals and locals parameters-
Let’s try giving it both.

1. >>> exec('print(dir())',{'built': builtins },{'sum':sum,'iter':iter})

[‘iter’, ‘sum’]
This lets the user execute the sum() and iter() methods along with the builtins . We can also keep the user
from availing any builtins:
Let’s revise Decorators in Python

1. >>> exec('print(dir())',{'__builtins ':None},{'sum':sum,'print':print,'dir':dir})

[‘dir’, ‘print’, ‘sum’]


You can also use the built-in globals() and locals() functions for this.

1. >>> exec('print(dir())',globals(),locals())

[‘ annotations ’, ‘ builtins ’, ‘ doc ’, ‘ loader ’, ‘ name ’, ‘ package ’, ‘ spec ’,


‘acos’, ‘acosh’, ‘asin’, ‘asinh’, ‘atan’, ‘atan2’, ‘atanh’, ‘ceil’, ‘copysign’, ‘cos’, ‘cosh’, ‘degrees’, ‘e’, ‘erf’,
‘erfc’, ‘exp’, ‘expm1’, ‘fabs’, ‘factorial’, ‘floor’, ‘fmod’, ‘frexp’, ‘fsum’, ‘gamma’, ‘gcd’, ‘hypot’, ‘inf’,
‘isclose’, ‘isfinite’, ‘isinf’, ‘isnan’, ‘ldexp’, ‘lgamma’, ‘log’, ‘log10’, ‘log1p’, ‘log2’, ‘modf’, ‘nan’, ‘pi’,
‘pow’, ‘radians’, ‘remainder’, ‘sin’, ‘sinh’, ‘sqrt’, ‘tan’, ‘tanh’, ‘tau’, ‘trunc’]
So, this was all in Python exec Function. hope you like our explanation.

5. Conclusion – Exec in Python


Hence, n this Python exec tutorial, we will say that exec supports dynamic execution of Python code.
Moreover, we discussed the meaning of exec in Python. Also, we saw Python exec example. At last, we
discussed risk with exec in Python. Still, if you have any confusion, ask in the comment tab.

Python repr Function With Example | repr vs str in Python


by DataFlair Team · May 27, 2019

1. Objective – Python repr Function


Talking of built-in functions in Python, let’s take one more. Today, we will talk about Python repr,
concluding with some examples to drive the point home. Also, we will discuss Python str vs repr. Moreover, we
will see working with class objects.

So, let’s start the Python repr Function. Hope you like our explanation.

Python repr Function With Example

2. What is repr() in Python?


Let’s ask the IDLE.
What is Python repr Function

This tells us five things:

 This is a built-in function


 This takes an object
 This returns the canonical string representation of this object
 It has the following syntax:

repr(obj, /)

 It is true for many object types and most builtins that eval(repr(obj))=obj

Now, what does this last statement mean?

1. >>> s='Hello'
2. >>> eval(repr(s))

‘Hello’

1. >>> s

‘Hello’

What about an integer?

1. >>> x=7
2. >>> eval(repr(x))==x
True

Now, according to the official documentation by Python, repr() returns a string that holds a printable
representation of an object. For most types in Python, this will give you a string that yields an object with the
same value as when we pass it to eval(). For a few other types, it returns a string delimited in angle brackets.
This holds the type of object and other information like the name and address of that object.

We recommend you to read Python Method

To us, this is the repr() function. To Python, this is a class that controls what it returns for its instances via the
repr () magic method.

3. Python repr Example


Let’s get to an example of Python repr function.

1. >>> msg='Hello, world!'


2. >>> repr(msg)

“‘Hello, world!’”
A closer look at this tells us this returns ‘Hello, world!’ within double quotes. If we pass this back to eval, it
gives us:

1. >>> eval("'Hello, world!'")

‘Hello, world!’

This wouldn’t work:

1. >>> eval('Hello, world!')

Traceback (most recent call last):

File “<pyshell#16>”, line 1, in <module>

eval(‘Hello, world!’)

File “<string>”, line 1

Hello, world!

SyntaxError: unexpected EOF while parsing

This is because we don’t have a variable with that name (Hello, world!)

4. Working With Class Objects


We said repr() internally makes a call to the repr () method. Let’s try this with one of our own classes.

1. >>> class Color:


2. color='orange'
3. def repr (self):
4. return repr(self.color)
5. >>> o=Color()
6. >>> repr(o)

“‘orange'”

Here, we override the repr () method to get it to do what we want. When we say the word override, note
that Color already has an repr () method. This is because it inherits from the object class, and object has an
repr () method.

1. >>> issubclass(Color,object)

True

1. >>> dir(object)
[‘ class ’, ‘ delattr ’, ‘ dir ’, ‘ doc ’, ‘ eq ’, ‘ format ’, ‘ ge ’, ‘ getattribute ’,
‘ gt ’, ‘ hash ’, ‘__init ’, ‘ init_subclass ’, ‘ le ’, ‘ lt ’, ‘ ne ’, ‘ new ’, ‘ reduce ’,
‘ reduce_ex ’, ‘ repr ’, ‘ setattr ’, ‘ sizeof ’, ‘ str ’, ‘ subclasshook ’]

Remember when in the beginning, we said repr returns a string in angle brackets for some types? Let’s see how
and where.

1. >>> class Orange:


2. def init (self,color,size):
3. self.color=color
4. self.size=size
5. >>> o=Orange('orange',7)
6. >>> o

< main .Orange object at 0x02C6C1D0>

1. >>> print(o)

< main .Orange object at 0x02C6C1D0>

These are strings with the class name and the id of the object instance(its memory address in CPython). To print
this better, we make use of the information that the print() function makes a call to the str dunder/ method:

1. >>> class Orange:


2. def init (self,color,size):
3. self.color=color
4. self.size=size
5. def str (self):
6. return f'I am {self.size} and {self.color}'
7. >>> o=Orange('orange',7)
8. >>> o

< main .Orange object at 0x02D40E70>

1. >>> print(o)

I am 7 and orange

That was pretty cool! In Java, we would use the toString() method for this.

5. str() vs repr() in Python


The str () and repr () methods both give us strings in return. So what sets them apart?

 The goal of repr is to be unambiguous and that of str is to be readable.


 repr is kind of official and str is somewhat informal.

Take an example to ensure you understand the difference:


1. >>> s='Hello'
2. >>> print(str(s))

Hello

1. >>> print(repr(s))

‘Hello’

 The print statement and str() function make a call to str , but repr() makes on to repr .
 Any string at the interpreter prompt makes a call to str (), but an object at the prompt makes a call
to repr ().

Want to do prepration for Python Interview – Click Here >>>

Take a look:

1. >>> str(3)

‘3’

1. >>> repr(3)

‘3’

They appear the same. Okay, now take a look at this one:

1. >>> import datetime


2. >>> t=datetime.datetime.now()
3. >>> str(t) #Readable

‘2018-09-07 17:33:24.261778’

1. >>> repr(t)

‘datetime.datetime(2018, 9, 7, 17, 33, 24, 261778)’

1. >>> t

datetime.datetime(2018, 9, 7, 17, 33, 24, 261778)

Using this ‘official’ representation, we can reconstruct the object, but not with what str() gives us:

1. >>> eval('datetime.datetime(2018, 9, 7, 17, 33, 24, 261778)')

datetime.datetime(2018, 9, 7, 17, 33, 24, 261778)

1. >>> eval('2018-09-07 17:33:24.261778')

Traceback (most recent call last):


File “<pyshell#56>”, line 1, in <module>

eval(‘2018-09-07 17:33:24.261778’)

File “<string>”, line 1

2018-09-07 17:33:24.261778

SyntaxError: invalid token

Let’s take another example.

1. >>> class demo:


2. def init (self,a,b):
3. self.a=a
4. self.b=b
5. def repr (self):
6. return ' repr for demo'
7. def str (self):
8. return ' str for demo'
9. >>> d=demo(3,4)
10. >>> d

repr for demo

1. >>> print(d)

str for demo

1. >>> str(d)

‘ str for demo’

1. >>> repr(d)

‘ repr for demo’

1. >>> f'{d}'

‘ str for demo’

So, this was all in Python repr tutorial. Hope you like our explanation.

6. Conclusion – Python repr


The interactive interpreter uses repr() too in giving you the output of your expression:

result=expr; if result is not None: print repr(result)


Hence, in this Python repr tutorial, we discussed the meaning of repr in Python. Also, we looked Python repr
example and working with class objects. Moreover, we saw str vs repr in Python. Still, if you have any query
regarding Python repr tutorial, ask in the comment tab.

Python Data Structures – Lists, Tuples, Sets, Dictionaries


by DataFlair Team · May 27, 2019

1. Python Data Structures Tutorial

Earlier we have discussed Python Operators. Today, in this Python Data Structures Tutorial, we will talk
about different data structures in Python provides us with. These include Python list, Python tuple, Python set,
and Python dictionaries with their syntax and examples.

So, let’s start Python Data Structure.

Python Data Structures – Lists, Tuples, Sets, Dictionaries

2. Introduction to Python Data Structures

You can think of a data structure as a way of organizing and storing data such that we can access and modify it
efficiently. Earlier, we have seen primitive data types like integers, floats, Booleans, and strings. Now, we’ll
take a deeper look at the non-primitive Python data structures.

Let’s begin with our first Python Data Structures and lists.

3. Python List

A list in Python is a heterogeneous container for items. This would remind you of an array in C++, but since
Python does not support arrays, we have Python Lists.
a. How to Declare Python List?
To use a list, you must declare it first. Do this using square brackets and separate values with commas.

1. >>> languages=['C++','Python','Scratch']

You can put any kind of value in a list. This can be a string, a Tuple, a Boolean, or even a list itself.

1. >>> list1=[1,[2,3],(4,5),False,'No']

Note that here, we put different kinds of values in the list. Hence, a list is (or can be) heterogeneous.

b. How to Access Python List?


1. Accessing an entire list

To access an entire list, all you need to do is to type its name in the shell.

1. >>> list1

[1, [2, 3], (4, 5), False, ‘No’]

2. Accessing a single item from the list


To get just one item from the list, you must use its index. However, remember that indexing begins at 0. Let’s
first take a look at the two kinds of indexing.

 Positive Indexing– As you can guess, positive indexing begins at 0 for the leftmost/first item, and then
traverses right.

1. >>> list1[3]

False

 Negative Indexing– Contrary to positive indexing, negative indexing begins at -1 for the rightmost/last
item, and then traverses left. To get the same item form list1 by negative indexing, we use the index -2.

1. >>> type(list1[-2])

<class ‘bool’>

It is also worth noting that the index can’t be a float, it has to be an integer.

1. >>> list1[1.0]

Traceback (most recent call last):

File “<pyshell#219>”, line 1, in <module>

list1[1.0]
TypeError: list indices must be integers or slices, not float

If you face any doubt in a Python list or Python Data Structure, please comment.

3. Slicing a Python List


Sometimes, you may not want an entire list or a single item, but a number of items from it. Here, the slicing
operator [:] comes into play.

Suppose we want items second through fourth from list ‘list1’. We write the following code for this.

1. >>> list1[1:4]

[[2, 3], (4, 5), False]

Here, we wanted the items from [2,3] to False. The indices for these boundary items are 1 and 3 respectively.
But if the ending index is n, then it prints items till index n-1. Hence, we gave it an ending index of 4 here.

We can use negative indexing in the slicing operator too. Let’s see how.

1. >>> list1[:-2]

[1, [2, 3], (4, 5)]

Here, -2 is the index for the tuple (4,5).

c. A list is mutable
Mutability is the ability to be mutated, to be changed. A list is mutable, so it is possible to reassign and delete
individual items as well.

1. >>> languages [‘C+

+’, ‘Python’, ‘Scratch’]

1. >>> languages[2]='Java'
2. >>> languages

[‘C++’, ‘Python’, ‘Java’]

Of how to delete an item, we will see in section d.

d. How to Delete a Python List?


Like anything else in Python, it is possible to delete a list.

To delete an entire list, use the del keyword with the name of the list.

1. >>> list1

Traceback (most recent call last):


File “<pyshell#225>”, line 1, in <module>

list1

NameError: name ‘list1’ is not defined

But to delete a single item or a slice, you need its index/indices.

1. >>> del languages[2]


2. >>> languages

[‘C++’, ‘Python’]

Let’s delete a slice now.

1. >>> del languages[1:]


2. >>> languages

[‘C++’]

e. Reassigning a List in Python


You can either reassign a single item, a slice, or an entire list. Let’s take a new list and then reassign on it.

1. >>> list1=[1,2,3,4,5,6,7,8]

1. Reassigning a single item

1. >>> list1[0]=0
2. >>> list1

[0, 2, 3, 4, 5, 6, 7, 8]

2. Reassigning a slice

Now let’s attempt reassigning a slice.

1. >>> list1[1:3]=[9,10,11]
2. >>> list1

[0, 9, 10, 11, 4, 5, 6, 7, 8]

3. Reassigning the entire list


Finally, let’s reassign the entire list.

1. >>> list1=[0,0,0]
2. >>> list1

[0, 0, 0]
To get an even deeper look into lists, read our article on Python Lists.

Any query yet on Python Data structures, Please Comment

4. Python Tuple

This Python Data Structure is like a, like a list in Python, is a heterogeneous container for items. But the major
difference between the two (tuple and list) is that a list is mutable, but a tuple is immutable. This means that
while you can reassign or delete an entire tuple, you cannot do the same to a single item or a slice.

To declare a tuple, we use parentheses.

1. >>> colors=('Red','Green','Blue')

a. Python Tuple Packing


Python Tuple packing is the term for packing a sequence of values into a tuple without using parentheses.

1. >>> mytuple=1,2,3, #Or it could have been mytuple=1,2,3


2. >>> mytuple

(1, 2, 3)

b. Python Tuple Unpacking


The opposite of tuple packing, unpacking allots the values from a tuple into a sequence of variables.

1. >>> a,b,c=mytuple
2. >>>

print(a,b,c) 1 2 3

c. Creating a tuple with a single item


Let’s do this once again. Create a tuple and assign a 1 to it.

1. >>> a=(1)

Now, let’s call the type() function on it.

1. >>> type(a)

<class ‘int’>

As you can see, this declared an integer, not a tuple.

To get around this, you need to append a comma to the end of the first item 1. This tells the interpreter that it’s
a tuple.

1. >>> a=(1,)
2. >>> type(a)

<class ‘tuple’>

d. Accessing, Reassigning, and Deleting Items


We can perform these operations on a tuple just like we can on a list. The only differences that exist are because
a tuple is immutable, so you can’t mess with a single item or a slice.

1. >>> del a[0]

Traceback (most recent call last):

File “<pyshell#251>”, line 1, in <module>

del a[0]

TypeError: ‘tuple’ object doesn’t support item deletion

Even though this tuple has only one item, we couldn’t delete it because we used its index to delete.

For information about functions and methods on a tuple, refer to our article on Python Tuples.

5. Python Set

This is one of the important Python Data Structures. A Python set is a slightly different concept from a list or a
tuple. A set, in Python, is just like the mathematical set. It does not hold duplicate values and is unordered.
However, it is not immutable, unlike a tuple.

Let’s first declare a set. Use curly braces for the same.

1. >>> myset={3,1,2}
2. >>> myset

{1, 2, 3}

As you can see, it rearranged the elements in an ascending order.

Since a set is unordered, there is no way we can use indexing to access or delete its elements. Then, to perform
operations on it, Python provides us with a list of functions and methods like discard(), pop(), clear(), remove(),
add(), and more. Functions like len() and max() also apply on sets.

Any Doubt yet in Python Data Structures? Please Comment.

6. Python Dictionaries in

Finally, we will take a look at Python dictionaries. Think of a real-life dictionary. What is it used for? It holds
word-meaning pairs. Likewise, a Python dictionary holds key-value pairs. However, you may not use an
unhashable item as a key.
To declare a Python dictionary, we use curly braces. But since it has key-value pairs instead of single values,
this differentiates a dictionary from a set.

1. >>> mydict={1:2,2:4,3:6}
2. >>> mydict

{1: 2, 2: 4, 3: 6}

To access pairs from a Python dictionary, we use their keys as indices. For example, let’s try accessing the
value 4.

1. >>> mydict[2]

This was all about the Python Data Structures Tutorial.

7. Conclusion – Python Data Structures

Summing up for today’s Python Data Structures tutorial, we learned about various user-defined data structures
using python like lists, tuples, sets, and dictionaries. All of these have their own advantages and disadvantages.
It is highly recommended to refer to our tutorials on each of those to sharpen your axes. See you later.

 9

Python List with Examples – A Complete Python List Tutorial


by DataFlair Team · May 27, 2019

1. Python List Tutorial

In today’s tutorial, we will learn about Python list. We will discuss how to create, access, slice, and reassign list
in Python. Then we will see how to apply functions to them. Along with this, we will discuss Python List
Operations and Concatenation.

So, let’s start the Python List Tutorial.


Python List with Examples – A Complete Python List Tutorial

2. What is Python List?

Unlike C++ or Java, Python Programming Language doesn’t have arrays. To hold a sequence of values, then, it
provides the ‘list’ class. A Python list can be seen as a collection of values.

3. How to Create Python List?

To create python list of items, you need to mention the items, separated by commas, in square brackets. This is
the python syntax you need to follow. Then assign it to a variable. Remember once again, you don’t need to
declare the data type, because Python is dynamically-typed.

1. >>> colors=['red','green','blue']

A Python list may hold different types of values.

1. >>> days=['Monday','Tuesday','Wednesday',4,5,6,7.0]

A list may have python list.

1. >>> languages=[['English'],['Gujarati'],['Hindi'],'Romanian','Spanish']
2. >>> languages

[[‘English’], [‘Gujarati’], [‘Hindi’], ‘Romanian’, ‘Spanish’]

1. >>> type(languages[0])

<class ‘list’>
A list may also contain tuples or so.

1. >>> languages=[('English','Albanian'),'Gujarati','Hindi','Romanian','Spanish']
2. >>> languages[0]

(‘English’, ‘Romanian’)

1. >>> type(languages[0])

<class ‘tuple’>

1. >>> languages[0][0]='Albanian'

Traceback (most recent call last):

File “<pyshell#24>”, line 1, in <module>

languages[0][0]=’Albanian’

TypeError: ‘tuple’ object does not support item assignment

4. How to Access Python List?

To access a Python list as a whole, all you need is its name.

1. >>> days

[‘Monday’, ‘Tuesday’, ‘Wednesday’, 4, 5, 6, 7.0]

Or, you can put it in a print statement.

1. >>> languages=[['English'],['Gujarati'],['Hindi'],'Romanian','Spanish']
2. >>> print(languages)

[[‘English’], [‘Gujarati’], [‘Hindi’], ‘Romanian’, ‘Spanish’]

To access a single element, use its index in square brackets after the list’s name. Indexing begins at 0.

1. >>> languages[0]

[‘English’]

An index cannot be a float value.

1. >>> languages[1.0]

Traceback (most recent call last):

File “<pyshell#70>”, line 1, in <module>

languages[1.0]
TypeError: list indices must be integers or slices, not float

5. Slicing a Python List

When you want only a part of a Python list, you can use the slicing operator [].

1. >>> indices=['zero','one','two','three','four','five']
2. >>> indices[2:4]

[‘two’, ‘three’]

This returns items from index 2 to index 4-1 (i.e., 3)

1. >>> indices[:4]

[‘zero’, ‘one’, ‘two’, ‘three’]

This returns items from the beginning of the list to index 3.

1. >>> indices[4:]

[‘four’, ‘five’]

It returns items from index 4 to the end of the list in Python.

1. >>> indices[:]

[‘zero’, ‘one’, ‘two’, ‘three’, ‘four’, ‘five’]

This returns the whole list.

 Negative indices- The indices we mention can be negative as well. A negative index means traversal
from the end of the list.

1. >>> indices[:-2]

[‘zero’, ‘one’, ‘two’, ‘three’]

This returns item from the list’s beginning to two items from the end.

1. >>> indices[1:-2]

[‘one’, ‘two’, ‘three’]

It returns items from the item at index 1 to two items from the end.

1. >>> indices[-2:-1]

[‘four’]

This returns items from two from the end to one from the end.
1. >>> indices[-1:-2]

[] This returns an empty Python list, because the start is ahead of the stop for the traversal.

6. Reassigning a Python List (Mutable)


Python Lists are mutable. This means that you can reassign its items, or you can reassign it as a whole. Let’s
take a new list.

1. >>> colors=['red','green','blue']

a. Reassigning the whole Python list


You can reassign a Python list by assigning it like a new list.

1. >>> colors=['caramel','gold','silver','occur']
2. >>> colors

[‘caramel’, ‘gold’, ‘silver’, ‘occur’]

b. Reassigning a few elements


You can also reassign a slice of a list in Python.

1. >>> colors[2:]=['bronze','silver']
2. >>> colors

[‘caramel’, ‘gold’, ‘bronze’, ‘silver’]

If we had instead put two values to a single one in the left, see what would’ve happened.

1. >>> colors=['caramel','gold','silver','occur']
2. >>> colors[2:3]=['bronze','silver']
3. >>> colors

[‘caramel’, ‘gold’, ‘bronze’, ‘silver’, ‘occur’]

colors[2:3] reassigns the element at index 2, which is the third element.

2:2 works too.

1. >>> colors[2:2]=['occur']
2. >>> colors

[‘caramel’, ‘gold’, ‘occur’, ‘bronze’, ‘silver’]

c. Reassigning a single element


You can reassign individual elements too.
1. >>> colors=['caramel','gold','silver','occur']
2. >>> colors[3]='bronze'
3. >>> colors

[‘caramel’, ‘gold’, ‘silver’, ‘bronze’]

Now if you want to add another item ‘holographic’ to the list, we cannot do it the conventional way.

1. >>> colors[4]='holographic'

Traceback (most recent call last):

File “<pyshell#2>”, line 1, in <module>

colors[4]=’holographic’

IndexError: list assignment index out of range

So, you need to reassign the whole list for the same.

1. >>> colors=['caramel','gold','silver','bronze','holographic']
2. >>> colors

[‘caramel’, ‘gold’, ‘silver’, ‘bronze’, ‘holographic’]

7. How can we Delete a Python List?

You can delete a Python list, some of its elements, or a single element.

a. Deleting the entire Python list


Use the del keyword for the same.

1. >>> del colors


2. >>> colors

Traceback (most recent call last):

File “<pyshell#51>”, line 1, in <module>

colors

NameError: name ‘colors’ is not defined

b. Deleting a few elements


Use the slicing operator in python to delete a slice.

1. >>> colors=['caramel','gold','silver','bronze','holographic']
2. >>> del colors[2:4]
3. >>> colors
[‘caramel’, ‘gold’, ‘holographic’]

1. >>> colors[2]

‘holographic’

Now, ‘holographic’ is at position 2.

c. Deleting a single element


To delete a single element from a Python list, use its index.

1. >>> del colors[0]


2. >>> colors

[‘gold’,

‘holographic’]

8. Multidimensional Lists in Python

You can also put a list in a list. Let’s look at a multidimensional list.

1. >>> grocery_list=[['caramel','P&B','Jelly'],['onions','potatoes'],['flour','oil']]
2. >>> grocery_list

[[‘caramel’, ‘P&B’, ‘Jelly’], [‘onions’, ‘potatoes’], [‘flour’, ‘oil’]]

This is a grocery Python list with lists in it, where the lists are according to a category.

Or, you can choose to go deeper.

1. >>> a=[[[1,2],[3,4],5],[6,7]]
2. >>> a

[[[1, 2], [3, 4], 5], [6, 7]]

To access the element 4 here, we type the following code into the shell.

1. >>> a[0][1][1]

9. Concatenation of Python List

The concatenation operator works for lists as well. It lets us join two lists, with their orders preserved.

1. >>> a,b=[3,1,2],[5,4,6]
2. >>> a+b

[3, 1, 2, 5, 4, 6]
10. Python List Operations
a. Multiplication
This is an arithmetic operation. Multiplying a Python list by an integer makes copies of its items that a number
of times while preserving the order.

1. >>> a*=3
2. >>> a

[3, 1, 2, 3, 1, 2, 3, 1, 2]

However, you can’t multiply it by a float.

1. >>> a*3.0

Traceback (most recent call last):

File “<pyshell#89>”, line 1, in <module>

a*3.0

TypeError: can’t multiply sequence by non-int of type ‘float’

b. Membership
You can apply the ‘in’ and ‘not in’ operators on a Python list.

1. >>> 1 in a

True

1. >>> 2 not in a

False

11. Iterating on a list

Python list can be traversed with a for loop in python.

1. >>> for i in [1,2,3]:


2. if i%2==0:
3. print(f"{i} is composite\n")

2 is composite

12. Python List Comprehension

You can create a new list just like you would do in mathematics. To do so, type an expression followed by a for
statement, all inside square brackets. You may assign it to a variable. Let’s make a list for all even numbers
from 1 to 20.

1. >>> even=[2*i for i in range(1,11)]


2. >>> even

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Optionally, you can add an if-statement to filter out items. If we want to change this list to hold only those items
from 1 to 20 that are even and are divisible by 3, we write the following code.

1. >>> even=[2*i for i in range(1,11) if i%3==0]


2. >>> even

[6, 12, 18]

13. Built-in List Functions

There are some built-in functions in Python that you can use on python lists.

Python List Tutorial – Built-in List Functions

a. len()
It calculates the length of the list.

1. >>> len(even)

b. max()
It returns the item from the list with the highest value.
1. >>> max(even)

18

If all the items in your list are strings, it will compare.

1. >>> max(['1','2','3'])

‘3’

But it fails when some are numeric, and some are strings in python.

1. >>> max([2,'1','2'])

Traceback (most recent call last):

File “<pyshell#116>”, line 1, in <module>

max([2,’1′,’2′])

TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’

c. min()
It returns the item from the Python list with the lowest value.

1. >>> min(even)

d. sum()
It returns the sum of all the elements in the list.

1. >>> sum(even)

36

However, for this, the Python list must hold all numeric values.

1. >>> a=['1','2','3']
2. >>> sum(a)

Traceback (most recent call last):

File “<pyshell#112>”, line 1, in <module>

sum(a)

TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’


It works on floats.

1. >>> sum([1.1,2.2,3.3])

6.6

e. sorted()
It returns a sorted version of the list, but does not change the original one.

1. >>> a=[3,1,2]
2. >>> sorted(a)

[1, 2, 3]

1. >>> a

[3, 1, 2]

If the Python list members are strings, it sorts them according to their ASCII values.

1. >>> sorted(['hello','hell','Hello'])

[‘Hello’, ‘hell’, ‘hello’]

Here, since H has an ASCII value of 72, it appears first.

f. list()
It converts a different data type into a list.

1. >>> list("abc")

[‘a’, ‘b’, ‘c’]

It can’t convert a single int into a list, though, it only converts iterables.

1. >>> list(2)

Traceback (most recent call last):

File “<pyshell#122>”, line 1, in <module>

list(2)

TypeError: ‘int’ object is not iterable

g. any()
It returns True if even one item in the Python list has a True value.
1. >>> any(['','','1'])

True

It returns False for an empty iterable.

1. >>> any([])

False

h. all()
It returns True if all items in the list have a True value.

1. >>> all(['','','1'])

False

It returns True for an empty iterable.

1. >>> all([])

True

14. Built-in Methods

While a function is what you can apply on a construct and get a result, a method is what you can do to it and
change it. To call a method on a construct, you use the dot-operator(.). Python supports some built-in methods
to alter a Python list.

Python List – Built-in Methods


a. append()
It adds an item to the end of the list.

1. >>> a

[2, 1, 3]

1. >>> a.append(4)
2. >>> a

[2, 1, 3, 4]

b. insert()
It inserts an item at a specified position.

1. >>> a.insert(3,5)
2. >>> a

[2, 1, 3, 5, 4]

This inserted the element 5 at index 3.

c. remove()
It removes the first instance of an item from the Python list.

1. >>> a=[2,1,3,5,2,4]
2. >>> a.remove(2)
3. >>> a

[1, 3, 5, 2, 4]

Notice how there were two 2s, but it removed only the first one.

d. pop()
It removes the element at the specified index, and prints it to the screen.

1. >>> a.pop(3)

1. >>> a

[1, 3, 5, 4]

e. clear()
It empties the Python list.

1. >>> a.clear()
2. >>> a

[]

It now has a False value.

1. >>> bool(a)

False

f. index()
It returns the first matching index of the item specified.

1. >>> a=[1,3,5,3,4]
2. >>> a.index(3)

g. count()
It returns the count of the item specified.

1. >>> a.count(3)

h. sort()
It sorts the list in an ascending order.

1. >>> a.sort()
2. >>> a

[1, 3, 3, 4, 5]

i. reverse()
It reverses the order of elements in the Python lists.

1. >>> a.reverse()
2. >>> a

[5, 4, 3, 3, 1]

This was all about the Python lists


15. Conclusion

Woah, that was a lot, wasn’t it? Let’s make a quick revision so you don’t forget it. In this lesson on Python
Lists, we first looked at how to declare and access a list. That included slicing lists in python. Then we looked at
how to delete and reassign elements or an entire list. Next, we learned about multidimensional lists and
comprehension. We saw how to iterate on python lists, concatenate them, and also the operations that you can
perform on them. Lastly, we looked at some built-in functions and methods that you can call on lists. Hope you
enjoyed, see you again. Furthermore, if you have any query, feel free to ask in the comment section

What is Python Tuple – Creating, Functions, Methods, Operations


by DataFlair Team · February 22, 2019

1. Python Tuple Tutorial

In this Python Tuple tutorial, we will rather take a deeper look at Python tuple. First, let’s look at what a
Python tuple is and then we will discuss how to create, access, slice, delete tuple in Python. Moreover, we will
learn the functions, methods, and operations of Python tuples.

Python provides a range of constructs to deal with items. These include python lists, dictionaries, sets, tuples,
and many more. It also supports in-built functions and methods that we can apply on these constructs.

So, let’s start the Python tuple Tutorial.

What is Python Tuple – Creating, Functions, Methods, Operations

2. What is Python Tuple?

Python Tuples are like a list. It can hold a sequence of items. The difference is that it is immutable. Let’s learn
the syntax to create a tuple in Python.
3. How to Create a Python Tuple?

To declare a Python tuple, you must type a list of items separated by commas, inside parentheses. Then assign it
to a variable.

1. >>> percentages=(90,95,89)

You should use a tuple when you don’t want to change just an item in future.

a. Python Tuples Packing


You can also create a Python tuple without parentheses. This is called tuple packing.

1. >>> b= 1, 2.0, 'three'

b. Python Tuples Unpacking


Python tuple unpacking is when you assign values from a tuple to a sequence of variables in python.

1. >>> percentages=(99,95,90,89,93,96)
2. >>> a,b,c,d,e,f=percentages
3. >>> c

90

You can do the same to a list.

c. Creating a tuple with a single item


Until now, we have seen how easy it is to declare a Python tuple. But when you do so with just one element, it
may create some problems. Let’s take a look at it.

1. >>> a=(1)
2. >>> type(a)

<class ‘int’>

Wasn’t the type() method supposed to return class ‘tuple’?

To get around this, we add a comma after the item.

1. >>> a=(1,)
2. >>> type(a)

<class ‘tuple’>

Problem solved. And as we saw in tuple packing, we can skip the parentheses here.

1. >>> a=1,
2. >>> type(a)
<class ‘tuple’>

Also, like a list, a Python tuple may contain items of different types.

1. >>> a=(1,2.0,'three')

4. How to Access Python Tuple?

a. Accessing the entire tuple


To access a tuple in python, just type its name.

1. >>>

percentages (90, 95, 89)

Or, pass it to the print statement.

1. >>> print(percentages)

(90, 95, 89)

b. Accessing a single item


To get a single item from a Python tuple, use its index in square brackets. Indexing begins at 0.

1. >>> percentages[1]

95

5. Slicing a Tuple in Python


If you want a part(slice) of a tuple in Python, use the slicing operator [].

1. >>> percentages=(99,95,90,89,93,96)

a. Positive Indices
When using positive indices, we traverse the list from the left.

1. >>> percentages[2:4]

(90, 89)

This prints out items from index 2 to index 3 (4-1) (items third to fourth).

1. >>> percentages[:4]

(99, 95, 90, 89)


This prints out items from the beginning to the item at index 3.

1. >>> percentages[4:]

(93, 96)

This prints out items from index 4 to the end of the list.

1. >>> percentages[2:2]

()

However, this returns an empty Python tuple.

b. Negative indexing
Now, let’s look at negative indexing. Unlike positive indexing, it begins traversing from the right.

1. >>> percentages[:-2]

(99, 95, 90, 89)

This prints out the items from the tuple’s beginning to two items from the end.

1. >>> percentages[-2:]

(93, 96)

This prints out items from two items from the end to the end.

1. >>> percentages[2:-2]

(90, 89)

This prints out items from index 2 to two items from the end.

1. >>> percentages[-2:2]

()

This last piece of code, however, returns an empty tuple. This is because the

start(-2) is behind the end(2) in this case.

Lastly, when you provide no indices, it prints the whole Python tuple.

1. >>> percentages[:]

(99, 95, 90, 89, 93, 96)

6. Deleting a Python Tuple


As we discussed above, a Python tuple is immutable. This also means that you can’t delete just a part of it. You
must delete an entire tuple, if you may.

1. >>> del percentages[4]

Traceback (most recent call last):

File “<pyshell#19>”, line 1, in <module>

del percentages[4]

TypeError: ‘tuple’ object doesn’t support item deletion

So, deleting a single element didn’t work. Let’s try deleting a slice.

1. >>> del percentages[2:4]

Traceback (most recent call last):

File “<pyshell#20>”, line 1, in <module>

del percentages[2:4]

TypeError: ‘tuple’ object does not support item deletion

As you can see, that didn’t work either. Now, let’s try deleting the entire tuple.

1. >>> del percentages


2. >>> percentages

Traceback (most recent call last):

File “<pyshell#40>”, line 1, in <module>

percentages

NameError: name ‘percentages’ is not defined

We see that the Python tuple has successfully been deleted.

7. Reassigning Tuples in Python

As we discussed, a Python tuple is immutable. So let’s try changing a value. But before that, let’s take a new
tuple with a list as an item in it.

1. >>> my_tuple=(1,2,3,[4,5])

Now, let’s try changing the list [4,5]. Its index is 3.

1. >>> my_tuple[3]=6
Traceback (most recent call last):

File “<pyshell#43>”, line 1, in <module>

my_tuple[3]=6

TypeError: ‘tuple’ object does not support item assignment

See, that failed. Now how about changing an element from the same list]?

1. >>> my_tuple[3][0]=6
2. >>> my_tuple

(1, 2, 3, [6, 5])

This worked without a flaw. So we can see that while tuples are immutable, a mutable item that it holds may be
reassigned.

8. Python Tuple Functions

A lot of functions that work on lists work on tuples too. A function applies on a construct and returns a result. It
does not modify the construct. Let’s see what we can do.

Python Tuple Tutorial – Python Tuple Functions

a. len()
Like a list, a Python tuple is of a certain length. The len() function returns its length.

1. >>> my_tuple
(1, 2, 3, [6, 5])

1. >>> len(my_tuple)

It returned 4, not 5, because the list counts as 1.

b. max()
It returns the item from the tuple with the highest value.

We can’t apply this function on the tuple my_tuple, because ints cannot be compared to a list. So let’s take yet
another tuple in Python.

1. >>> a=(3,1,2,5,4,6)
2. >>> max(a)

Let’s try that on strings.

1. >>> max(('Hi','hi','Hello'))

‘hi’

‘hi’ is the greatest out of these, because h has the highest ASCII value among h and H.

But you can’t compare an int and a string.

1. >>> max(('Hi',9))

Traceback (most recent call last):

File “<pyshell#59>”, line 1, in <module>

max((‘Hi’,9))

TypeError: ‘>’ not supported between instances of ‘int’ and ‘str’

c. min()
Like the max() function, the min() returns the item with the lowest values.

1. >>> min(a)

As you can see, 1 is the smallest item in this Python tuple.

d. sum()
This function returns the arithmetic sum of all the items in the tuple.

1. >>> sum(a)

21

However, you can’t apply this function on a tuple with strings.

1. >>> sum(('1','2','3'))

Traceback (most recent call last):

File “<pyshell#57>”, line 1, in <module>

sum((‘1′,’2′,’3’))

TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

e. any()
If even one item in the tuple has a Boolean value of True, then this function returns True. Otherwise, it returns
False.

1. >>> any(('','0',''))

True

The string ‘0’ does have a Boolean value of True. If it was rather the integer 0, it would’ve returned False.

1. >>> any(('',0,''))

False

f. all()
Unlike any(), all() returns True only if all items have a Boolean value of True. Otherwise, it returns False.

1. >>> all(('1',1,True,''))

False

g. sorted()
This function returns a sorted version of the tuple. The sorting is in ascending order, and it doesn’t modify the
original tuple in Python.

1. >>> sorted(a)

[1, 2, 3, 4, 5, 6]
h. tuple()
This function converts another construct into a Python tuple. Let’s look at some of those.

1. >>> list1=[1,2,3]
2. >>> tuple(list1)

(1, 2, 3)

1. >>> string1="string"
2. >>> tuple(string1)

(‘s’, ‘t’, ‘r’, ‘i’, ‘n’, ‘g’)

How well would it work with sets?

1. >>> set1={2,1,3}
2. >>> tuple(set1)

(1, 2, 3)

1. >>> set1

{1, 2, 3}

As we can see, when we declared a set as 2,1,3, it automatically reordered itself to 1,2,3. Furthermore, creating
a Python tuple from it returned the new tuple in the new order, that is, ascending order.

9. Python Tuple Methods


A method is a sequence of instructions to perform on something. Unlike a function, it does modify the construct
on which it is called. You call a method using the dot operator in python. Let’s learn about the two in-built
methods of Python.

a. index()
This method takes one argument and returns the index of the first appearance of an item in a tuple. Let’s take a
new tuple.

1. >>> a=(1,2,3,2,4,5,2)
2. >>> a.index(2)

As you can see, we have 2s at indices 1, 3, and 6. But it returns only the first index.

b. count()
This method takes one argument and returns the number of times an item appears in the tuple.
1. >>> a.count(2)

10. Python Tuple Operations

Now, we will look at the operations that we can perform on tuples in Python.

a. Membership
We can apply the ‘in’ and ‘not in’ operators on items. This tells us whether they belong to the tuple.

1. >>> 'a' in

tuple("string") False

1. >>> 'x' not in tuple("string")

True

b. Concatenation
Like we’ve previously discussed on several occasions, concatenation is the act of joining. We can join two
tuples using the concatenation operator ‘+’.

1. >>> (1,2,3)+(4,5,6)

(1, 2, 3, 4, 5, 6)

Other arithmetic operations do not apply on a tuple.

c. Logical
All the logical operators (like >,>=,..) can be applied on a tuple.

1. >>> (1,2,3)>(4,5,6)

False

1. >>> (1,2)==('1','2')

False

As is obvious, the ints 1 and aren’t equal to the strings ‘1’ and ‘2’. Likewise, it returns False.

d. Identity
Remember the ‘is’ and ‘is not’ operators we discussed about in our tutorial on Python Operators? Let’s try that
on tuples.
1. >>> a=(1,2)
2. >>> (1,2) is a

False

That did not make sense, did it? So what really happened? Well, in Python, two tuples or lists do not have the
same identity. In other words, they are two different tuples or lists. As a result, it returns False.

11. Iterating on a Python Tuple

You can iterate on a Python tuple using a for loop like you would iterate on a list.

1. >>> for i in (1,3,2):


2. print(i)

1
3
2

12. Nested Tuples in Python

Finally, we will learn about nesting tuples. You may remember how we can nest lists. Due to the similarities of
a tuple to a list, we do the same with tuples.

1. >>> a=((1,2,3),(4,(5,6)))

Suppose we want to access the item 6. For that, since we use indices, we write the following code.

1. >>> a[1][1][1]

Python tuple may also contain other constructs, especially, lists. After all, it is a collection of items, and items
can be anything.

1. >>> (1,2,[3,4])

(1, 2, [3, 4])

This was all on Python Tuple Tutorial. Hope you like our explanation.

13. Conclusion

Hence, today, we learned about creating tuples in Python. In that, we looked at tuple packing and unpacking,
and how to create a tuple with just one item. Then we talked about how to access, slice, delete, and reassign a
tuple. After that, we looked at the inbuilt functions and methods that we can call on a tuple. Lastly, we learned
about the operations we can perform on a Python tuple, how to iterate on it, and nested tuples. Try them in the
shell and leave your honest comments.

Python Tuples vs Lists – Comparison Between Lists and Tuples


by DataFlair Team · May 27, 2019

1. Python Tuples vs Lists – Objective

In our previous python tutorials, we’ve seen tuples in python and lists in python. Both are heterogeneous
collections of python objects. But which one do you choose when you need to store a collection? To answer this
question, we first get a little deeper into the two constructs and then we will study comparison between python
tuples vs lists.

So, let’s start Python Tuples vs Lists Tutorial.

Python Tuples vs Lists – Comparison between Lists and Tuples

2. A Revision of Tuples in Python

Before comparing tuples and lists, we should revise the two. First, we look at a tuple.
A tuple is a collection of values, and we declare it using parentheses. However, we can also use tuple packing to
do the same, and unpacking to assign its values to a sequence of variables.

1. >>> numbers=(1,2,'three')
2. >>> numbers=4,5,6
3. >>> a,b,c=numbers
4. >>> print(numbers,a,b,c,type(numbers))

(4, 5, 6) 4 5 6 <class ‘tuple’>

A tuple is returned when we call the method localtime().

1. >>> import time


2. >>> time.localtime()
time.struct_time(tm_year=2018, tm_mon=1, tm_mday=1, tm_hour=23, tm_min=1, tm_sec=59, tm_wday=0,
tm_yday=1, tm_isdst=0)

To access a tuple, we use indexing, which begins at 0.

1. >>> numbers[1]

We can also slice it to retrieve a part of it.

1. >>> numbers[:-1]

(4, 5)

Finally, we can delete an entire tuple.

1. >>> del numbers


2. >>> numbers

Traceback (most recent call last):

File “<pyshell#40>”, line 1, in <module>

numbers

NameError: name ‘numbers’ is not defined

We also learned some functions and methods on tuples and lists. You must read our tutorials on them for more
insight.

3. A Revision of Lists in Python

Unlike in C++, we don’t have arrays to work with in Python. Here, we have a list instead.

We create lists using square brackets.

1. >>>

colors=['red','blue','green'] We can

slice lists too.

1. >>> colors[-2:]

[‘blue’, ‘green’]

Then, we learned how to reassign and delete them.

1. >>> colors[0]='pink'
2. >>> colors

[‘pink’, ‘blue’, ‘green’]


1. >>> del colors[0]
2. >>> colors[0]

‘blue’

1. >>> del colors


2. >>> colors

Traceback (most recent call last):

File “<pyshell#52>”, line 1, in <module>

colors

NameError: name ‘colors’ is not defined

Now that we’ve refreshed our memories, we can proceed to differentiate between python tuples vs lists.

4. Python tuples vs lists – Mutability

The major difference between tuples and lists is that a list is mutable, whereas a tuple is immutable. This means
that a list can be changed, but a tuple cannot.

a. A List is Mutable
Let’s first see lists. Let’s take a new list for exemplar purposes.

1. >>> list1=[0,1,2,3,4,5,6,7]

Now first, we’ll try reassigning an element of a list. Let’s reassign the second element to hold the value 3.

1. >>> list1[1]=3
2. >>> list1

[0, 3, 2, 3, 4, 5, 6, 7]

Again, let’s see how we can reassign the entire list.

1. >>> list1=[7,6,5,4,3,2,1,0]
2. >>> list1

[7, 6, 5, 4, 3, 2, 1, 0]

It worked, great.

Now, we will delete just one element from the list.

1. >>> del list1[1]


2. >>> list1

[7, 5, 4, 3, 2, 1, 0]
This was easy, but could we delete a slice of the list? Let’s try it.

1. >>> del list1[3:]


2. >>> list1

[7, 5, 4]

We can access a slice the same way. Can we reassign a slice?

1. >>> nums=[1,2,3,4,5]
2. >>> nums[1:3]=[6,7,8]
3. >>> nums

[1, 6, 7, 8, 4, 5]

Indeed, we can. Finally, let’s try deleting the entire list.

1. >>> del list1


2. >>> list1

Traceback (most recent call last):

File “<pyshell#67>”, line 1, in <module>

list1

NameError: name ‘list1’ is not defined

The list doesn’t exist anymore.

b. A Tuple is Immutable
Now, let’s try doing the same things to a tuple. We know that a tuple is immutable, so some of these operations
shouldn’t work. We’ll take a new tuple for this purpose.

1. >>> mytuple=0,1,2,3,4,5,6,7

First, let’s try reassigning the second element.

1. >>> mytuple[1]=3

Traceback (most recent call last):

File “<pyshell#70>”, line 1, in <module>

mytuple[1]=3

TypeError: ‘tuple’ object does not support item assignment

As you can see, a tuple doesn’t support item assignment.


However, we can reassign an entire tuple.

1. >>> mytuple=2,3,4,5,6
2. >>> mytuple

(2, 3, 4, 5, 6)

Next, let’s try slicing a tuple to access or delete it.

1. >>> mytuple[3:]

(5, 6)

1. >>> del mytuple[3:]

Traceback (most recent call last):

File “<pyshell#74>”, line 1, in <module>

del mytuple[3:]

TypeError: ‘tuple’ object does not support item deletion

As is visible, we can slice it to access it, but we can’t delete a slice. This is because it is immutable.

Can we delete a single element?

1. >>> del mytuple[3]

Traceback (most recent call last):

File “<pyshell#75>”, line 1, in <module>

del mytuple[3]

TypeError: ‘tuple’ object doesn’t support item deletion

Apparently, the answer is no.

Finally, let’s try deleting the entire tuple.

1. >>> del mytuple


2. >>> mytuple

Traceback (most recent call last):

File “<pyshell#77>”, line 1, in <module>

mytuple

NameError: name ‘mytuple’ is not defined


So, here, we conclude that you can slice a tuple, reassign it whole, or delete it whole.

But you cannot delete or reassign just a few elements or a slice.

Let us proceed with more differences between python tuples vs lists.

5. Functions

Some python functions apply on both, these are- len(), max(), min(), sum(), any(), all(), sorted(). We’ll take just
one example here for both containers.

1. >>> max((1,3,-1))

1. >>> max([1,3,-1])

6. Methods

Lists and tuples share the index() and count() methods. But other than those, there are a few methods that apply
to lists. These are- append(), insert(), remove(), pop(), clear(), sort(), and reverse(). Let’s take an example of one
of these.

1. >>> [1,3,2].index(3)

1. >>> (1,3,2).index(3)

1
To get an insight into all of these methods and functions we mentioned, you should refer to our articles on lists
and tuples.

7. Tuples in a List

We can store tuples in a list when we want to.

1. >>> mylist=[(1,2,3),(4,5,6)]
2. >>> type(mylist)

<class ‘list’>

1. >>> type(mylist[1])

<class ‘tuple’>

But when would we need to do this? Take an example.

[(1, ‘ABC’), (2, ‘DEF’), (3, ‘GHI’)]


8. Lists in a Tuple

Likewise, we can also use a tuple to store lists. Let’s see how.

1. >>> mytuple=([1,2],[3,4],[5,6])

9. Nested Tuples

A tuple may hold more tuples, and this can go on in more than two dimensions.

1. >>> mytuple=((1,2),(3,(4,5),(6,(7,(8,9)))))

To access the element with the value 8, we write the following code.

1. >>> mytuple[1][2][1][1][0]

10. Nested Lists

Similarly, a list may hold more lists, in as many dimensions as you want.

1. >>> mylist=[[1,2],[3,4]]
2. >>> myotherlist=[[1,2],[3,[4,5]]]

To access the element with the value 5, we write the following code.

1. >>> myotherlist[1][1][1]

11. When to Use Which

Use a tuple when you know what information goes in the container that it is. For example, when you want to
store a person’s credentials for your website.

1. >>> person=('ABC','admin','12345')

But when you want to store similar elements, like in an array in C++, you should use a list.

1. >>> groceries=['bread','butter','cheese']

Note that this does not say that a list can only contain homogeneous values. Also, you can’t use a list as a key
for a dictionary. This is because only immutable values can be hashed. Hence, we can only set immutable
values like tuples as keys. But if you still want to use a list as a key, you must turn it into a tuple first.

So, this was all


Python Collections Module – Python Counter, DefaultDict, OrderedDict,
NamedTuple
by DataFlair Team · November 15, 2018

1. Collections in Python

Over the last few days, we opened ourselves up to three subclasses of the class ‘dict’, and function
namedtuple(). In this Python Collections Module tutorial, we will study Python Counter, Python DefaultDict,
Python OrderedDict, and Python NamedTuple with their subtypes, syntax and examples.

So, let’s start Python Collection Modules.

Python Collections Module – Introduction

2. Introduction to Python Collections Module

The ‘collections’ module in Python that implements special container datatypes. These provide alternatives to
Python’s general-purpose built-in containers.

Like we said, all three of these are subclasses of Python class ‘dict’.

1. >>> from collections import Counter,defaultdict,OrderedDict,namedtuple


2. >>> issubclass(Counter,dict) and issubclass(defaultdict,dict) and issubclass(OrderedDict,dict)

True

1. >>> type(namedtuple)

<class ‘function’>
To use any of its functionality, we must first import it.
1. >>> import collections

Python Collections Module

Lets’ see all the collections of Python

3. Python Collections Counter

The first thing we discuss in this Python Collection Modeule tutorial, is counter in python collections
module. Python counter is a container that keeps count of the number of occurrences of any value in the
container. It counts hashable objects. Let’s take an example.

a. Python Counter – Syntax


To define a Python counter, we use the Counter() factory function. To it, we can pass a container like Python
list or a tuple, or even a string or a dictionary. We may also use keyword arguments.

1. >>> from collections import Counter


2. >>> c=Counter({'a':3,'b':2,'c':1})
3. >>> c

Counter({‘a’: 3, ‘b’: 2, ‘c’: 1})

1. >>> c=Counter('Hello')
2. >>> c

Counter({‘l’: 2, ‘H’: 1, ‘e’: 1, ‘o’: 1})

1. >>> c=Counter(a=3,b=2,c=1)
2. >>> c

Counter({‘a’: 3, ‘b’: 2, ‘c’: 1})


b. Updating a Python Counter
To declare an empty counter in python, and then populate it, we use the update() method.

1. >>> c=Counter()
2. >>> c.update('bfg')
3. >>> c

Counter({‘b’: 1, ‘f’: 1, ‘g’: 1})

c. Accessing Counts in python


To get a value’s count, we pass it as an index to the counter we defined.

1. >>> c['f']

1. >>> c['h']

As you can see, it does not raise a KeyError.

What are Python Errors and How to Handle Python Errors?

The elements() method returns a python iterator for the values in the container.

1. >>> for i in c.elements():


2. print(f"{i}: {c[i]}")

b: 1

f: 1

g: 1

We can also call the most_common() method to get the n most-common values. These are the ones with the
highest frequencies.

1. >>> c=Counter('hello')
2. >>> c

Counter({‘l’: 2, ‘h’: 1, ‘e’: 1, ‘o’: 1})

1. >>> c.most_common(2)

[(‘l’, 2), (‘h’, 1)]

d. Python Counter Arithmetic


We can also perform arithmetic on python counters.
1. >>> c1=Counter('hello')
2. >>> c2=Counter('help')
3. >>> c1+c2

Counter({‘l’: 3, ‘h’: 2, ‘e’: 2, ‘o’: 1, ‘p’: 1})

1. >>> c1&c2

Counter({‘h’: 1, ‘e’: 1, ‘l’: 1})

4. Python DefaultDict

Python DefaultDict collection, lets us provide a default value for keys. We define it using the defaultdict()
factory function, which takes another function as an argument. This function returns a default value for it.

a. Python DefaultDict – Syntax


To define Python defaultdict, we use the factory function defaultdict().

1. >>> from collections import defaultdict


2. >>> d=defaultdict(lambda :35)
3. >>> d['Ayushi']=95
4. >>> d['Bree']=89
5. >>> d['Leo']=90.5
6. >>> d['Adam']

35
Here, we did not initialize ‘Adam’. So, it took 35, because that’s what our function returns to defaultdict(). We
can also check the default value with the missing () method.

1. >>> d. missing ('Adam')

35

b. Using a Type as a Default Factory


We can tell the interpreter what type of values we’re going to work with. We do this by passing it as an
argument to defaultdict().

1. >>> d=defaultdict(list)
2. >>> for i,j in [('a',(1,2)),('b',(3,4)),('c',(5,6))]:
3. d[i].append(j)
4. >>> d

defaultdict(<class ‘list’>, {‘a’: [(1, 2)], ‘b’: [(3, 4)], ‘c’: [(5, 6)]})

5. Python OrderedDict

Python OderDict, remembers the order in which the key-value pairs were added. Let’s take python ordereddict
example.
1. >>> from collections import OrderedDict
2. >>> o=OrderedDict()
3. >>> o['a']=3
4. >>> o['c']=1
5. >>> o['b']=4
6. >>> o

OrderedDict([(‘a’, 3), (‘c’, 1), (‘b’, 4)])

a. Move_to_end()
We’ll take a look at two methods in python orderedDict. The first we discuss is move_to_end(). It lets us move
a key-value pair either to the end, or to the front.

1. >>> o.move_to_end('c')
2. >>> o

OrderedDict([(‘a’, 3), (‘b’, 4), (‘c’, 1)])

1. >>> o.move_to_end('c',last=False)
2. >>> o

OrderedDict([(‘c’, 1), (‘a’, 3), (‘b’, 4)])

b. Popitem()
This method lets us pop a key-value pair out of the container, and then displays it.

1. >>> o.popitem()

(‘b’, 4)

1. >>> o.popitem(last=False)

(‘c’, 1)

1. >>> o

OrderedDict([(‘a’, 3)])

6. Python NamedTuple

Finally, in python collections module we discuss Python NamedTuple. This is a container that

lets us access elements using names/labels.

1. >>> from collections import namedtuple


2. >>> colors=namedtuple('colors','r g b')
3. >>> red=colors(r=255,g=0,b=0)
a. Accessing Elements
To access these elements, we use the dot Python operator.

1. >>> red.r

255

1. >>> red.g

1. >>> red.b

Or, we could just use indices.

1. >>> red[0]

255
We can also use the getattr() function.

1. >>> getattr(red,'r')

255
Python namedtuple is immutable. So, you can’t reassign a value directly.

1. >>> red.r=3
2. Traceback (most recent call last):
3. File "<pyshell#95>", line 1, in <module>
4. red.r=3

AttributeError: can’t set attribute

b. Converting into Python Dictionary


To convert a namedtuple into Python dictionary, we use the _asdict() method.

1. >>> red._asdict()

OrderedDict([(‘r’, 255), (‘g’, 0), (‘b’, 0)])

c. Converting an Iterable into a namedtuple


The _make() method lets us create a namedtuple from Python list and the format we specified.

1. >>> colors._make(['1','2','3'])

colors(r=’1′, g=’2′, b=’3′)


Follow this link to know more about Python Iterables.

d. Creating a namedtuple from the dictionary


To use a dictionary to make python namedtuple, we use this code:

1. >>> colors(**{'r':255,'g':0,'b':0})

colors(r=255, g=0, b=0)

e. Checking What Fields Belong to the Tuple


For this, we have the _fields attribute.

1. >>> red._fields

(‘r’, ‘g’, ‘b’)

f. Changing a Value
Like we said, Python namedtuples are immutable. But to change a value, we can use the _replace() method.

1. >>> red._replace(g=3)

colors(r=255, g=3, b=0)

So, this was all about Pythons Collections Module Tutorial. Hope you like our explanation.

7. Conclusion
Now that we’ve discussed all four Python collections module- Counter, defaultdict, OrderedDict, and namedtuple with
their syntax, methods, and examples of python collections module. We can move on to other things. Hope you had fun, If
you had any query, write us in a comment box we surely get back to you.

Python Counter with Example & Python Collections Type


by DataFlair Team · May 27, 2019

1. Python Counter Tutorial


Earlier, we discussed three classes from Python module collections. Today, we’ll talk about another such
class- Python Counter. Here, we will study initializing, updating, accessing, and reassigning counters in Python.
Moreover, we will learn Python counter list, loops and arithmetic.

So, let’s start the Python Counter Tutorial.


Python Counter with Example & Python Collections Type

2. Introduction to Python Counter

Python Counter, like the other three containers we mentioned above, is a subclass of ‘dict’. It keeps a count of
the number of occurrences of any value in the container. Simply speaking, if you add the value ‘hello’ thrice in
the container, it will remember that you added it thrice. So, Counter counts hashable objects in Python. Lets
see this Python Counter example.

1. >>> from collections import Counter


2. >>> c=Counter(['a','b','c','a','b','a'])
3. >>> c

Counter({‘a’: 3, ‘b’: 2, ‘c’: 1})

1. >>> c['a']

1. >>> issubclass(Counter,dict)

True
Now, let’s take a look at python counter syntax.

3. Initializing a Python Counter

To initialize or define a counter in python, we use the counter factory function. Yet, in that, we can do it in three
ways:

a. Using a List or Similar Containers


We can pass Python list of values to Counter(). Every time it encounters a value again, it raises its count by 1.

1. >>> c=Counter(['a','b','c','a','b','a'])
2. >>> c

Counter({‘a’: 3, ‘b’: 2, ‘c’: 1})


As you can see, it could recognize that there are three ‘a’s in the list in python, two ‘b’s, and one ‘c’.
We can also use Python tuple.

1. >>> c=Counter(('a','b','c','a','b','a'))
2. >>> c

Counter({‘a’: 3, ‘b’: 2, ‘c’: 1})


Or, you can pass it Python string.

1. >>> c=Counter("Hello")
2. >>> c

Counter({‘l’: 2, ‘H’: 1, ‘e’: 1, ‘o’: 1})


Python string is a container too, remember? Also, it displays the counts in a descending order. But when we use
a Set, it only holds every value once. So, it does not make sense to use Counter() with Python Set.

1. >>> c=Counter({'a','b','c','a','b','a'})
2. >>> c

Counter({‘a’: 1, ‘c’: 1, ‘b’: 1})

b. Using a Python Dictionary


We can also manually tell the Python Counter the count of values, using a dictionary in Python.

1. >>> c=Counter({'a':3,'b':2,'c':1})
2. >>> c

Counter({‘a’: 3, ‘b’: 2, ‘c’: 1})

c. Using Keyword Arguments


Finally, we can use keyword arguments to manually tell Counter() the count.

1. >>> c=Counter(a=3,b=2,c=1)
2. >>> c

Counter({‘a’: 3, ‘b’: 2, ‘c’: 1})

4. Updating a Python Counter

Like it is with every other container, we can first declare an empty Python Counter and then populate it. We
perform the update calling the update() method on the Counter.

1. >>> d=Counter()
2. >>>
d.update("Hello") 3. >>>
d

Counter({‘l’: 2, ‘H’: 1, ‘e’: 1, ‘o’: 1})


We updated it once; we can update it further, in a different way if we want.

1. >>> d.update({'e':2,'o':4})
2. >>> d

Counter({‘o’: 5, ‘e’: 3, ‘l’: 2, ‘H’: 1})


Here, we told Python Counter that we’re adding two more ‘e’s and four more ‘o’s. Then, when we accessed it, it
printed the counts in a descending order.

5. Accessing Counts in Python

We can access the count for a particular value simply by using it as an index to the Python Counter we defined.

1. >>> d['e']

3
Let’s try displaying the counts of values in a string, with Python counter that takes a different string as an
argument.

1. >>> e=Counter("Hello")
2. >>> for i in "Help":
3. print(f"{i}: {e[i]}")
4. H: 1
5. e: 1
6. l: 2
7. p: 0

From this, we interpret that in Python Counter e, ‘H’ has a count of 1, ‘e’ has a count of 1, ‘l’ has 2, and ‘p’ has
none(hence, 0).
From this, we conclude that if a key doesn’t exist, it will consider its count to be 0, instead of raising a
KeyError.

1. >>> e['q']

To compare, let’s also see how this would fair in a regular dictionary.

1. >>> dict1={'H':1,'e':1,'l':2,'o':1}
2. >>> dict1['p']
3. Traceback (most recent call last):
4. File "<pyshell#36>", line 1, in <module>
5. dict1['p']

KeyError: ‘p’

a. The elements() Method


Or, we could use the elements() method, which returns an iterator object for the values in the Counter. We can
use this with a Python for-loop.

1. >>> e=Counter({'a':3,'b':2,'c':1,'d':0})
2. >>> for i in e.elements():
3. print(f"{i}: {e[i]}")
4. a: 3
5. a: 3
6. a: 3
7. b: 2
8. b: 2
9. c: 1
10. >>> e.elements()

<itertools.chain object at 0x06336390>


We’ll discuss python itertools in a later lesson.

b. Accessing the Most Common Values


To get n most-common values (the ones with the highest frequencies), we call the method most_common().

1. >>> e.most_common(2)

[(‘a’, 3), (‘b’, 2)]

1. >>> e.most_common(4)

[(‘a’, 3), (‘b’, 2), (‘c’, 1), (‘d’, 0)] When we call it without any argument, however, we get all the items. So, it is
the same as calling it with an argument with a value equal to the number of elements in Python counter.

1. >>> e.most_common()

[(‘a’, 3), (‘b’, 2), (‘c’, 1), (‘d’, 0)]

6. Reassigning Counts in Python

Of course, Python Counters aren’t immutable. You can reassign a count the following way:

1. >>> e['e']=5
2. >>> e

Counter({‘e’: 5, ‘l’: 2, ‘H’: 1, ‘o’: 1})


To clear a Python counter, we use clear().

1. >>> b.clear()
2. >>> b

Counter()
7. Python Counter Arithmetic

Finally, we’ll discuss some Counter arithmetic in Python.


To aggregate results, we can perform arithmetic and set operations on Python Counters. Let’s take two sample
Counters for exemplary purposes.

1. >>> a=Counter({'a':3,'b':2,'c':1})
2. >>> b=Counter({'c':3,'d':2,'e':1})

Now, sit back and watch it unfold.

1. >>> a+b

Counter({‘c’: 4, ‘a’: 3, ‘b’: 2, ‘d’: 2, ‘e’: 1})

1. >>> a-b

Counter({‘a’: 3, ‘b’: 2})

1. >>> b-a

Counter({‘c’: 2, ‘d’: 2, ‘e’: 1})


Here, a-b does not have ‘c’, because 1-3=-2. A negative count does not mean anything. Likewise, b-a has ‘c’
with a count of 2, because 3-1=2. We can also do this calling the subtract() method.

1. >>> a.subtract(b)
2. >>> a

Counter({‘a’: 3, ‘b’: 2, ‘e’: -1, ‘c’: -2, ‘d’: -2})


This way, it gives us negative counts if it has to.
Now, look at the following code:

1. >>> a. add (b)

Counter({‘a’: 3, ‘b’: 2, ‘c’: 1})

1. >>> a&b

Counter({‘c’: 1})

1. >>> a|b

Counter({‘a’: 3, ‘c’: 3, ‘b’: 2, ‘d’: 2, ‘e’: 1})


Here, a|b has a count of 3 for ‘c’, because that is what OR does.

1. >>> a=Counter({'e':-1})
2. >>> -a

Counter({‘e’: 1})
If you’ve forgotten about these operators, read up on Python Operators.
Check out the result for dir(Counter), and try to apply all of those methods to your Counters in Python.
8. Conclusion

Python Counter is a container that keeps track of the number of occurrences of a value. Today, we looked at
methods like update(), most_common(), clear(), elements(), and subtract(). In our next lesson, we’ll revise all
these four classes in brief.

Python Namedtuple – Working and Benefits of Namedtuple in Python


by DataFlair Team · September 26, 2018

1. Python Namedtuple Tutorial

In our journey so far, we have seen Python Tuple, which is an important container type. Today, we will talk
about python namedtuple with its example & syntax. Moreover, we will start our learning with a quick revision
of Python tuple and Accessing Elements of python namedtuple. At last, we will cover the working, and benefits
of python namedtuple.

So, let’s start the Python Namedtuple Tutorial.

Python Namedtuple – Working and Benefits of Namedtuple in Python

2. Python Tuple – A Revision

Before we proceed, we think we must review tuples in python.


A python tuple is a container that can hold different values. Let’s take an example.

1. >>> colors=(255,0,0)
As you can see, we define it using parentheses. To access an element, we use indices. (And remember, indexing
starts at 0)

1. >>> colors[0]

255
What makes a >>> colors[0] python tuple unique is that its values cannot be changed, i.e., it is immutable. Let’s
try changing a value.

1. >>> colors[1]=10

Traceback (most recent call last):

File “<pyshell#316>”, line 1, in <module> c

olors[1]=10

TypeError: ‘tuple’ object does not support item assignment


Now that we’ve taken a quick revision at tuples, let’s proceed to python syntax.

3. Python Namedtuple – Syntax

A Python namedtuple lets us access elements in a tuple using names/labels. To define it, we import namedtuple
from Python collections module and use the namedtuple() factory function.

1. >>> from collections import namedtuple


2. >>> Colors=namedtuple('Colors','red green blue')

Here, we use the function namedtuple().

1. >>> type(namedtuple)

<class ‘function’>

This takes two arguments-

1. Tuple name- Here, Colors is the tuple


2. Python string of fields, separated by spaces- Here, we have three fields- red, green, and blue.

Now, let’s define some python tuples.

1. >>> red=Colors(red=255,green=0,blue=0)
2. >>> green=Colors(red=0,green=255,blue=0)
3. >>> blue=Colors(red=0,green=0,blue=255)
4. >>> red

Colors(red=255, green=0, blue=0)


We’ll just leave here another way to define a python namedtuple- using a list instead of a string of fields.

1. >>> pets=namedtuple('pets',['name','age'])
2. >>> Fluffy=pets('Fluffy',8)
3. >>> Fluffy

pets(name=’Fluffy’, age=8)

4. Accessing Elements in a Python Namedtuple

To access an item, we can now use the dot-operator to access a field by its name. We do it this way:

1. >>> red.red

255

1. >>> red.green

1. >>> red.blue

See how simple it makes this? This way, a namedtuple is something like a python dictionary. But really,
python namedtuple is backward-compatible to a regular python tuple. This means that we can access a value
using indexing as well.

1. >>> red[0]

255

1. >>> red[1]

Finally, you can also access a value using the getattr() function.

1. >>> getattr(red,'green')

To see what kind of python objects these are, we use the type() function, like we always do.

1. >>> type(Colors)

<class ‘type’>

1. >>> type(red)

<class ‘ main .Colors’>

1. >>> type(red.red)

<class ‘int’>

5. How Namedtuple in Python Works?

Let’s see some more things we can do to a namedtuple in python.

a. A Python namedtuple is Immutable


Like its regular counterpart, a python namedtuple is immutable. We can’t change its attributes. To prove this,
we’ll try changing one of the attributes of a tuple of type ‘Colors’.

1. >>> red.blue=1

Traceback (most recent call last):

File “<pyshell#319>”, line 1, in <module>

red.blue=1

AttributeError: can’t set attribute


As is visible, it raises an AttributeError. Hence, we conclude that a python namedtuple is immutable.

b. Converting a Python namedtuple into a Python Dictionary


A namedtuple in Python is much like a dictionary, but if we want to convert it into one, we can:

1. >>> red._asdict()

OrderedDict([(‘red’, 255), (‘green’, 0), (‘blue’, 0)])

As you can see, we use the ._asdict() function for this. Also, this gives us a Python OrderedDict. We’ll see
that in detail in its own lesson.

c. Creating a namedtuple from a python Iterable


If you have a python list, you can make a namedtuple from it. But for this, you must have defined the format.

1. >>> Colors._make(['Purple','Violet','Gold'])

Colors(red=’Purple’, green=’Violet’, blue=’Gold’)


Follow this link to know more about Python Iterable

d. Converting a Python Dictionary into a namedtuple


CoA conversef what we learned in point b, we can turn a dictionary into a namedtuple in Python. We do this
using two asterisks before the dictionary to be passed as an argument to Colors here.

1. >>> Colors(**{'red':255,'green':0,'blue':0})

Colors(red=255, green=0, blue=0)

e. Checking what fields belong to a Python tuple


For this, we use the _fields attribute.

1. >>> red._fields

(‘red’, ‘green’, ‘blue’)


f. Changing a Value
Yes, a namedtuple’s attributes are immutable. But we can use the _replace() function to change them.

1. >>> red._replace(green=1)

Colors(red=255, green=1, blue=0)

6. Benefits of Python Namedtuple

Of course, no one would be using these if they observed no benefits at all. So, here we go:
1. Unlike a regular tuple, python namedtuple can also access values using names of the fields.

1. >>> red.red

255
2. Python namedtuple is just as memory-efficient as a regular tuple, because it does not have per-instance
dictionaries. This is also why it is faster than a dictionary.

7. Conclusion

Today, we learned about Python namedtuple. It is just like a regular tuple, apart from the fact that it can also
access fields through their names. This is easy on the programmer. It is also more memory-efficient than a
dictionary. Next, we will discuss some more functions from the collections module. Till give us your valuable
feedbacks.

Python Defaultdict – Int and List as a Default Factory


by DataFlair Team · September 26, 2018

1. Python Defaultdict

In today’s lesson, we will look at Python defaultdict, a subclass of the built-in dict class. So let’s start with
defaultdict Python 3 tutorial. Here, we will discuss what is Python Defaultdict with its syntax and exmaple.
Moreover, we will study Python Defaultdict using Int and List as a defaultdict in Python.

Dictionaries are an important part of Python. They are containers to hold key-value pairs.

1. >>> issubclass(defaultdict,dict) #You’ll need to import defaultdict from collections for this

True

So, let’s start Python Defualtdict Tutorial.


Python Defaultdict – Int and List as a Default Factory

2. A Revision – Python Dictionaries

Before we proceed to defaultdict in Python, we suggest you read up on Python Dictionaries.

A python dictionary is a container that holds key-value pairs. Keys must be unique, immutable objects. This
means that a Python tuple can be a key, but a python list can’t since it is mutable.

1. >>> {[1,2]:1,2:2}
2. Traceback (most recent call last):
3. File "<pyshell#355>", line 1, in <module>
4. {[1,2]:1,2:2}

TypeError: unhashable type: ‘list’

As you can see, a list, then, is unhashable. Let’s take a quick example to see how to define a python dictionary.

1. >>> mydict={'a':1,'b':2,'c':3}
2. >>> mydict['b']

2
We can also use the dict() function.

1. >>> otherdict=dict((['a',1],['b',2],['c',3]))
2. >>> otherdict

{‘a’: 1, ‘b’: 2, ‘c’: 3}

To get a list of keys, we use the keys() method.

1. >>> otherdict.keys()

dict_keys([‘a’, ‘b’, ‘c’])


But we have one problem. If the key does not exist, and we try to access it, it raises a KeyError.

1. >>> otherdict['d']
2. Traceback (most recent call last):
3. File "<pyshell#364>", line 1, in <module>
4. otherdict['d']

KeyError: ‘d’

3. Introduction to Python Defaultdict

To deal with this situation, we have defaultdict in Python. First, we must import it from Python collections
module.

1. >>> from collections import defaultdict

Here, we use the Python defaultdict() factory function. It takes, as an argument, a function object that will return
a value. Actually, if we don’t provide a value for a particular key, it will take that value for it. Let’s take a look
at the syntax.

4. Python Defaultdict – Syntax

Before Python defaultdict syntax, we revise python syntax.

As we discussed, we first import defaultdict from the ‘collections’ module. Let us see this Python defaultdict
example.

1. >>> from collections import defaultdict

Next, we define a python function to return a default value for the keys we don’t initialize.

1. >>> def defaultvalue():


2. return 0

Now, we create a Python defaultdict using the defaultdict() function. To this, we pass the function defaultvalue
as a function argument. Remember, you must pass the function object, you don’t have to call it with
parentheses.

1. >>> otherdict=defaultdict(defaultvalue)

Let’s now define values for keys ‘a’, ‘b’, and ‘c’.

1. >>> otherdict['a']=1
2. >>> otherdict['b']=2
3. >>> otherdict['c']=3

What if we access the value for key ‘d’? We haven’t initialized it yet.

1. >>> otherdict['d']
As you can see, it assigned it the default value we specified through function defaultvalue().
Let’s see the whole code at once now.

1. >>> def defaultvalue():


2. return 0
3. >>> otherdict=defaultdict(defaultvalue)
4. >>> otherdict['a']=1
5. >>> otherdict['b']=2
6. >>> otherdict['c']=3
7. >>> otherdict['d']

5. Another Example of Python Defaultdict

Let’s take another python defaultdict example. We take a defaultdict in python to hold the marks of students.
Also, we let the default value for marks be 35.

1. >>> marks=defaultdict(lambda :35)


2. >>> marks['Ayushi']=95
3. >>> marks['Gigi']=86
4. >>> marks['Ayushi']

95
Here, we used a Lambda Expression since all we need to do in it is to return a value. So why waste space,
right? Now, if we try to access the value to a key that doesn’t exist, it saves 35 to it.

1. >>> marks['Oshin']

35
Finally, these are the keys to this python defaultdict now:

1. >>> marks.keys()

dict_keys([‘Ayushi’, ‘Gigi’, ‘Oshin’])

6. More on Defaultdict in Python


Let’s see what happens if we return a None from the function.

1. >>> a=defaultdict(lambda :None)


2. >>> a[1]
3. >>> type(a[1])

<class ‘NoneType’>

What if a python exception was raised in the factory function?

1. >>> def defaultvalue():


2. print(1/0)
3. return 0
4. >>> a=defaultdict(defaultvalue)
5. >>> a[1]
Traceback (most recent call last):

File “<pyshell#386>”, line 1, in <module>

a[1]

File “<pyshell#384>”, line 2, in defaultvalue

print(1/0)

ZeroDivisionError: division by zero

Python defaultdict supports all operations that a regular dictionary does. These include keys() and len().

1. >>> dir(a)

[‘ class ’, ‘ contains ’, ‘ copy ’, ‘ delattr ’, ‘ delitem ’, ‘ dir ’, ‘ doc ’, ‘ eq ’,


‘ format ’, ‘ ge ’, ‘ getattribute ’, ‘ getitem ’, ‘ gt ’, ‘ hash ’, ‘ init ’,
‘ init_subclass ’, ‘ iter ’, ‘ le ’, ‘ len ’, ‘ lt ’, ‘ missing ’, ‘ ne ’, ‘ new ’,
‘ reduce ’, ‘ reduce_ex ’, ‘ repr ’, ‘ setattr ’, ‘ setitem ’, ‘ sizeof ’, ‘ str ’,
‘ subclasshook ’, ‘clear’, ‘copy’, ‘default_factory’, ‘fromkeys’, ‘get’, ‘items’, ‘keys’, ‘pop’, ‘popitem’,
‘setdefault’, ‘update’, ‘values’]

Let’s know about Exception handling in python.

a. missing (key)

This Python method is called by the getitem () method of the dict class when the requested key isn’t
found.

1. >>> from collections import defaultdict


2. >>> a=defaultdict(lambda :0)
3. >>> a['a']=1
4. >>> a['b']=2
5. >>> a['c']=3
6. >>> a. missing ('d')

It returned 0 here because that’s what we specified as a default value through a lambda expression to the
defaultdict() factory function.

1. >>> a. getitem ('a')

1. >>> a. getitem ('e')

7. Using ‘list’ as a Default Factory

If we pass ‘list’ (without the quotes) to the defaultdict() Pytohn function, we can group a sequence of key-value
pairs into a dictionary of lists. We can do this to more types as well. We’ll see another in the next section.
1. >>> a=[('a',1),('b',2),('c',3)]
2. >>> b=defaultdict(list)
3. >>> for i,j in a:
4. b[i].append(j)
5. >>> b

defaultdict(<class ‘list’>, {‘a’: [1], ‘b’: [2], ‘c’: [3]})

Let’s explain what this code does. First, we define ‘a’ as a list of tuples to hold the key-value pairs. Next, we
pass ‘list’ to defaultdict(), and store this in ‘b’. This tells the interpreter that b will hold a dictionary with values
that are list.

Then, we traverse on the tuples using names ‘I’ and ‘j’ with a for-loop. In this, we append j to b[i]. What this
means is that we take the second value in each tuple in ‘a’, and append it to the python defaultdict for each key
(first value in each tuple). For ‘c’ in the list ‘a’, as a key in the defaultdict ‘b’, we append the value 3 to the
python defaultdict to that key. This is its value now.

8. Using ‘int’ as a Default Factory

We can tell the interpreter to create a Python dictionary of integers. Here’s how.

1. >>> name='Bubbles'
2. >>> mydict=defaultdict(int)
3. >>> for i in name:
4. mydict[i]+=1
5. >>> mydict

defaultdict(<class ‘int’>, {‘B’: 1, ‘u’: 1, ‘b’: 2, ‘l’: 1, ‘e’: 1, ‘s’: 1})

This way, we can use it as a counter. Of course, we could have done this with a regular dictionary as well. But
here, we tell the interpreter that we’re going to work with only integer values.

So, this was all about Python Defaultdict Tutorial. Hope you like our explanation.

9. Conclusion
With a subtle difference to a regular dictionary, we see that a python defaultdict is actually quite useful. It has a
simple syntax as well and lets us define a default value for uninitialized keys. It also lets us tell the interpreter
that we want to work with a particular type of values.

Python OrderedDict – Reordering, Delete and Reinsert New


OrderedDict
by DataFlair Team · September 26, 2018
1. Python OrderedDict
We’ve been talking about classes from Python collections module– python namedtuple, and python
defaultdict. Today, we base our article on Python OrderedDict, another class in ‘collections’. Here we study
what is Python OrderedDict with its syntax and examples. Moreover, we will study comparing to a regular
dictionary, and reordering a OrderedDict in Python. At last, we will cover how to delete and reinsert a key for
new ordereddict, and popitem method.

So, let’s start the Python OderedDict Tutorial.

Python OrderedDict – Reordering, Delete and Reinsert New OrderedDict

2. Introduction to Python OrderedDict


Python OrderedDict is just like a regular dictionary in python, but it also saves the order in which pairs were
added. Actually, it is a subclass of ‘dict’.

1. >>> issubclass(OrderedDict,dict)

True

3. Python OrderedDict Syntax


To define an OrderedDict in python, we import it from the module ‘collections’. Let us see this Python
ordereddict example.
1. >>> from collections import OrderedDict

Then, we call this factory function and assign it to a variable in python.

1. >>> d=OrderedDict()

We now add some key-value pairs to it.

1. >>> d['a']=1
2. >>> d['e']=5
3. >>> d['d']=4
4. >>> d['b']=2
5. >>> d['c']=3

Now, if we access ‘d’, we see that it preserved the order in which we defined the key-value pairs.

1. >>> d

OrderedDict([(‘a’, 1), (‘e’, 5), (‘d’, 4), (‘b’, 2), (‘c’, 3)])

4. Comparing to a Regular Dictionary


Let’s try this with a regular dictionary. If we declared this as a regular dictionary, it would produce the pairs
according to how the keys are stored in a hash table. This depends on a random value to reduce collisions.

a. Equality

To a regular dictionary, the order does not matter. Let u take another Python ordereddict example.

1. >>> {'a': 1, 'e': 5, 'd': 4, 'b': 2, 'c': 3}=={'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

True
To Python, these two are equal. Let’s create another OrderedDict, and check if it is the same as the OrderedDict
‘d’ we defined above.

1. >>> e=OrderedDict()
2. >>> e['a']=1
3. >>> e['b']=2
4. >>> e['c']=3
5. >>> e['d']=4
6. >>> e['e']=5
7. >>> e

OrderedDict([(‘a’, 1), (‘b’, 2), (‘c’, 3), (‘d’, 4), (‘e’, 5)])
Now, let’s check if they’re equal.

1. >>> d==e
False
As you can see, they’re not.

5. How to Reorder Python OrderedDict?


To reorder a key-value pair to the front or the end of an OrderedDict in python, we have the move_to_end()
method. Look, this is ‘d’:

1. >>> d

OrderedDict([(‘a’, 1), (‘e’, 5), (‘d’, 4), (‘b’, 2), (‘c’, 3)])
Now, let’s move (‘e’,5) to the end.

1. >>> d.move_to_end('e')
2. >>> d

OrderedDict([(‘a’, 1), (‘d’, 4), (‘b’, 2), (‘c’, 3), (‘e’, 5)])

This method takes a key as an argument. But it may also take another argument- ‘last’. This may take one of
two values: True or False. When true, the item is moved to the end. And when false, it is moved to the front.

1. >>> d.move_to_end('a',last=True)
2. >>> d

OrderedDict([(‘d’, 4), (‘b’, 2), (‘c’, 3), (‘e’, 5), (‘a’, 1)])
Here, we moved (‘a’,1) to the end. Now, let’s move it back to the front.

1. >>> d.move_to_end('a',last=False)
2. >>> d

OrderedDict([(‘a’, 1), (‘d’, 4), (‘b’, 2), (‘c’, 3), (‘e’, 5)])
Now, to sort this, we do the following:

1. >>> d.move_to_end('b')
2. >>> d

OrderedDict([(‘a’, 1), (‘d’, 4), (‘c’, 3), (‘e’, 5), (‘b’, 2)])

1. >>> d.move_to_end('c')
2. >>> d

OrderedDict([(‘a’, 1), (‘d’, 4), (‘e’, 5), (‘b’, 2), (‘c’, 3)])

1. >>> d.move_to_end('d')
2. >>> d

OrderedDict([(‘a’, 1), (‘e’, 5), (‘b’, 2), (‘c’, 3), (‘d’, 4)])

1. >>> d.move_to_end('e')
2. >>> d

OrderedDict([(‘a’, 1), (‘b’, 2), (‘c’, 3), (‘d’, 4), (‘e’, 5)])

6. Assigning a Key Again in Python


OrderedDict
Let’s define a new OrderedDict in Python for this example.

1. >>> f=OrderedDict()
2. >>> f['c']=3
3. >>> f['e']=5
4. >>> f['a']=1
5. >>> f['b']=2
6. >>> f['d']=4
7. >>> f

OrderedDict([(‘c’, 3), (‘e’, 5), (‘a’, 1), (‘b’, 2), (‘d’, 4)])
Now, let’s try changing the value of key ‘e’.

1. >>> f['e']=7
2. >>> f

OrderedDict([(‘c’, 3), (‘e’, 7), (‘a’, 1), (‘b’, 2), (‘d’, 4)])
Okay. Since the key ‘e’ already exists, the old order is preserved; it isn’t ordered to the end.

7. Deleting and Reinserting a Key


When we delete a key and then reinsert it, it is ordered to the end of the new order. Let’s try deleting ‘e’.

1. >>> f.pop('e')

1. >>> f

OrderedDict([(‘c’, 3), (‘a’, 1), (‘b’, 2), (‘d’, 4)])


Now, let’s insert it again.

1. >>> f

OrderedDict([(‘c’, 3), (‘a’, 1), (‘b’, 2), (‘d’, 4), (‘e’, 7)])
As you can see, it is at the back of the list now.
8. Python Popitem ()
The popitem() method in Python may take 0 or 1 argument- ‘last’. When ‘last’ is true, LIFO is followed to
delete, otherwise, FIFO is followed. When we don’t pass an argument, last is assumed to be true.
Let’s take a new Python OrderedDict for this.

1. >>> g=OrderedDict()
2. >>> g['d']=4
3. >>> g['b']=2
4. >>> g['a']=1
5. >>> g['c']=3
6. >>> g['e']=5
7. >>> g

OrderedDict([(‘d’, 4), (‘b’, 2), (‘a’, 1), (‘c’, 3), (‘e’, 5)])
Now, let’s start popping.

1. >>> g.popitem(last=False)

(‘d’, 4)

1. >>> g.popitem()

(‘e’, 5)

1. >>> g.popitem(last=True)

(‘c’, 3)

So, this was all about Python OrderedDict Tutorial. Hope you like our explanation.

9. Conclusion
Hopefully, we’ve covered every important detail about python orderedDict in this article. We saw how to define
them, Syntax, deleting and reinserting, assigning A key to python ordereddict, and we saw methods
move_to_end(), popitem(), and pop(). Next, we will discuss Counter python module, yet another class from
collections.
Python Dictionary with Methods, Functions
and
Dictionary Operations
by DataFlair Team · May 27, 2019

1. Python Dictionary Tutorial


In the last few lessons, we have learned about some Python constructs like lists and tuples. Today, we will have
a word about Python dictionary which is another type of data structure in Python. Moreover, we will study how
to create, access, delete, reassign dictionary in Python. Along with this, we will learn Python Dictionary method
and operations.

So, let’s start the Python Dictionary Tutorial.

Python Dictionary

2. An Introduction to Python Dictionaries


A real-life dictionary holds words and their meanings. As you can imagine, likewise, a Python dictionary holds
key-value pairs. Let’s look at how to create one.
3. How to Create a Dictionary in Python?
Creating a Python Dictionary is easy as pie. Separate keys from values with a colon(:), and a pair from another
by a comma(,). Finally, put it all in curly braces.

1. >>> {'PB&J':'Peanut Butter and Jelly','PJ':'Pajamas'}

{‘PB&J’: ‘Peanut Butter and Jelly’, ‘PJ’: ‘Pajamas’}

Optionally, you can put the dictionary in a variable. If you want to use it later in the program, you must do this.

1. >>> lingo={'PB&J':'Peanut Butter and Jelly','PJ':'Pajamas'}

To create an empty dictionary, simply use curly braces and then assign it to a variable

1. >>> dict2={}
2. >>> dict2

{}

1. >>> type(dict2)

<class ‘dict’>

a. Python Dictionary Comprehension


You can also create a Python dict using comprehension. This is the same thing that you’ve learned in your math
class. To do this, follow an expression pair with a for-statement loop in python. Finally, put it all in curly
braces.

1. >>> mydict={x*x:x for x in range(8)}


2. >>> mydict

{0: 0, 1: 1, 4: 2, 9: 3, 16: 4, 25: 5, 36: 6, 49: 7}

In the above code, we created a Python dictionary to hold squares of numbers from 0 to 7 as keys, and numbers
0-1 as values.

b. Dictionaries with mixed keys


It isn’t necessary to use the same kind of keys (or values) for a dictionary in Python.

1. >>> dict3={1:'carrots','two':[1,2,3]}
2. >>> dict3

{1: ‘carrots’, ‘two’: [1, 2, 3]}


As you can see here, a key or a value can be anything from an integer to a list.

c. dict()
Using the dict() function, you can convert a compatible combination of constructs into a Python dictionary.

1. >>> dict(([1,2],[2,4],[3,6]))

{1: 2, 2: 4, 3: 6}

However, this function takes only one argument. So if you pass it three lists, you must pass them inside a list or
a tuple. Otherwise, it throws an error.

1. >>> dict([1,2],[2,4],[3,6])

Traceback (most recent call last):

File “<pyshell#121>”, line 1, in <module>

dict([1,2],[2,4],[3,6])

TypeError: dict expected at most 1 arguments, got 3

d. Declaring one key more than once


Now, let’s try declaring one key more than once and see what happens.

1. >>> mydict2={1:2,1:3,1:4,2:4}
2. >>> mydict2

{1: 4, 2: 4}

As you can see, 1:2 was replaced by 1:3, which was then replaced by 1:4. This shows us that a dictionary cannot
contain the same key twice.

e. Declaring an empty dictionary and adding elements later


When you don’t know what key-value pairs go in your Python dictionary, you can just create an empty Python
dict, and add pairs later.

1. >>> animals={}
2. >>> type(animals)

<class ‘dict’>

1. >>> animals[1]='dog'
2. >>> animals[2]='cat'
3. >>> animals[3]='ferret'
4. >>> animals

{1: ‘dog’, 2: ‘cat’, 3: ‘ferret’}

Any query on Python Dictionay yet? Leave a comment.

4. How to Access a Python Dictionary?


a. Accessing the entire Python dictionary
To get the entire dictionary at once, type its name in the shell.

1. >>> dict3

{1: ‘carrots’, ‘two’: [1, 2, 3]}

b. Accessing a value
To access an item from a list or a tuple, we use its index in square brackets. This is the python syntax to be
followed. However, a Python dictionary is unordered. So to get a value from it, you need to put its key in square
brackets.

To get the square root of 36 from the above dictionary, we write the following code.

1. >>> mydict[36]

c. get()
The Python dictionary get() function takes a key as an argument and returns the corresponding value.

1. >>> mydict.get(49)

d. When the Python dictionary keys doesn’t exist


If the key you’re searching for doesn’t exist, let’s see what happens.

1. >>> mydict[48]

Traceback (most recent call last):

File “<pyshell#125>”, line 1, in <module>

mydict[48]
KeyError: 48

Using the key in square brackets gives us a KeyError. Now let’s see what the get() method returns in such a
situation.

1. >>> mydict.get(48)
2. >>>

As you can see, this didn’t print anything. Let’s put it in the print statement to find out what’s going on.

1. >>> print(mydict.get(48))

None

So we see, when the key doesn’t exist, the get() function returns the value None. We discussed it earlier, and
know that it indicates an absence of value.

5. Reassigning a Python Dictionary


The python dictionary is mutable. This means that we can change it or add new items without having to reassign
all of it.

a. Updating the Value of an Existing Key


If the key already exists in the Python dictionary, you can reassign its value using square brackets.

Let’s take a new Python dictionary for this.

1. >>> dict4={1:1,2:2,3:3}

Now, let’s try updating the value for the key 2.

1. >>> dict4[2]=4
2. >>> dict4

{1: 1, 2: 4, 3: 3}

b. Adding a new key


However, if the key doesn’t already exist in the dictionary, then it adds a new one.

1. >>> dict4[4]=6
2. >>> dict4

{1: 1, 2: 4, 3: 3, 4: 6}

Python dictionary cannot be sliced.


6. How to Delete Python Dictionary?
You can delete an entire dictionary. Also, unlike a tuple, a Python dictionary is mutable. So you can also delete
a part of it.

a. Deleting an entire Python dictionary


To delete the whole Python dict, simply use its name after the keyword ‘del’.

1. >>> del dict4


2. >>> dict4

Traceback (most recent call last):

File “<pyshell#138>”, line 1, in <module>

dict4

NameError: name ‘dict4’ is not defined

b. Deleting a single key-value pair


To delete just one key-value pair, use the keyword ‘del’ with the key of the pair to delete.

Now let’s first reassign dict4 for this example.

1. >>> dict4={1:1,2:2,3:3,4:4}

Now, let’s delete the pair 2:2

1. >>> del dict4[2]


2. >>> dict4

{1: 1, 3: 3, 4: 4}

A few other methods allow us to delete an item from a dictionary in Python. We will see those in section 8.

7. In-Built Functions on a Python Dictionary


A function is a procedure that can be applied on a construct to get a value. Furthermore, it doesn’t modify the
construct. Python gives us a few functions that we can apply on a Python dictionary. Take a look.

a. len()
The len() function returns the length of the dictionary in Python. Every key-value pair adds 1 to the length.
1. >>> len(dict4)

An empty Python dictionary has a length of 0.

1. >>> len({})

b. any()
Like it is with lists an tuples, the any() function returns True if even one key in a dictionary has a Boolean value
of True.

1. >>> any({False:False,'':''})

False

1. >>> any({True:False,"":""})

True

1. >>> any({'1':'','':''})

True

c. all()
Unlike the any() function, all() returns True only if all the keys in the dictionary have a Boolean value of True.

1. >>> all({1:2,2:'',"":3})

False

d. sorted()
Like it is with lists and tuples, the sorted() function returns a sorted sequence of the keys in the dictionary. The
sorting is in ascending order, and doesn’t modify the original Python dictionary.

But to see its effect, let’s first modify dict4.

1. >>> dict4={3:3,1:1,4:4}

Now, let’s apply the sorted() function on it.

1. >>> sorted(dict4)

[1, 3, 4]
Now, let’s try printing the dictionary dict4 again.

1. >>> dict4

{3: 3, 1: 1, 4: 4}

As you can see, the original Python dictionary wasn’t modified.

This function returns the keys in a sorted list. To prove this, let’s see what the type() function returns.

1. >>> type(sorted(dict4))

<class ‘list’>

This proves that sorted() returns a list.

8. In-Built Methods on a Python Dictionary


A method is a set of instructions to execute on a construct, and it may modify the construct. To do this, a
method must be called on the construct. Now, let’s look at the available methods for dictionaries.

Let’s use dict4 for this example.

1. >>> dict4

{3: 3, 1: 1, 4: 4}

a. keys()
The keys() method returns a list of keys in a Python dictionary.

1. >>> dict4.keys()

dict_keys([3, 1, 4])

b. values()
Likewise, the values() method returns a list of values in the dictionary.

1. >>> dict4.values()

dict_values([3, 1, 4])

c. items()
This method returns a list of key-value pairs.
1. >>> dict4.items()

dict_items([(3, 3), (1, 1), (4, 4)])

d. get()
We first saw this function in section 4c. Now, let’s dig a bit deeper.

It takes one to two arguments. While the first is the key to search for, the second is the value to return if the key
isn’t found. The default value for this second argument is None.

1. >>> dict4.get(3,0)

1. >>> dict4.get(5,0)

Since the key 5 wasn’t in the dictionary, it returned 0, like we specified.

Any doubt yet in Python Dictionary? Leave a comment.

e. clear()
The clear function’s purpose is obvious. It empties the Python dictionary.

1. >>> dict4.clear()
2. >>> dict4

{}

Let’s reassign it though for further examples.

1. >>> dict4={3:3,1:1,4:4}

f. copy()
First, let’s see what shallow and deep copies are. A shallow copy only copies contents, and the new construct
points to the same memory location. But a deep copy copies contents, and the new construct points to a
different location. The copy() method creates a shallow copy of the Python dictionary.

1. >>> newdict=dict4.copy()
2. >>> newdict

{3: 3, 1: 1, 4: 4}
g. pop()
This method is used to remove and display an item from the dictionary. It takes one to two arguments. The first
is the key to be deleted, while the second is the value that’s returned if the key isn’t found.

1. >>> newdict.pop(4)

Now, let’s try deleting the pair 4:4.

1. >>> newdict.pop(5,-1)

-1

However, unlike the get() method, this has no default None value for the second parameter.

1. >>> newdict.pop(5)

Traceback (most recent call last):

File “<pyshell#191>”, line 1, in <module>

newdict.pop(5)

KeyError: 5

As you can see, it raised a KeyError when it couldn’t find the key.

h. popitem()
Let’s first reassign the Python dictionary newdict.

1. >>> newdict={3:3,1:1,4:4,7:7,9:9}

Now, we’ll try calling popitem() on this.

1. >>> newdict.popitem()

(9, 9)

It popped the pair 9:9.

Let’s restart the shell and reassign the dictionary again and see which pair is popped.

1. =============================== RESTART: Shell ===============================


2. >>> newdict={3:3,1:1,4:4,7:7,9:9}
3. >>> newdict.popitem()
(9, 9)

As you can see, the same pair was popped. We can interpret from this that the internal logic of the popitem()
method is such that for a particular dictionary, it always pops pairs in the same order.

i. fromkeys()
This method creates a new Python dictionary from an existing one. To take an example, we try to create a new
dictionary from newdict. While the first argument takes a set of keys from the dictionary, the second takes a
value to assign to all those keys. But the second argument is optional.

1. >>> newdict.fromkeys({1,2,3,4,7},0)

{1: 0, 2: 0, 3: 0, 4: 0, 7: 0}

However, the keys don’t have to be in a set.

1. >>> newdict.fromkeys((1,2,3,4,7),0)

{1: 0, 2: 0, 3: 0, 4: 0, 7: 0}

Like we’ve seen so far, the default value for the second argument is None.

1. >>> newdict.fromkeys({'1','2','3','4','7'})

{‘4’: None, ‘7’: None, ‘3’: None, ‘1’: None, ‘2’: None}

j. update()
The update() method takes another dictionary as an argument. Then it updates the dictionary to hold values
from the other dictionary that it doesn’t already.

1. >>> dict1={1:1,2:2}
2. >>> dict2={2:2,3:3}
3. >>> dict1.update(dict2)
4. >>> dict1

{1: 1, 2: 2, 3: 3}

9. Python Dictionary Operations


We learned about different classes of operators in Python earlier. Let’s now see which of those can we apply on
dictionaries.

a. Membership
We can apply the ‘in’ and ‘not in’ operators on a Python dictionary to check whether it contains a certain key.
For this example, we’ll work on dict1.

1. >>> dict1

{1: 1, 2: 2, 3: 3}

1. >>> 2 in dict1

True

1. >>> 4 in dict1

False

2 is a key in dict1, but 4 isn’t. Hence, it returns True and False for them, correspondingly.

10.Python Iterate Dictionary


When in a for loop, you can also iterate on a Python dictionary like on a list, tuple, or set.

1. >>> dict4

{1: 1, 3: 3, 4: 4}

1. >>> for i in dict4:


2. print(dict4[i]*2)

2
6
8

The above code, for every key in the Python dictionary, multiplies its value by 2, and then prints it.

11.Nested Dictionary
Finally, let’s look at nested dictionaries. You can also place a Python dictionary as a value within a dictionary.

1. >>> dict1={4:{1:2,2:4},8:16}
2. >>> dict1

{4: {1: 2, 2: 4}, 8: 16}

To get the value for the key 4, write the following code.

1. >>> dict1[4]

{1: 2, 2: 4}
However, you can’t place it as a key, because that throws an error.

1. >>> dict1={{1:2,2:4}:8,8:16}

Traceback (most recent call last):

File “<pyshell#227>”, line 1, in <module>

dict1={{1:2,2:4}:8,8:16}

TypeError: unhashable type: ‘dict’

So, this was all about Python Dictionary tutorial. Hope you like our explanation

12.Conclusion
In today’s lesson, we took a deep look at Python Dictionary. We first saw how to create, access, reassign, and
delete a dictionary or its elements. Then we looked at built-in functions and methods for dictionaries. After that,
we learned about the operations that we can perform on them. Lastly, we learned about nested dictionaries and
how to iterate on a Python dictionary. Still, you have a confusion? feel free to ask in the comment box.

Python Datetime Module with Quick Examples


by DataFlair Team · May 27, 2019

1. Python Datetime Module


With the ever-complex lifestyle we have adopted, date and time are extremely important. It is like we’re all
slaves to time. In this Python Datetime Module tutorial, we will see how to work with Python Datetime Module
and Python date Objects, Python time Objects, Python datetime Objects, and Python timedelta Objects. You
should refer to Python Date and Time.

So, let’s start the Python Datetime Module.


Introduction to Python Datetime Module

2. Python Datetime Module


The Python datetime module offers functions and classes for working with date and time parsing, formatting,
and arithmetic. Let’s start with Python Date time with Examples.

Two kinds of date and time objects exist- naïve and aware.

A naïve object is easier to deal with and doesn’t have enough information to unambiguously locate itself
relative to other date/time objects. An aware object is more realistic, it knows applicable algorithmic and
political time adjustments.

To use this module, we must first import it.

1. >>> import datetime

It has the following constants:

a. MAXYEAR
MAXYEAR tells us the maximum value a year can take, which is 9999.

1. >>> datetime.MAXYEAR

9999
b. MINYEAR
The minimum value of year is 1. This is what MINYEAR returns.

1. >>> datetime.MINYEAR

1
Both MAXYEAR and MINYEAR are of the type integer.

1. >>> type(datetime.MAXYEAR),type(datetime.MINYEAR)

(<class ‘int’>, <class ‘int’>)


Bonus- type() is of the type type.

1. >>> type(type)

<class ‘type’>
Other than these constants, datetime has these datetime class types:

1. class datetime.date

Python date is an idealized naïve date considering the current Gregorian calendar.
Attributes: year, month, and day.

1. class datetime.time

Python time is an idealized time, independent of any particular day. Here, we assume that each day is made of
exactly 24*60*60 seconds (no leap seconds).
Attributes: hour, minute, second, microsecond, and tzinfo.

1. class datetime.datetime

When you combine a date and a time, you get a datetime.

1. >>> issubclass(datetime.datetime,datetime.date)

True

1. >>> issubclass(datetime.datetime,datetime.time)

False
Attributes: year, month, day, hour, minute, second, microsecond, and tzinfo.

1. class datetime.timedelta

A timedelta is a duration expressing the difference between two date, time, or datetime instances to
microsecond resolution.

1. class datetime.tzinfo
tzinfo is an abstract base class we use for time zone information objects. The date and time classes use it to
provide a customizable notion of time adjustment (for example, to account for time zone and/or DST(daylight
saving time)).

1. class datetime.timezone

timezone implements the tzinfo abstract base class as a fixed offset from the UTC.
Such objects are immutable. Also, objects of the type ‘date’ is naïve, but those of the types ‘time’ or ‘datetime’
may be aware or naïve. The next in Python Datetime Module Tutorial is Date Objects

3. Python date Objects


A date object represents a date with year, month, and day, according to the ideal Gregorian calendar.
With a date object, we have the following methods:

a. date(year, month, day)


This method will create an object of type ‘date’.

1. >>> d=datetime.date(2018,2,28)

Here, year can be from MAXYEAR to MINYEAR, and month can be from 1 to 12. The day can be from 1 to
the number of days in the given month for the given year.

b. today()
today() will return the current local date.

1. >>> datetime.date.today()

datetime.date(2018, 2, 28)

c. fromtimestamp(timestamp)
fromtimestamp will return the date for the Python timestamp provided.

1. >>> import time


2. >>> time.time()

1519818814.358453

1. >>> datetime.date.fromtimestamp(time.time())

datetime.date(2018, 2, 28)

1. >>> datetime.date.fromtimestamp(time.time()+999999)
datetime.date(2018, 3, 12)
The date class also has these attributes:

a. date.min
It returns the earliest representable date.

1. >>> datetime.date.min

datetime.date(1, 1, 1)

b. date.max
Like min, max returns the latest representable date.

1. >>> datetime.date.max

datetime.date(9999, 12, 31)

c. date.resolution
resolution returns the smallest possible difference between non-equal date objects.

1. >>> datetime.date.resolution

datetime.timedelta(1)

We also have the following instance attributes:

a. year
This returns the year from a date object.

1. >>> d=datetime.date(2018,2,28)
2. >>> d.year

2018

b. month
month returns the month from a date object.

1. >>> d.month

2
c. day
This returns the day from a date object.

1. >>> d.day

28
And then, we have the following instance methods:

a. replace(year, month, day)


This will let us update any or all of these three values.

1. >>> d=d.replace(month=3,day=1)
2. >>> d

datetime.date(2018, 3, 1)

b. timetuple()
timetuple() returns a tuple of attributes for the current local time.

1. >>> d.timetuple()

time.struct_time(tm_year=2018, tm_mon=2, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2,


tm_yday=59, tm_isdst=-1)

c. weekday()
weekday() will return the day of the week, where 0 denotes Monday.

1. >>> d.weekday()

d. isoweekday()
Here, Monday is 1.

1. >>> d.isoweekday()

3
e. isocalendar()
This method returns a tuple of three things- ISO year, ISO week number, and ISO weekday.

1. >>> d.isocalendar()

(2018, 9, 3)

f. isoformat()
This returns the date in the ISO format.

1. >>> d.isoformat()

‘2018-02-28’

g. str ()
This will return the current local date as a string.

1. >>> d. str ()

‘2018-02-28’

1. >>> str(d)

‘2018-02-28’

h. ctime()
ctime returns the current local date in a string format.

1. >>> d.ctime()

‘Wed Feb 28 00:00:00 2018’


We can also perform some operations on a date object:

1. >>> d=datetime.date(2018,12,30)
2. >>> td=datetime.timedelta(0,99999)
3. >>> d1=d+td
4. >>> d1

datetime.date(2018, 12, 31)

1. >>> d1<d

False
Any doubt yet in Date time module in Python or Examples? Please comment.

The Next in Python Datetime Module Tutorial is Time Objects

4. Python time Objects


A time object represents a local time of day. Its arguments are- hour, minute, second, microsecond, and tzinfo.

1. >>> t=datetime.time(11,59,59,99999)

The class time has the following attributes:

a. min
This returns the earliest representable time.

1. >>> t.min

datetime.time(0, 0)

b. max
This returns the latest representable time.

1. >>> t.max

datetime.time(23, 59, 59, 999999)

c. resolution
resolution returns the smallest possible difference between non-equal time objects.

1. >>> t.resolution

datetime.timedelta(0, 0, 1)
Now, let’s look at some non-readable instance attributes:

a. hour
This tells us the hour from the object.

1. >>> t.hour

11
b. minute
This returns the minute.

1. >>> t.minute

59

c. second
This returns the second.

1. >>> t.second

59

d. microsecond
This returns the microsecond.

1. >>> t.microsecond

99999

e. tzinfo
This returns whatever we pass as tzinfo to the object while creating it. If we didn’t, it returns None.

1. >>> print(t.tzinfo)

None

f. fold
This disambiguates wall times during a repeated interval.

1. >>> t.fold

We have the following instance methods:

i. replace()

This does the same as for ‘date’ objects.

1. >>> t=t.replace(hour=22,second=7)
ii.isoformat()

This method returns the time in the object in the ISO format.

1. >>> t.isoformat()

’22:59:07.099999′

iii. str ()

This does the same as it does for ‘date’ objects.

1. >>> t. str ()

’22:59:07.099999′
Now in the Python Datetime Module Tutorial Lets move ahead with datetime Objects

5. Python datetime Objects


A datetime objects knows about the date and the time. Arguments include year, month, day, hour, minute,
second, microsecond, tzinfo.

1. >>> d=datetime.datetime(1995,12,31,10,0)

We have the following methods:

a. today()
This method returns the current local datetime.

1. >>> datetime.datetime.today()

datetime.datetime(2018, 2, 28, 19, 9, 40, 751445)

b. now()
now() returns the current local date and time, but is more precise than today().

1. >>> datetime.datetime.now()

datetime.datetime(2018, 2, 28, 19, 12, 45, 710542)

c. utcnow()
utcnow() returns the current UTC time.

1. >>> datetime.datetime.utcnow()
datetime.datetime(2018, 2, 28, 13, 49, 14, 486367)

d. fromtimestamp()
This returns the date and time for the provided timestamp.

1. >>> datetime.datetime.fromtimestamp(time.time())

datetime.datetime(2018, 2, 28, 19, 20, 24, 55451)

e. utctimestamp()
This is like the previous one, but it returns the UTC time.

1. >>> datetime.datetime.utcfromtimestamp(time.time())

datetime.datetime(2018, 2, 28, 13, 51, 56, 615793)


Now, let’s look at the class attributes:

a. min
Like for everything else, this returns the earliest representable datetime.

1. >>> datetime.datetime.min

datetime.datetime(1, 1, 1, 0, 0)

b. max
max returns the latest representable datetime.

1. >>> datetime.datetime.max

datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)

c. resolution
Resolution is about the smallest possible difference between non-equal datetime objects.

1. >>> datetime.datetime.resolution

datetime.timedelta(0, 0, 1)
Now, let’s see some read-only instance attributes:
a. year
This returns the year.

1. >>> d.year

1995

b. month
This returns the month.

1. >>> d.month

12

c. day
This returns the day.

1. >>> d.day

31

d. hour
This returns the hour.

1. >>> d.hour

10

e. minute
This returns the minute.

1. >>> d.minute

f. second
This returns the second.

1. >>> d.second
g. microsecond
This returns the microsecond.

1. >>> d.microsecond

h. tzinfo
This returns the tzinfo; None, if we passed none while creating the object.

1. >>> print(d.tzinfo)

None

i. fold
This is the same as we discussed before.

1. >>> d.fold

Finally, let’s try some instance methods.

a. replace()
Again, this is like we have been doing so far.

1. >>> d.replace(microsecond=7)

datetime.datetime(1995, 12, 31, 10, 0, 0, 7)

b. date()
date() returns a date object from the datetime object.

1. >>> d.date()

datetime.date(1995, 12, 31)

c. time()
time() returns a time object from the datetime object.

1. >>> d.time()

datetime.time(10, 0)
d. timetz()
Other than what time() does, timetz() also returns the tzinfo value.

1. >>> d.timetz()

datetime.time(10, 0)

e. astimezone()
This returns a datetime object with new tzinfo attribute tz, adjusting the date and time data so the result is the
same UTC time as self, but in tz’s local time.

1. >>> d.astimezone()

datetime.datetime(1995, 12, 31, 10, 0, tzinfo=datetime.timezone(datetime.timedelta(0, 19800), ‘India Standard


Time’))

f. utcoffset()
If there is a UTC offset, it returns that, else, None.

1. >>> print(d.utcoffset())

None

g. dst()
If Daylight Savings Time applies, it returns its magnitude.

1. >>> print(d.dst())

None

h. tzname
If you would have set tzinfo, this would return its name.

1. >>> print(d.tzname())

None

i. timetuple()
Like we saw earlier, this returns a time tuple of the object.
1. >>> d.timetuple()

time.struct_time(tm_year=1995, tm_mon=12, tm_mday=31, tm_hour=10, tm_min=0, tm_sec=0, tm_wday=6,


tm_yday=365, tm_isdst=-1)

j. utctimetuple()
This returns a time tuple of the UTC time.

1. >>> d.utctimetuple()

time.struct_time(tm_year=1995, tm_mon=12, tm_mday=31, tm_hour=10, tm_min=0, tm_sec=0, tm_wday=6,


tm_yday=365, tm_isdst=0)

k. timestamp()
This returns the timestamp of the object (in seconds).

1. >>> d.timestamp()

820384200.0

l. weekday()
This returns the number of weekday for the object, where 0 is for Monday.

1. >>> d.weekday()

6
#A Sunday

m. isoweekday()
This returns the day of the week, but with Monday as 1.

1. >>> d.isoweekday()

n. isocalendar()
This returns a tuple of the following- ISO year, ISO week number, ISO weekday.

1. >>> d.isocalendar()

(1995, 52, 7)
o. isoformat()
This returns the date and time in the ISO format.

1. >>> d.isoformat()

‘1995-12-31T10:00:00’

p. str ()
This returns the date and time in a string representation.

1. >>> d. str ()

‘1995-12-31 10:00:00’

1. >>> str(d)

‘1995-12-31 10:00:00’

q. ctime()
This, like str, returns the datetime as a string.

1. >>> d.ctime()

‘Sun Dec 31 10:00:00 1995’


Some operations that we can perform on a datetime object are:

1. >>> d=datetime.datetime(2018,12,30)
2. >>> td=datetime.timedelta(0,99999)
3. >>> d1=d+td
4. >>> d1

datetime.datetime(2018, 12, 31, 3, 46, 39)

1. >>> d<d1

True
6. Python timedelta Objects
A timedelta object represents the duration between two dates or times.
Attributes: days, seconds, microseconds, milliseconds, minutes, hours, weeks
Here, seconds can be from 0 to 86399.

1. >>> td=datetime.timedelta(9,3,9999,999,58,22,3)

These attributes belong to the timedelta class:

a. min
This returns the most negative timedelta object.

1. >>> datetime.timedelta.min

datetime.timedelta(-999999999)

b. max
This one returns the most positive timedelta object.

1. >>> datetime.timedelta.max

datetime.timedelta(999999999, 86399, 999999)

c. resolution
resolution returns the smallest possible difference between non-equal timedelta objects.

1. >>> datetime.timedelta.resolution

datetime.timedelta(0, 0, 1)
timedelta also supports one instance method:

a. total_seconds()
This returns the total number of seconds in the duration.

1. >>> td.total_seconds()

2674684.008999
You can perform arithmetic operations on timedelta objects.

1. >>> td=datetime.timedelta(0,333)
2. >>> td1=td*2
3. >>> td1

datetime.timedelta(0, 666)

So, this was all about the Python Datetime Module Tutorial. Hope you like our explanation.

7. Conclusion: Python Datetime Module Tutorial


We hope that after this article on Python datetime Module Tutorial, and after Date and Time, you will be able to
handle all date and time easily. If you think this is a bit too much for once, don’t panic. Work on it twice or
thrice. Practice will do it for you. And comment if you need any help on Python Datetime examples.

Advance Python Modules – How to Create &


Import with dir Function
by DataFlair Team · September 27, 2018

1. Python Modules Tutorial


In this Python Modules tutorial, we will discuss what is a module in Python programming language?. Moreover,
we will talk about how to create python modules and import modules in python. Along with this, we will learn
how can we execute python module as a script, standard Python modules, and Python dir functions.

So, let’s start Python Modules Tutorial.


Python Modules

2. Define Python Modules?


Python module is but a piece of code.

Exiting the interpreter destroys all functions and variables we created. But when we want a longer program, we
create a script. With Python, we can put such definitions in a file, and use them in a script, or in an interactive
instance of the interpreter. Such a file is a module. If you face any difficulty in article on Python modules, ask
us in comments.

In essence, a module is a file that contains Python statements and definitions. A Python modules looks like this:

calc.py

3. How to Create Python Modules?


Let’s create a Python modules ‘calc’.

Microsoft Windows [Version 10.0.16299.309]

(c) 2017 Microsoft Corporation. All rights reserved.

C:\Users\lifei>cd Desktop

C:\Users\lifei\Desktop>mkdir calc

C:\Users\lifei\Desktop>cd calc

C:\Users\lifei\Desktop\calc>echo > init .py

C:\Users\lifei\Desktop\calc>echo >calc.py

C:\Users\lifei\Desktop\calc>

And this is what we put inside the module calc.py:

1. def add(a,b):
2. return a+b
3. def sub(a,b):
4. return a-b
5. def mul(a,b):
6. return a*b
7. def div(a,b):
8. return a/b
9. def exp(a,b):
10. return a**b
11. def floordiv(a,b):
12. return a//b

Also, calc is a package we create, and we place init .py inside it (Refer to Python Packages).

4. How can we Import Modules in Python?


Now, to import Python modules, we first get to the Desktop in Python.

1. >>> import os
2. >>> os.chdir('C:\\Users\\lifei\\Desktop\\calc')
3. >>> import calc
4. >>>

To find the name of this module, we can use the __name attribute.

1. >>> calc. name

‘calc’

We can now use functions from this module:

We can also assign one of these functions a name:

1. >>> fd=calc.floordiv
2. >>> fd(5.5,4)

1.0

1. >>> fd(9,4)

1. >>> type(fd(9,4))

<class ‘int’>

1. >>> type(fd(5.5,4))

<class ‘float’>

Read: Python Module vs Package

5. More on Python Modules and Importing


Python modules may contain anything from executable statements to function definitions. Such statements
initialize the module. Hence, they execute only once, when we import the module. However, they also run if we
execute the file as a script.
Each module uses its own private symbol table globally for all of its functions. So, its author can use global
variables in the module without worrying that they will accidentally clash with a user’s global variables.

A module can always import other modules in Python. In fact, we can place import statements at the beginning
of a module/script, but we don’t ‘need’ to. This places the imported module’s name in the importing module’s
symbol table.

We can also selectively import functions from a Python modules:

1. >>> from calc import div as d,floordiv as fd


2. >>> d(9,4)

2.25

1. >>> fd(9,4)

2
We can also import all from a module:

1. >>> from calc import *


2. >>> floordiv(9,4)

This will import all names other than those beginning with an underscore(_). However, we disparage this use, as
it makes for poorly readable code.

We can also import a module under an alias.

1. >>> import calc as cal


2. >>> cal.sub

<function sub at 0x0655CC90>

6. How to Execute Python Modules as Scripts?


Look at the following code:

1. def add(a,b):
2. print(a+b)
3. def sub(a,b):
4. print(a-b)
5. def mul(a,b):
6. print(a*b)
7. def div(a,b):
8. print(a/b)
9. def exp(a,b):
10. print(a**b)
11. def floordiv(a,b):
12. print(a//b)
13. if name == " main ":
14. import sys
15. if int(sys.argv[1])==1:
16. add(int(sys.argv[2]),int(sys.argv[3]))
17. elif int(sys.argv[1])==2:
18. sub(int(sys.argv[2]),int(sys.argv[3]))

These last few lines let us use the sys module to deal with command line arguments. To execute subtraction,
this is what we type in the command prompt:

C:\Users\lifei\Desktop\calc>python calc.py 2 3 4

-1

This way, you can complete the code for other operations as well. Hence, we’ve created a script. But we can
also import this normally like a module:

1. >>> import calc


2. >>>

We may want to run a module as a script for testing purposes.

Any Doubt yet in Python Modules? Please Comment.

7. Python Module Search Path


Whenever we import Python modules, say eggs, the interpreter searches a built-in version. If not found, it
searches for a file named eggs.py under a list of directories given by variable sys.path. This variable is
initialized from the following locations:

 The directory holding the input script (or the current directory, in case no file is specified).
 PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
 The installation-dependent default.

Once initialized, a Python program may modify sys.path.

8. Compiled Python Files


In an attempt to speed up loading a module, Python will cache each module’s compiled version in the
pycache directory. It does so under the name module.version.pyc. Here, the version encodes the compiled
file’s format. For instance, under CPython 3.3, we’ll have eggs.py as pycache /eggs.cpython-33.pyc. This
allows compiled modules from different Python versions and releases to coexist. These compiled modules are
platform-independent.
If the compiled version is out of date, Python recompiles it automatically.
9. Python Standard Modules
And like we’ve always said, Python ships with a library of standard Python modules. While some of them are
built into the interpreter, we can create our own. The standard ones lend us extra functionality, in turn reducing
the need to code too much. Other times, they provide efficiency to a programmer, in cases like providing access
to operating system primitives, the likes of system calls.

The module sys is built into every Python interpreter. However, some modules are only available to certain
operating platforms. For instance, the winreg module is only available to Windows programmers.

The sys module will also tell you which version of Python you are using.

1. >>> import sys


2. >>> sys.version

‘3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)]’

10. Python dir() Function


The dir() is a built-in function that returns a sorted list of all the names that a Python modules defines.

1. >>> dir(sys)

[‘ displayhook ’, ‘ doc ’, ‘ excepthook ’, ‘ interactivehook ’, ‘ loader ’, ‘ name ’,


‘ package ’, ‘ spec ’, ‘ stderr ’, ‘ stdin ’, ‘ stdout ’, ‘_clear_type_cache’, ‘_current_frames’,
‘_debugmallocstats’, ‘_enablelegacywindowsfsencoding’, ‘_getframe’, ‘_home’, ‘_mercurial’, ‘_xoptions’,
‘api_version’, ‘argv’, ‘base_exec_prefix’, ‘base_prefix’, ‘builtin_module_names’, ‘byteorder’, ‘call_tracing’,
‘callstats’, ‘copyright’, ‘displayhook’, ‘dllhandle’, ‘dont_write_bytecode’, ‘exc_info’, ‘excepthook’,
‘exec_prefix’, ‘executable’, ‘exit’, ‘flags’, ‘float_info’, ‘float_repr_style’, ‘get_asyncgen_hooks’,
‘get_coroutine_wrapper’, ‘getallocatedblocks’, ‘getcheckinterval’, ‘getdefaultencoding’,
‘getfilesystemencodeerrors’, ‘getfilesystemencoding’, ‘getprofile’, ‘getrecursionlimit’, ‘getrefcount’,
‘getsizeof’, ‘getswitchinterval’, ‘gettrace’, ‘getwindowsversion’, ‘hash_info’, ‘hexversion’, ‘implementation’,
‘int_info’, ‘intern’, ‘is_finalizing’, ‘last_traceback’, ‘last_type’, ‘last_value’, ‘maxsize’, ‘maxunicode’,
‘meta_path’, ‘modules’, ‘path’, ‘path_hooks’, ‘path_importer_cache’, ‘platform’, ‘prefix’,
‘set_asyncgen_hooks’, ‘set_coroutine_wrapper’, ‘setcheckinterval’, ‘setprofile’, ‘setrecursionlimit’,
‘setswitchinterval’, ‘settrace’, ‘stderr’, ‘stdin’, ‘stdout’, ‘thread_info’, ‘version’, ‘version_info’, ‘warnoptions’,
‘winver’]

1. >>> for i in dir(calc): print(i)

builtins
cached
doc
file
loader
name
package
spec
add
div
exp
floordiv
mul
sub
And without any arguments, dir() returns a lilst of the names that we have defined currently.

1. >>> dir()

[‘ annotations ’, ‘ builtins ’, ‘ doc ’, ‘ loader ’, ‘ name ’, ‘ package ’, ‘ spec ’, ‘add’, ‘cal’,


‘calc’, ‘div’, ‘exp’, ‘floordiv’, ‘i’, ‘mul’, ‘os’, ‘sub’, ‘sys’]

To get a list of built-in functions and variables, we do the following, instead:

1. >>> import builtins


2. >>> dir(builtins)

[‘ArithmeticError’, ‘AssertionError’, ‘AttributeError’, ‘BaseException’, ‘BlockingIOError’, ‘BrokenPipeError’,


‘BufferError’, ‘BytesWarning’, ‘ChildProcessError’, ‘ConnectionAbortedError’, ‘ConnectionError’,
‘ConnectionRefusedError’, ‘ConnectionResetError’, ‘DeprecationWarning’, ‘EOFError’, ‘Ellipsis’,
‘EnvironmentError’, ‘Exception’, ‘False’, ‘FileExistsError’, ‘FileNotFoundError’, ‘FloatingPointError’,
‘FutureWarning’, ‘GeneratorExit’, ‘IOError’, ‘ImportError’, ‘ImportWarning’, ‘IndentationError’, ‘IndexError’,
‘InterruptedError’, ‘IsADirectoryError’, ‘KeyError’, ‘KeyboardInterrupt’, ‘LookupError’, ‘MemoryError’,
‘ModuleNotFoundError’, ‘NameError’, ‘None’, ‘NotADirectoryError’, ‘NotImplemented’,
‘NotImplementedError’, ‘OSError’, ‘OverflowError’, ‘PendingDeprecationWarning’, ‘PermissionError’,
‘ProcessLookupError’, ‘RecursionError’, ‘ReferenceError’, ‘ResourceWarning’, ‘RuntimeError’,
‘RuntimeWarning’, ‘StopAsyncIteration’, ‘StopIteration’, ‘SyntaxError’, ‘SyntaxWarning’, ‘SystemError’,
‘SystemExit’, ‘TabError’, ‘TimeoutError’, ‘True’, ‘TypeError’, ‘UnboundLocalError’, ‘UnicodeDecodeError’,
‘UnicodeEncodeError’, ‘UnicodeError’, ‘UnicodeTranslateError’, ‘UnicodeWarning’, ‘UserWarning’,
‘ValueError’, ‘Warning’, ‘WindowsError’, ‘ZeroDivisionError’, ‘_’, ‘ build_class ’, ‘ debug ’, ‘ doc ’,
‘ import ’, ‘ loader ’, ‘ name ’, ‘ package ’, ‘ spec ’, ‘abs’, ‘all’, ‘any’, ‘ascii’, ‘bin’, ‘bool’,
‘bytearray’, ‘bytes’, ‘callable’, ‘chr’, ‘classmethod’, ‘compile’, ‘complex’, ‘copyright’, ‘credits’, ‘delattr’, ‘dict’,
‘dir’, ‘divmod’, ‘enumerate’, ‘eval’, ‘exec’, ‘exit’, ‘filter’, ‘float’, ‘format’, ‘frozenset’, ‘getattr’, ‘globals’,
‘hasattr’, ‘hash’, ‘help’, ‘hex’, ‘id’, ‘input’, ‘int’, ‘isinstance’, ‘issubclass’, ‘iter’, ‘len’, ‘license’, ‘list’, ‘locals’,
‘map’, ‘max’, ‘memoryview’, ‘min’, ‘next’, ‘object’, ‘oct’, ‘open’, ‘ord’, ‘pow’, ‘print’, ‘property’, ‘quit’, ‘range’,
‘repr’, ‘reversed’, ’round’, ‘set’, ‘setattr’, ‘slice’, ‘sorted’, ‘staticmethod’, ‘str’, ‘sum’, ‘super’, ‘tuple’, ‘type’,
‘vars’, ‘zip’]

This was all on Python modules. Hope the Python Modules article was informative.
11. Conclusion
While this is all about Python modules, we suggest you should also read about Packages in Python. Then,
maybe you should switch to Packages vs Modules. For any question regarding, Please Comment. Until then,
have a good day.

Python Pickle | What is Serialization in Python with


Example
by DataFlair Team · September 27, 2018

1. Python Pickle Tutorial


In the Last tutorial, we talked about Python Virtual Environment. In this Python Pickle tutorial, we will study
what is a Pickle in Python and how Python Serialization deals with the ‘pickle’ module of Python for the
purpose of serialization. At last, we will discuss some Python Pickle Examples.

So, let’s start the Python Pickle Tutorial.

Python Pickle and Python Serialization

2. What is Serialization in Python?


In Python, when we want to serialize and de-serialize a Python object, we use functions and methods from the
module Python Pickle. Pickling, then, is the act of converting a Python object into a byte stream. We also call
this ‘serialization’, ‘marshalling’, or ‘flattening’. Unpickling is its inverse, ie., converting a byte stream from a
binary file or bytes-like object into an object. Lets start with comparing Python serialize with other modules of
Python.
3. Comparing Python Pickle to Other Python Modules
a. Comparing Python pickle to marshal
‘marshal’ is a more primitive module for serialization in Python, and its purpose is to support .pyc files.
However, we prefer Python pickle. The two differ in the following ways:

1. Python pickle tracks the objects it has serialized. Because of this, it doesn’t have to serialize the same
objects again when it references them again. This is unlike marshal.
2. marshal cannot serialize user-defined classes and their instances. If the class definition is importable
and in the same module as when we stored the object, pickle can save and restore class instances.
3. The serialization format for pickle in Python is backwards-compatible. This isn’t the same with marshal.

b. Comparing Python pickle to json


json is a standard library module for serialization and deserialization with Python.

1. Where Python pickle has a binary serialization format, json has a text serialization format.
2. Python pickle isn’t human-readable, but marshal isn’t.
3. pickle is Python-specific, but JSON is interoperable.
4. pickle can represent a very large number of Python types. However, json can only represent a subset of
Python’s in-built types.

4. Python Pickle Supports Data Stream Format


Python pickle uses a Python-specific data format. So, external standards like JSON or XDR impose no
restrictions. But this makes for inability of non-Python programs to reconstruct pickled Python objects.

Like we said above, Python pickle uses a data format with a relatively compact binary representation. We can
efficiently compress it.

Complementary to Python pickle is the module ‘pickletools’ for analyzing data streams that it generates.

We have five different protocols for pickling:

1. Protocol version 0: Original, human-readable protocol; backwards-compatible with earlier versions of


Python.
2. Protocol version 1: Old, binary format; compatible with earlier versions of Python.
3. Protocol version 2: Added in Python 2.3; provides more efficient pickling of new-style classes.
4. Protocol version 3: Introduced in Python 3.0; default; supports bytes objects; cannot be unpickled by
Python 2.x. It is recommended when we need compatibility with other Python 3 versions.
5. Protocol version 4: Introduced in Python 3.4; supports very large objects, more kinds of objects, and
certain data format optimizations.
5. Python Pickle Module Interface
To serialize and deserialize, we use functions dumps() and loads(), respectively. Alternatively, we can create
our own Pickler and Unpickler objects for more control over this.
Python pickle has two constants:

a. HIGHEST_PROTOCOL
This is an integer, and it holds the highest protocol version that is available. We can pass this as a protocol
value to dump() and dumps(), and to the Pickler constructor.

b. DEFAULT_PROTOCOL
Also an integer, this holds the default protocol version for pickling. The default is currently Protocol 3.

It also has the following functions:

i. dump(obj, file, protocol=None, *, fix_imports=True)


This writes a pickled representation of object obj to file, an open file object. Consider this equivalent to
Pickler(file, protocol).dump(obj)

1. >>> x=7
2. >>> import os
3. >>> os.chdir('C:\\Users\\lifei\\Desktop')
4. >>> import pickle
5. >>> f=open('abcde.txt','r+b') //opened it in binary mode to pickle
6. >>> pickle.dump(x,f)

When we checked in the file abcde.txt, we found this:

€K. €K.€K.

file, here, must have a write() method accepting a single bytes argument. So, it can be a file you opened in
binary mode, an io.BytesIO instance, or a custom object meeting this interface. Protocol lets us choose which
protocol to use.

When fix_imports is true and we use a protocol less than 3, pickle maps new Python 3 names to old module
names in Python 2. This lets Python 2 read the pickle data stream.

ii. dumps(obj, protocol=None, *, fix_imports=True)


This returns the pickled representation of obj as a bytes object. This does not write it to a file.

1. >>> pickle.dumps(x)
b’\x80\x03K\x07.’

iii. load(file, *, fix_imports=True, encoding=”ASCII”, errors=”strict”)


load() takes in file, an open file object, reads a pickled representation from it, and returns the reconstructed
object hierarchy. Consider this equivalent to Unpickler(file).load()
file can be a file object opened in the binary reading mode, an io.BytesIO object, or an object that meets its
interface. This is because it must have two methods- read(), that takes one integer argument, and readline(), that
takes no arguments. Both of these methods must return bytes.

fix_imports , encoding, and errors help control compatibility support for pickle streams by Python 2. When
fix_imports is true, pickle maps old Python 2 names to new Python 3 names. The other two guide pickle with
decoding 8-but string instances pickled by Python 2. The default encoding is ‘ASCII’, and the default value for
errors is ‘strict’. To read such 8-bit string instances as bytes objects, we can set the encoding to ‘bytes’.

Let’s try doing this.

1. >>> pickle.load(f)

Traceback (most recent call last):

File “<pyshell#63>”, line 1, in <module>

pickle.load(f)

EOFError: Ran out of input

Uh-oh. Let’s get to the beginning of the file.

1. >>> f.seek(0)

Now, we can successfully load it.

1. >>> pickle.load(f)

iv. loads(bytes_object, *, fix_imports=True, encoding=”ASCII”,


errors=”strict”)
This function takes in a bytes object, reads a pickled object hierarchy, and returns the reconstructed object
hierarchy.

fix_imports, encoding, and errors help control compatibility support for pickle streams that Python 2 generates.
When it is true, pickle maps old Python 2 names to new Python 3 names. encoding guides pickle with decoding
8-bit string instances pickled by Python 2. The default for encoding is ‘ASCII’, and that for errors is ‘strict’. To
read such 8-byte instances as bytes objects, we can set the encoding to ‘bytes’.

1. >>> f.seek(0)

1. >>> pickle.loads(f.read())

6. Python Pickle Exceptions


The Python pickle module also defines three kinds of exceptions:

a. PickleError

This is the common parent class for all other pickling exceptions. It, in turn, inherits from Exception.

b. PicklingError

When the Pickler encounters an unpicklable object, it raises a PicklingError. This class inherits from
PickleError.

c. UnpicklingError

When Python pickle cannot unpickle an object due to data corruption or a security violation, it raises an
UnpicklingError. This inherits from PickleError.

Some other exceptions we observe when pickling, as we did above, include:


EOFError
TypeError
ValueError
AttributeError
ImportError
IndexError

Learn: Python Recursion with Examples

7. Imported Classes in Python Pickle


Python pickle imports two classes- Pickler and Unpickler:

a. Pickler(file, protocol=None, *, fix_imports=True)


Pickler takes in a binary file and writes a pickle data stream.
file must have a write() method accepting a single bytes argument. This can be a file object for a file opened for
writing in binary mode, an io.BytesIO instance, or a custom object meeting this interface.
protocol is an integer, and informs the pickler about which protocol to use (0 to HIGHEST_PROTOCOL).
Otherwise, it uses DEFAULT_PROTOCOL. On providing a negative number, it selects
HOGHEST_PROTOCOL.

When fix_imports is true and the protocol version is less than 3, pickle maps new Python 3 names to old Python
2 names. This makes the Python data stream readable by Python 2.

Python Pickler has the following members:

i. dump(obj)
This takes in obj and writes a pickled representation of it to the open file object specified in the constructor of
Pickler.

ii. persistent_id(obj)
By default, it does nothing. It only exists to let subclasses override it. If it returns none, pickle pickles obj as
usual. Otherwise, Pickler emits the returned value as a persistent ID for obj. Unpickler.persistent_load() defines
this context.

iii. dispatch_table
For an object of Pickler, a dispatch table is a registry holding reduction functions that we can declare with
copyreg.pickle(). This mapping has classes as its keys, and reduction functions as its values.

A reduction function takes one argument of the class, and conforms to this interface as a reduce () method.

But pickler objects don’t have dispatch_tables by default. Instead, it makes use of the global dispatch table that
the copyreg module manages. To customize pickling for an object of a specific object of Pickler, we can set
dispatch_table to a dict-like object. Or, if one of the subclasses of Pickler has dispatch_table, then this serves as
the default dispatch table for instances of that class.

iv. fast
Although this is deprecated(no longer advised), it enables fast mode when set to true. This mode disables
memo, thereby speeding pickling as it doesn’t generate extra PUT opcodes. However, do not use it with self-
referential objects, as it can set Pickler off into infinite recursion.

For more compact pickles, we can use pickletools.optimize().

b. Unpickler(file, *, fix_imports=True, encoding=”ASCII”,


errors=”strict”)
The Unpickler takes in a binary file and reads a pickle data stream.
file must have the methods read()- that takes an integer argument, and readline()- that needs no arguments. Both
of these methods must return bytes. This can be a file object opened for reading in binary mode, an io.BytesIO
object, or a custom object meeting this interface.

pickle automatically detects the version of protocol used; we don’t need an argument for that.

fix_imports, encoding, and errors help control compatibility support for pickle streams generated by Python 2.
When fix_imports is true, pickle maps old Python 2 names to new Python 3 names. encoding and errors guide
pickle with decoding 8-bit string instances pickled by Python 2. The default for encoding is ‘ASCII’, and that
for errors is ‘strict’. When we want to read such 8-bit string instances as bytes objects, we can set the
encoding to ‘bytes’.

Unpickler has the following members:

1. load()

This takes in an open file object, reads a pickled object representation, and returns the reconstructed object
hierarchy.

2. persistent_load(pid)

By default, this raises an UnpicklingError. When we define it, however, it must return the object pertaining to
the persistent ID pid. If we pass an invalid persistent ID, it raises an UnpicklingError.

3. find_class(module,name)

If necessary, it imports module, and returns the object name from it. Here, module and name are str objects. We
can also use find_class() to find functions.

A subclass can override this to control what kind of objects it can take, and how we can load them. This
alleviates security risks.

Any doubt yet in Python Pickle? Please Comment.

7. What Can We Pickle and Unpickle?


We can pickle the following types:

 None, True, and False


 integers, floating point numbers, complex numbers
 strings, bytes, bytearrays
 tuples, lists, sets, and dictionaries holding only picklable objects
 functions defined at a module’s top level (using def, not lambda)
 built-in functions defined at a module’s top level
 classes defined at a module’s top level
 instances of such classes whose dict or the result of calling getstate () is picklable

When we try to pickle an unpicklable object, pickle raises the PicklingError exception. In this process, it is
possible that an unspecified number of bytes have already been written to the file.
In trying to pickle a highly-recursive data structure, we may exceed the maximum recursion depth. Such a case
raises a RecursionError. However, we can raise that limit with sys.setrecursionlimit().
Let’s take a quick look.

We pickle functions by their ‘fully-qualified’ name references, not by their values. This way, we only pickle the
function name and the module it resides in. We do not pickle the function’s code or attributes. So, we should be
able to import the defining module in the unpickling environment. This module must hold the named object.
Otherwise, it raises an exception.

We pickle classes by named reference. This way, the same restrictions apply in the unpickling environment. We
do not pickle the class’ code or data. We only pickle instance data.
Such restrictions mandate that we define picklable classes and functions in a module’s top level.

This was all on Python Pickle and Python Serialization. Hope you now understand Python Serialization.

8. Conclusion: Python Pickle and Serialization


Simply speaking, Python serialization is the act of converting a Python object into a byte stream. In Python, we
use the module ‘pickle’, which has a binary serializable format. We can also serialize classes and functions. We
have also studied in detail about Python Pickle and its comparison with other modules. If you have any queries
in Python pickle or Python Serialization, Please Comment.

Python Packages Tutorial – How to Create Your Own


Package
by DataFlair Team · September 26, 2018

1. Python Packages Tutorial


In today’s article, we will discuss Python Packages. Moreover, we will learn the structure of Python Packages
and how to import modules from packages in Python.

So, let’s start the Python Packages Tutorial.


Python Packages Tutorial – How to Create Your Own Package in Python

2. What are Python Packages?


In our computer systems, we store our files in organized hierarchies. We don’t store them all in one location.
Likewise, when our programs grow, we divide it into packages. In real-life projects, programs are much larger
than what we deal with in our journey of learning Python. A package lets us hold similar modules in one place.

Like a directory may contain subdirectories and files, a package may contain sub-packages and modules. We
have been using modules a lot in the previous lessons. Remember math, os, and collections? Those were all
modules that ship with Python officially. We will discuss the difference between a module and a package in our
next lesson. But for now, let’s dive into the world of Python packages.

3. Structure of Python Packages


As we discussed, a package may hold other Python packages and modules. But what distinguishes a package
from a regular directory? Well, a Python package must have an init .py file in the directory. You may leave
it empty, or you may store initialization code in it. But if your directory does not have an init .py file, it
isn’t a package; it is just a directory with a bunch of Python scripts. Leaving init .py empty is indeed good
practice.
Take a look at the following structure for a game:

Python Packages Module Structure


Here, the root package is Game. It has sub packages Sound, Image, and Level, and file init .py. Sound
further has modules load, play, and pause, apart from file init .py. Image has modules open, change, and
close, apart from init .py. Finally, Level has modules start, load, and over, apart from init .py.

4. How to Import Modules from Packages


in Python?
A Python package may contain several modules. To import one of these into your program, you must use the
dot operator(.)

In the above example, if you want to import the load module from subpackage sound, we type the following at
the top of our Python file:

import Game.Sound.load

Note that we don’t type the extension, because that isn’t what we refer to the module as. The subpackage Level
has a module named load too, but there is no clash here. This is because we refer to the module by its fully
qualified name.

To escape having to type so much every time we needed to use the module, we could also import it under an
alias:

import Game.Sound.load as loadgame

(If you’re working the interpreter, you may also do the following:
loadgame=Game.Sound.load

This works equally fine.)

Alternatively, you could do:

from Game.Sound import load

Now, if the Sound subpackage has a function volume_up(), we call it this way:
loadgame.volume_up(7)

If we imported this way:

from Game.Sound.load import volume_up() as volup

We could call the function simply, without needing to use a full qualifier:
volup(7)

But this isn’t recommended, as this may cause names in a namespace to clash.
5. Further Notes
When you import a package, only the modules directly under it are imported. An import does not import the sub
packages.

1. >>> import one


2. >>> one.two

Traceback (most recent call last):

File “<pyshell#488>”, line 1, in <module>

one.two.evenodd

AttributeError: module ‘one’ has no attribute ‘two’

Also note that if you want to check where your Python packages are being created, your path will look
something like this:

C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\Lib\site-packages

6. How to Create Your Own Python Package?


Now, on to the most interesting part. Like we said, Python packages are nothing but a dictionary with sub-
packages and modules, and an init .py file.
In our example, this is the hierarchy we create:

How to Create Your Own Python Package

This is what we have in evenodd.py:

1. def check():
2. a=int(input('Enter a number'))
3. if a%2==0: print("Even")
4. else: print("Odd")

Also, we keep each init .py empty.

Now, we import and use it this way:

1. >>> from one.two.evenodd import check as check


2. >>> check()

Enter a number7
Odd

1. >>> check()

Enter a number0
Even

So, this was all about Python Packages. Hope you like our explanation.

7. Conclusion
In this Python Packages tutorial, we discussed packages, and how to create them. Apart from that, the Python
Package Index(PyPI) provides us with a lot of Python packages to help us with our projects. We talked about
this in our Introduction to Python. Still, have a confusion? Feel free to ask in the comment box.

List of 63 Python os Module with Syntax & Examples


(Latest)
by DataFlair Team · May 27, 2019

1. Python os Module
In this tutorial on Python os Module, we will get closer to the os module and its methods. Moreover, we will
study syntax and examples of os Module in Python Programming Language.

So, let’s start Python Module Tutorial


List of 63 Python os Module with Syntax & Examples (Latest)

2. Python os Module
The Python OS module lets us work with files and directories. We have been using it a lot to get to the Desktop
in our examples. But it is much more. Let’s discuss the important functions/methods it offers. In case of any
doubt, please as us in comments. Let’s check the dir() on this module?

1. >>> dir(os)

[‘DirEntry’, ‘F_OK’, ‘MutableMapping’, ‘O_APPEND’, ‘O_BINARY’, ‘O_CREAT’, ‘O_EXCL’, ‘O_NOINHERIT’,


‘O_RANDOM’, ‘O_RDONLY’, ‘O_RDWR’, ‘O_SEQUENTIAL’, ‘O_SHORT_LIVED’, ‘O_TEMPORARY’, ‘O_TEXT’,
‘O_TRUNC’, ‘O_WRONLY’, ‘P_DETACH’, ‘P_NOWAIT’, ‘P_NOWAITO’, ‘P_OVERLAY’, ‘P_WAIT’, ‘PathLike’,
‘R_OK’, ‘SEEK_CUR’, ‘SEEK_END’, ‘SEEK_SET’, ‘TMP_MAX’, ‘W_OK’, ‘X_OK’, ‘_Environ’, ‘ all ’, ‘ builtins ’,
‘ cached ’, ‘ doc ’, ‘ file ’, ‘ loader ’, ‘ name ’, ‘ package ’, ‘ spec ’, ‘_execvpe’, ‘_exists’,
‘_exit’, ‘_fspath’, ‘_get_exports_list’, ‘_putenv’, ‘_unsetenv’, ‘_wrap_close’, ‘abc’, ‘abort’, ‘access’, ‘altsep’,
‘chdir’, ‘chmod’, ‘close’, ‘closerange’, ‘cpu_count’, ‘curdir’, ‘defpath’, ‘device_encoding’, ‘devnull’, ‘dup’,
‘dup2’, ‘environ’, ‘errno’, ‘error’, ‘execl’, ‘execle’, ‘execlp’, ‘execlpe’, ‘execv’, ‘execve’, ‘execvp’, ‘execvpe’,
‘extsep’, ‘fdopen’, ‘fsdecode’, ‘fsencode’, ‘fspath’, ‘fstat’, ‘fsync’, ‘ftruncate’, ‘get_exec_path’,
‘get_handle_inheritable’, ‘get_inheritable’, ‘get_terminal_size’, ‘getcwd’, ‘getcwdb’, ‘getenv’, ‘getlogin’,
‘getpid’, ‘getppid’, ‘isatty’, ‘kill’, ‘linesep’, ‘link’, ‘listdir’, ‘lseek’, ‘lstat’, ‘makedirs’, ‘mkdir’, ‘name’, ‘open’,
‘pardir’, ‘path’, ‘pathsep’, ‘pipe’, ‘popen’, ‘putenv’, ‘read’, ‘readlink’, ‘remove’, ‘removedirs’, ‘rename’,
‘renames’, ‘replace’, ‘rmdir’, ‘scandir’, ‘sep’, ‘set_handle_inheritable’, ‘set_inheritable’, ‘spawnl’, ‘spawnle’,
‘spawnv’, ‘spawnve’, ‘st’, ‘startfile’, ‘stat’, ‘stat_float_times’, ‘stat_result’, ‘statvfs_result’, ‘strerror’,
‘supports_bytes_environ’, ‘supports_dir_fd’, ‘supports_effective_ids’, ‘supports_fd’,
‘supports_follow_symlinks’, ‘symlink’, ‘sys’, ‘system’, ‘terminal_size’, ‘times’, ‘times_result’, ‘truncate’,
‘umask’, ‘uname_result’, ‘unlink’, ‘urandom’, ‘utime’, ‘waitpid’, ‘walk’, ‘write’]

3. access(path,mode)

This method uses the real uid/gid to test for access to a path. If access is allowed, it returns True. Else, it returns
False. The first argument is the path; the second is the mode. The mode can take one of four values:
1. os.F_OK — Found
2. os.R_OK — Readable
3. os.W_OK — Writable
4. os.X_OK — Executable

Now, let’s take an example.

1. >>> os.chdir('C:\\Users\\lifei\\Desktop')
2. >>> os.access('Today.txt',os.R_OK)

True

1. >>> os.access('Today.txt',os.F_OK)

True

1. >>> os.access('Today.txt',os.W_OK)

True

1. >>> os.access('Today.txt',os.X_OK)

True

4. chdir(path)

This Python os module changes the current working directory to the path we specify.
Does this need another example?

1. >>> os.chdir('C:\\Users\\lifei\\Desktop')

It returns None.

5. chflags(path,flags)

chflags() sets path flags to the numeric flags. These flags may take a combination(bitwise OR) of the following
values:

 os.UF_NODUMP – Don’t dump the file


 os.UF_IMMUTABLE − You may not change the file
 os.UF_APPEND − You may only append to the file
 os.UF_NOUNLINK – You may not rename or delete the file
 os.UF_OPAQUE − The directory is opaque when we view it through a union stack
 os.SF_ARCHIVED – You may archive the file
 os.SF_IMMUTABLE – You may not change the file
 os.SF_APPEND – You may only append to the file
 os.SF_NOUNLINK – You may not rename or delete the file
 os.SF_SNAPSHOT − It is a snapshot file

Most flags are such that only the super-user can change them. Also, some flags don’t work on all systems.
Sample usage:

1. >>> os.chflags('Today.txt',os.SF_NOUNLINK)

6. chmod(path,mode)

This Python os Module alters the mode of the path to the passed numeric mode. The mode may be on of the
following values(or a bitwise OR combination of them):

 stat.S_ISUID − Set user ID on execution


 stat.S_ISGID − Set group ID on execution
 stat.S_ENFMT – Enforced record locking
 stat.S_ISVTX – After execution, save text image
 stat.S_IREAD − Read by owner
 stat.S_IWRITE − Write by owner
 stat.S_IEXEC − Execute by owner
 stat.S_IRWXU − Read, write, and execute by owner
 stat.S_IRUSR − Read by owner
 stat.S_IWUSR − Write by owner
 stat.S_IXUSR − Execute by owner
 stat.S_IRWXG − Read, write, and execute by group
 stat.S_IRGRP − Read by group
 stat.S_IWGRP − Write by group
 stat.S_IXGRP − Execute by group
 stat.S_IRWXO − Read, write, and execute by others
 stat.S_IROTH − Read by others
 stat.S_IWOTH − Write by others
 stat.S_IXOTH − Execute by others

Sample usage:

1. >>> import stat


2. >>> os.chmod('Today.txt',stat.S_ISVTX)

This method does not return any value.

7. chroot(path)

chroot Python os Module alters the current process’ root directory to the given path. To use this, we need super-
user privileges.

Sample usage:

1. >>> os.chroot("/Photos")

This method returns no value.

8. close(fd)

This Python os module closes the associated file with descriptor fd.
1. >>> fd=os.open('Today.txt',os.O_RDWR)
2. >>> os.close(fd)

It does not return any value.

9. closerange(fd_low,fd_high)

closerange() closes all file descriptors from fd_low to fd_high. Here, fd_low is inclusive, and fd_high is
exclusive. Here, fd_low is the lowest file descriptor to be closed, while fd_high is the highest. This method
ignores errors.

Sample usage:

1. >>> fd = os.open( "Today.txt", os.O_RDWR)


2. >>> os.write(fd, "Testing")
3. >>> os.closerange( fd, fd)

This method does not return any value.

10. dup(fd)

Python os Module dup(fd) returns a duplicate of the file descriptor fd.


Sample usage:

1. >>> fd = os.open( "Today.txt", os.O_RDWR)


2. >>> d_fd = os.dup( fd )
3. >>> os.write(d_fd, "Testing")
4. >>> os.closerange( fd, d_fd)

This method returns a duplicate of the file descriptor.

11. dup2(fd,fd2)

dup2() duplicates the descriptor fd to fd2. And if necessary, it closes fd2 first.

The interpreter assigns the new file description only when it is available.

Sample usage:

1. >>> fd = os.open( "Today.txt", os.O_RDWR)


2. >>> os.write(fd, "Testing")
3. >>> fd2 = 1000
4. >>> os.dup2(fd, fd2)
5. >>> os.lseek(fd2, 0, 0)
6. >>> str = os.read(fd2, 100)
7. >>> print(f"Read String is {str}")
8. >>> os.close( fd )

This method returns a duplicate of the file descriptor.


12. fchdir(fd)

fchdir() alters the current working directory to the directory that the file descriptor fd represents. For this, it is
mandatory that the descriptor must refer to an opened directory, and not to an open file.
Sample usage:

1. >>> os.chdir("/var/www/html" )
2. >>> print "Current working dir : %s" % os.getcwd()
3. >>> fd = os.open( "/tmp", os.O_RDONLY )
4. >>> os.fchdir(fd)
5. >>> print "Current working dir : %s" % os.getcwd()
6. >>> os.close( fd )

This method doesn’t return any value.

13. fchmod(fd,mode)

This Python os Module alters the file mode of the file, specified by fd, to the numeric mode. The mode may be
one of the following (or an ORed combination of):

 stat.S_ISUID − Set user ID on execution


 stat.S_ISGID − Set group ID on execution
 stat.S_ENFMT − Record locking enforced
 stat.S_ISVTX − Save text image aGer execution
 stat.S_IREAD − Read by owner
 stat.S_IWRITE − Write by owner
 stat.S_IEXEC − Execute by owner
 stat.S_IRWXU − Read, write, and execute by owner
 stat.S_IRUSR − Read by owner
 stat.S_IWUSR − Write by owner
 stat.S_IXUSR − Execute by owner
 stat.S_IRWXG − Read, write, and execute by group
 stat.S_IRGRP − Read by group
 stat.S_IWGRP − Write by group
 stat.S_IXGRP − Execute by group
 stat.S_IRWXO − Read, write, and execute by others
 stat.S_IROTH − Read by others
 stat.S_IWOTH − Write by others
 stat.S_IXOTH − Execute by others

Sample usage:

1. >>> fd = os.open( "/tmp", os.O_RDONLY )


2. >>> os.fchmod( fd, stat.S_IXGRP)
3. >>> os.fchmod(fd, stat.S_IWOTH)
4. >>> print "Changed mode successfully!!"
5. >>> os.close( fd )

This method doesn’t return any value.


14. fchown(fd,uid,gid)

fchown() alters the owner and the group id of the file specified by fd to the numeric uid and gid. Setting an id to
-1 leaves it unchanged.
Sample usage:

1. >>> fd = os.open( "/tmp", os.O_RDONLY )


2. >>> os.fchown( fd, 100, -1)
3. >>> os.fchown( fd, -1, 50)
4. >>> print "Changed ownership successfully!!"
5. >>> os.close( fd )

This method doesn’t return any value.

15. fdatasync(fd)

fdatasync() forces writing the file with filedescriptor fd to disk. This, however, doesn’t force update on
metadata. You can do this to flush your buffer.

Sample usage:

1. >>> fd = os.open( "Today.txt", os.O_RDWR)


2. >>> os.write(fd, "Testing")
3. >>> os.fdatasync(fd)
4. >>> os.lseek(fd, 0, 0)
5. >>> str = os.read(fd, 100)
6. >>> print(f"Read String is {str}")
7. >>> os.close( fd )

This method doesn’t return any value.

16. fdopen(fd[, mode[, bufsize]])

fdopen(), Python os Module returns an open file object. This object is connected to the descriptor fd. Once you
do this, you can perform all defined functions on the file object.
Sample usage:

1. >>> fd = os.open( "Today.txt", os.O_RDWR)


2. >>> fo = os.fdopen(fd, "w+")
3. >>> print (f"Current I/O pointer position {fo.tell()}")
4. >>> fo.write( "Python is a great language.\nYeah its great!!\n");
5. >>> os.lseek(fd, 0, 0)
6. >>> str = os.read(fd, 100)
7. >>> print (f"Read String is {str}")
8. >>> print (f"Current I/O pointer position {fo.tell()}")
9. >>> fo.close()

fdopen() returns an open file object that is connected to the file descriptor.

17. fpathconf(fd, name)


fpathconf() returns system configuration information that is relevant to an open file. This is quite similar to the
unix system call fpathconf(). It also accepts similar arguments.
Sample usage:

1. >>> fd = os.open( "Today.txt", os.O_RDWR)


2. >>> print (f"{os.pathconf_names}")
3. >>> no = os.fpathconf(fd, 'PC_LINK_MAX')
4. >>> print (f"Maximum number of links to the file: {no}")
5. >>> no = os.fpathconf(fd, 'PC_NAME_MAX')
6. >>> print (f"Maximum length of a filename :{no}")
7. >>> os.close( fd)

fpathconf() returns system configuration that is relevant to an open file.

18. fstat(fd)

Python os Module fstat() returns information about the file pertaining to the fd. Let’s take a look at the structure
fstat() returns:

 st_dev − ID of device containing file


 st_ino − inode number
 st_mode – protection
 st_nlink − number of hard links
 st_uid − user ID of owner
 st_gid − group ID of owner
 st_rdev − device ID (if special file)
 st_size − total size, in bytes
 st_blksize − blocksize for filesystem I/O
 st_blocks − number of blocks allocated
 st_atime − time of last access
 st_mtime − time of last modification
 st_ctime − time of last status change

Sample usage:

1. >>> fd = os.open( "Today.txt", os.O_RDWR)


2. >>> info = os.fstat(fd)
3. >>> print (f"File Info: {info}")
4. >>> print (f"UID of the file: {info.st_uid}")
5. >>> print (f"GID of the file: {info.st_gid}")
6. >>> os.close( fd)

fstat() returns information about the file linked with the fd.

19. fstatvfs(fd)

This Python os module returns information pertaining to the file system containing the file linked with file
descriptor fd. This is the structure it returns:

 f_bsize − file system block size


 f_frsize − fragment size
 f_blocks − size of fs in f_frsize units
 f_bfree − free blocks
 f_bavail − free blocks for non-root
 f_files – inodes
 f_ffree − free inodes
 f_favail − free inodes for non-root
 f_fsid − file system ID
 f_flag − mount flags
 f_namemax − maximum filename length

Sample usage:

1. >>> fd = os.open( "Today.txt", os.O_RDWR)


2. >>> info = os.fstatvfs(fd)
3. >>> print(f"File Info: {info}")
4. >>> print(f"Maximum filename length: {info.f_namemax}")
5. >>> print (f"Free blocks: {info.f_bfree}")
6. >>> os.close( fd)

fstatvfs() returns information about the file system containing the file linked.

20. fsync(fd)

This Python os Module forces write on the file liknked to the descriptor fd to disk. Beginning with a Python file
object f, first execute f.flush(), then perform os.fsync(f.fileno()). Do this to ensure all internal buffers linked to f
are written to the disk.
Sample usage:

1. >>> fd = os.open( "Today.txt", os.O_RDWR)


2. >>> os.write(fd, "Testing")
3. >>> os.fsync(fd)
4. >>> os.lseek(fd, 0, 0)
5. >>> str = os.read(fd, 100)
6. >>> print("Read String is: {str} ")
7. >>> os.close( fd )

fsync() doesn’t return any value.

21. ftruncate(fd,length)

ftruncate() truncates the file linked to the descriptor fd, so it holds at most length bytes in size.
Sample usage:

1. >>> fd = os.open( "Today.txt", os.O_RDWR)


2. >>> os.write(fd, "Testing")
3. >>> os.ftruncate(fd, 10)
4. >>> os.lseek(fd, 0, 0)
5. >>> str = os.read(fd, 100)
6. >>> print("Read String is: {str}”)
7. >>> os.close( fd )

ftruncate() doesn’t return any value.


22. getcwd()

getcwd() Python os Module returns the current working directory of a process.


Sample usage:

1. >>> os.getcwd()

‘C:\\Users\\lifei\\Desktop’

23. getcwdu()
getcwdu() returns a unicode object that represents the current working directory.
Sample usage:

1. >>> os.chdir("/var/www/html" )
2. >>> print(f"Current working dir: {os.getcwdu()}")
3. >>> fd = os.open( "/tmp", os.O_RDONLY )
4. >>> os.fchdir(fd)
5. >>> print(f"Current working dir: {os.getcwdu()}”)
6. >>> os.close( fd )

24. isatty(fd)
isatty()returns True if the descriptor fd is open, and is connected to a tty(-like) device. Otherwise, it returns
False.
Sample usage:

1. >>> fd = os.open( "Today.txt", os.O_RDWR)


2. >>> os.write(fd, "Testing")
3. >>> ret = os.isatty(fd)
4. >>> print(f"Returned value is: {ret}")
5. >>> os.close( fd )

25. lchflags(path,flags)
This Python os Module sets path flags to the numeric flags. Unlike chflags(), ut doesn’t follow symbolic links.
The flags may be one of the following values, or a bitwise OR combination of:

 UF_NODUMP − Do not dump the file


 UF_IMMUTABLE − The file may not be changed
 UF_APPEND − The file may only be appended to
 UF_NOUNLINK − The file may not be renamed or deleted
 UF_OPAQUE − The directory is opaque when viewed through a union stack
 SF_ARCHIVED − The file may be archived
 SF_IMMUTABLE − The file may not be changed
 SF_APPEND − The file may only be appended to
 SF_NOUNLINK − The file may not be renamed or deleted
 SF_SNAPSHOT − The file is a snapshot file.

Sample usage:
1. >>> path = "/var/www/html/Today.txt"
2. >>> fd = os.open( path, os.O_RDWR)
3. >>> os.close( fd )
4. >>> ret = os.lchflags(path, os.UF_IMMUTABLE )

lchflags() doesn’t return a value.

26. lchmod(path,mode)
lchmod() Python os Module ters the path mode to the numeric mode. If the path is a symlink, it affects the
symlink, not the target.
The mode may be one of the following values, or a bitwise OR combination of:

 stat.S_ISUID − Set user ID on execution


 stat.S_ISGID − Set group ID on execution
 stat.S_ENFMT − Record locking enforced
 stat.S_ISVTX − Save text image aGer execution
 stat.S_IREAD − Read by owner
 stat.S_IWRITE − Write by owner
 stat.S_IEXEC − Execute by owner
 stat.S_IRWXU − Read, write, and execute by owner
 stat.S_IRUSR − Read by owner
 stat.S_IWUSR − Write by owner
 stat.S_IXUSR − Execute by owner
 stat.S_IRWXG − Read, write, and execute by group
 stat.S_IRGRP − Read by group
 stat.S_IWGRP − Write by group
 stat.S_IXGRP − Execute by group
 stat.S_IRWXO − Read, write, and execute by others
 stat.S_IROTH − Read by others
 stat.S_IWOTH − Write by others
 stat.S_IXOTH − Execute by others

Sample usage:

1. >>> path = "/var/www/html/Today.txt"


2. >>> fd = os.open( path, os.O_RDWR )
3. >>> os.close( fd )
4. >>> os.lchmod( path, stat.S_IXGRP)
5. >>> os.lchmod("/tmp/Today.txt", stat.S_IWOTH)

lchmod() doesn’t return any value.

27. lchown(path,uid,gid)
Python os Module lchown() alters the owner and group id of path to the numeric uid and gid. It doens’t follow
symbolic links. Setting an id to -1 leaves it unchanged.
Sample usage:

1. >>> path = "/var/www/html/Today.txt"


2. >>> fd = os.open( path, os.O_RDWR)
3. >>> os.close( fd )
4. >>> os.lchown( path, 500, -1)
5. >>> os.lchown( path, -1, 500)

lchown() doesn’t return any value.

28. link(src,dst)
link() will create a hard link that points to an src named dst. You can do this when you want to create a copy of
an existing file.
Sample usage:

1. >>> path = "/var/www/html/Today.txt"


2. >>> fd = os.open( path, os.O_RDWR )
3. >>> os.close( fd )
4. >>> dst = "/tmp/Today.txt"
5. >>> os.link( path, dst)

lilnk() doesn’t return any value.


29. listdir(path)
listdir() will return a list holding the names of the entries in the directory at the path. This list is in an arbitrary
order, and it exclude special entries ‘.’ and ‘..’, even if they exist in the directory.
Sample usage:

1. >>> path = "/var/www/html/"


2. >>> dirs = os.listdir( path )
3. >>> for file in dirs:
4. print(file)

30. lseek(fd,pos,how)
lseek() will set the current position of the descriptor fd to the specified position pos. ‘how’ modifies it.
Sample usage:

1. >>> fd = os.open( "Today.txt", os.O_RDWR)


2. >>> os.write(fd, "This is test")
3. >>> os.fsync(fd)
4. >>> os.lseek(fd, 0, 0)
5. >>> str = os.read(fd, 100)
6. >>> print(f"Read String is: {str}")
7. >>> os.close( fd )

lseek() doesn’t return any value.


31. lstat(path)
Like fstat(), lstat() returns information about a file, but does not follow symbolic links. lstat is an alias for fstat()
on those platforms that do not support symbolic links, for instance, Windows.
It returns the following structure:

 st_dev − ID of device containing file


 st_ino − inode number
 st_mode – protection
 st_nlink − number of hard links
 st_uid − user ID of owner
 st_gid − group ID of owner
 st_rdev − device ID (if special file)
 st_size − total size, in bytes
 st_blksize − blocksize for filesystem I/O
 st_blocks − number of blocks allocated
 st_atime − time of last access
 st_mtime − time of last modification
 st_ctime − time of last status change

Sample usage:

1. >>> path = "/var/www/html/Today.txt"


2. >>> fd = os.open( path, os.O_RDWR)
3. >>> os.close( fd )
4. >>> info = os.lstat(path)
5. >>> print(f"File Info: {info}")
6. >>> print(f"UID of the file: {info.st_uid}")
7. >>> print(f"GID of the file: {info.st_gid}")

32. major(device)
major() takes a raw device number, and extracts the device major number (usually the st_dev or st_rdev field
from stat).
Sample usage:

1. >>> path = "/var/www/html/Today.txt"


2. >>> info = os.lstat(path)
3. >>> major_dnum = os.major(info.st_dev)
4. >>> minor_dnum = os.minor(info.st_dev)
5. >>> print(f"Major Device Number: {major_dnum}")
6. >>> print(f"Minor Device Number: {minor_dnum}")

major() returns the device major number.


33. makedev(major,minor)
This Python os Module takes the minor and major device numbers, and creates a raw device number.
Sample usage:

1. >>> path = "/var/www/html/Today.txt"


2. >>> info = os.lstat(path)
3. >>> major_dnum = os.major(info.st_dev)
4. >>> minor_dnum = os.minor(info.st_dev)
5. >>> print(f"Major Device Number: {major_dnum}")
6. >>> print(f"Minor Device Number: {minor_dnum}")
7. >>> dev_num = os.makedev(major_dnum, minor_dnum)
8. >>> print(f"Device Number: {dev_num}")

makedev() returns the device number.


34. makedirs(path[, mode])
makedirs() creates a directory recursively. This way, it is like mkdir(). However, it mandates that all
intermediate-level directories contain the leaf directory.
Sample usage:

1. >>> path = "/tmp/home/monthly/daily"


2. >>> os.makedirs( path, 0755 )

35. minor(device)
Python os Module minor() will take a raw device number, and extract the device’s minor (usually the st_dev or
st_rdev field from stat).
Sample usage:

1. >>> path = "/var/www/html/Today.txt"


2. >>> info = os.lstat(path)
3. >>> major_dnum = os.major(info.st_dev)
4. >>> minor_dnum = os.minor(info.st_dev)
5. >>> print(f"Major Device Number: {major_dnum}")
6. >>> print(f"Minor Device Number: {minor_dnum}")

minor() returns the device’s minor number.


36. mkdir(path[, mode])
mkdir() Python os Module creates a directory ‘path’ with the numeric mode ‘mode’. Some systems ignore
mode. But where used, it masks out the current umask value first.
Default mode=0777 (octal).
Sample usage:

1. >>> path = "/tmp/home/monthly/daily/hourly"


2. >>> os.mkdir( path, 0755 )

mkdir() doesn’t return any value.


37. mkfifo(path[, mode])
mkfifo() creates a FIFO named ‘path’ with the specified numeric mode. It masks out the current umask value
first.
Default mode=0666 (octal).
Sample usage:

1. >>> path = "/tmp/hourly"


2. >>> os.mkfifo( path, 0644 )

mkfifo() doesn’t return any value.

38. mknod(filename[, mode=0600, device])


This Python os Module will create a filesystem node named ‘filename’. This can be a file, a device-special file,
or a named pipe.
Sample usage:

1. >>> filename = '/tmp/tmpfile'


2. >>> mode = 0600|stat.S_IRUSR
3. >>> os.mknod(filename, mode)

mknod() doesn’t return any value.


39. open(file, flags[, mode])
open() will open the file ‘file’, and will set flags based on the specified flags. It possibly sets its mode according
to the specified mode. It also masks out the current umask value first.
Default mode=0777 (octal).
The flags may take one of these values, or a bitwise-OR combination of these:

 os.O_RDONLY − open for reading only


 os.O_WRONLY − open for writing only
 os.O_RDWR − open for reading and writing
 os.O_NONBLOCK − do not block on open
 os.O_APPEND − append on each write
 os.O_CREAT − create file if it does not exist
 os.O_TRUNC − truncate size to 0
 os.O_EXCL − error if create and file exists
 os.O_SHLOCK − atomically obtain a shared lock
 os.O_EXLOCK − atomically obtain an exclusive lock
 os.O_DIRECT − eliminate or reduce cache effects
 os.O_FSYNC − synchronous writes
 os.O_NOFOLLOW − do not follow symlinks

Sample usage:

1. >>> fd = os.open( "Today.txt", os.O_RDWR)


2. >>> os.write(fd, "This is test")
3. >>> os.close( fd )

open() returns the descriptor for the file we opened.

40. openpty()
Python os Module openpty() opens a pseudo-terminal pair. Then, it returns a pair of descriptors- master &
slave- for the pty & the tty, respectively.
Sample usage:

1. >>> m,s = os.openpty()


2. >>> print(m)
3. >>> print(s)
4. >>> s = os.ttyname(s)
5. >>> print(m)
6. >>> print(s)

41. pathconf(path,name)
Python os Module pathconf() returns system configuration information pertaining to a named file.
Sample usage:

1. >>> print(f"{os.pathconf_names}" )
2. >>> no = os.pathconf('a2.py', 'PC_NAME_MAX')
3. >>> print(f"Maximum length of a filename: {no}")
4. >>> no = os.pathconf('a2.py', 'PC_FILESIZEBITS')
5. >>> print(f"file size in bits: {no}")
42. pipe()
pipe() creates a pipe. Then, it returns a pair of descriptors- r & w- for reading and writing.
Sample usage:

1. >>> os.pipe()

(3, 4)
43. popen(command[, mode[, bufsize]])
This Python os Module popen() will open a pipe to, or from, the command specified .It returns an open file
object that is connected to the pipe. We can read or write to this object depending on whether the mode is ‘r’
(default) or ‘w’. The bufsize argument means the same as in the open() function.
Sample usage:

1. >>> a = 'mkdir nwdir'


2. >>> b = os.popen(a,'r',1)

44. read(fd,n)
read() Python os Module will let us read at most n bytes from the desciptor fd. It returns a string holding the
bytes we just read. And if it reaches the end of file, it returns an empty string.
Sample usage:

1. >>> fd = os.open("f1.txt",os.O_RDWR)
2. >>> ret = os.read(fd,12)
3. >>> print(ret)
4. >>> os.close(fd)

45. readlink(path)
Python os Module readlink() will return a string denoting the path to which the symbolic link points. It may
return a relative or an absolute pathname.
Sample usage:

1. >>> src = '/usr/bin/python'


2. >>> dst = '/tmp/python'
3. >>> os.symlink(src, dst)
4. >>> path = os.readlink( dst )
5. >>> print(path)

46. remove(path)
remove() removes the specified file path. If that path is a directory, it raises an OSError.
Sample usage:

1. >>> print(f"The dir is: {os.listdir(os.getcwd())}")


2. >>> os.remove("aa.txt")
3. >>> print(f"The dir after removal of path: {os.listdir(os.getcwd())}")

remove() doesn’t return any value.

47. removedirs(path)
This Python os Module will remove directories recursively. And if we successfully remove the leaf directory, it
attempts to successively remove every parent directory displayed in that path.
Sample usage:
1. >>> print(f"The dir is: {os.listdir(os.getcwd())}")
2. >>> os.removedirs("/tutorialsdir")
3. >>> print(f"The dir after removal is: {os.listdir(os.getcwd())}")

removedirs() doesn’t return any value.


48. rename(src,dst)
rename() renames a file or directory. If the destination is a file or a directory that already exists, it raises an
OSError.
Sample usage:

1. >>> print(f"The dir is: {os.listdir(os.getcwd())}”)


2. >>> os.rename("tutorialsdir","tutorialsdirectory")
3. >>> print(“Successfully renamed”)
4. >>> print(f"The dir is: {os.listdir(os.getcwd())}")

rename() doesn’t return any value.


49. renames(old,new)
renames() Python os Module renames directories and files recursively. It is like os.rename(), but it also moves a
file to a directory, or a whole tree of directories, that do not already exist.
Sample usage:

1. >>> print("Current directory is: { os.getcwd()}")


2. >>> print("The dir is: { os.listdir(os.getcwd())}")
3. >>> os.renames("aa1.txt","newdir/aanew.txt")
4. >>> print("Successfully renamed”)
5. >>> print(f"The dir is: {os.listdir(os.getcwd())}")

renames() does not return any value.

50. rmdir(path)
Python os Module rmdir() removes the directory path specified. If the directory isn’t empty, however, it raises
an OSError.
Sample usage:

1. >>> print(f"the dir is: { os.listdir(os.getcwd())}")


2. >>> os.rmdir("mydir")
3. >>> print(f"the dir is: { os.listdir(os.getcwd())}"

rmdir() doesn’t return any value.


51. stat(path)
This Python os Module performs a stat system call on the specified path.
These are the members of the stat structure:

 st_mode − protection bits


 st_ino − inode number
 st_dev − device
 st_nlink − number of hard links
 st_uid − user id of owner
 st_gid − group id of owner
 st_size − size of file, in bytes
 st_atime − time of most recent access
 st_mtime − time of most recent content modification
 st_ctime − time of most recent metadata change.

Sample usage:

1. >>> statinfo = os.stat('a2.py')


2. >>> print(statinfo)

52. stat_float_times([newvalue])
stat_float_times() Python os Module decides whether stat_result denotes time stamps as float objects.
Sample usage:

1. >>> import os, sys


2. >>> statinfo = os.stat('a2.py')
3. >>> print(statinfo)
4. >>> statinfo = os.stat_float_times()
5. >>> print(statinfo)

53. statvfs(path)
Python os Module statvfs() executes a statvfs system call on the specified path.
The structure has the following members:

 f_bsize − preferred file system block size


 f_frsize − fundamental file system block size
 f_blocks − total number of blocks in the filesystem
 f_bfree − total number of free blocks
 f_bavail − free blocks available to non-super user
 f_files − total number of file nodes
 f_ffree − total number of free file nodes
 f_favail − free nodes available to non-super user
 f_flag − system dependent
 f_namemax − maximum file name length

Sample usage:

1. >>> stinfo = os.statvfs('a1.py')


2. >>> print(stinfo)

54. symlink(src,dst)
symlink() composes a symbolic link dst that points to the source.
Sample usage:

1. >>>src = '/usr/bin/python'
2. >>> dst = '/tmp/python'
3. >>> os.symlink(src, dst)

symlink() returns no value.


55. tcgetpgrp(fd)
This Python os Module returns the process group linked to the terminal specified by fd, which is an open file
descriptor, and is returned by os.open().
Sample usage:

1. >>> print(f"Current working dir : { os.getcwd()}")


2. >>> fd = os.open("/dev/tty",os.O_RDONLY)
3. >>> f = os.tcgetpgrp(fd)
4. >>> print(f"the process group associated is: {f}")
5. >>> os.close(fd)

tcgetpgrp() returns the process group.

56. tcsetpgrp(fd, pg)


Python os Module tcsetpgrp() sets the process group linked to the terminal specified by fd, which is an open file
descriptor, and is returned by os.open(), to pg.
Sample usage:

1. >>> print(f"Current working dir : { os.getcwd()}")


2. >>> fd = os.open("/dev/tty",os.O_RDONLY)
3. >>> f = os.tcgetpgrp(fd)
4. >>> print(f"the process group associated is: {f}")
5. >>> os.tcsetpgrp(fd,2672)
6. >>> print("done")
7. >>> os.close(fd)

tcsetpgrp() returns no value.


57. tempnam([dir[, prefix]])
tempnam() Python os Module returns a unique path name reasonable enough to create a temporary file.
Sample usage:

1. >>> tmpfn = os.tempnam('/tmp/tutorialsdir,'tuts1')

tempnam() returns a unique path.

58. tmpfile()
tmpfile() will return a new temporary file object, opening it in update mode (w+b). This file has zero directory
entries linked to it, and will automatically delete when no descriptors are available.
Sample usage:

1. >>> tmpfile = os.tmpfile()


2. >>> tmpfile.write('Temporary newfile is here.....')
3. >>> tmpfile.seek(0)
4. >>> print(tmpfile.read())
5. >>> tmpfile.close()

59. tmpnam()
tmpnam() will return a unique path name reasonable enough to create a temporary file.
Sample usage:

1. >>> tmpfn = os.tmpnam()


2. >>> print(f"This is the unique path: {tmpfn}")
60. ttyname(fd)
ttyname() Python os Module will return a string that denotes the terminal device linked to the descriptor fd. If it
isn’t linked to a terminal device, it raises an exception.
Sample usage:

1. >>> print(f"Current working dir : { os.getcwd()}")


2. >>> fd = os.open("/dev/tty",os.O_RDONLY)
3. >>> p = os.ttyname(fd)
4. >>> print(f"the terminal device associated is: {p}")
5. >>> os.close(fd)

ttyname() returns a string that denotes the terminal device.

61. unlink(path)
This Python os Module will remove specified file path. If it is a directory, it raises an OSError.
Sample usage:

1. >>> print(f"The dir is: { os.listdir(os.getcwd())}")


2. >>> os.unlink("aa.txt")
3. >>> print(f"The dir after removal of path : { os.listdir(os.getcwd())}")

unlink() doesn’t return any value.


62. utime(path,times)
Python os Module utime() sets the access and modified times of the file at the specified path.
Sample usage:

1. >>> stinfo = os.stat('a2.py')


2. >>> print(stinfo)
3. >>> print(f"access time of a2.py: { stinfo.st_atime }")
4. >>> print(f"modified time of a2.py: { stinfo.st_mtime }")
5. >>> os.utime("a2.py",(1330712280, 1330712292))

utime() returns no value.


63. walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
walk() creates file names in a directory tree. It does so by walking the tree either bottom-up or top-down.
It has the following parameters:

1. top − Each directory rooted at directory


2. topdown − If topdown is True, or not specified, it scans directories top-down.
3. onerror − This may show an error to continue with the walk, or may raise an exception to abort the
walk.
4. followlinks − This will visit directories that symlinks points to, that is, if set to true.

Sample usage:

1. >>> for root, dirs, files in os.walk(".", topdown=False):

for name in files:


print(os.path.join(root, name))
for name in dirs:
print(os.path.join(root, name))

64. write(fd,str)
This Python os Module will write the specified string to descriptor fd. It returns the number of bytes that it
actually wrote.
Sample usage:

1. >>> fd = os.open("f1.txt",os.O_RDWR|os.CREAT)
2. >>> ret = os.write(fd,"This is test")
3. >>> print(f"the number of bytes written: {ret}")
4. >>> print("written successfully")
5. >>> os.close(fd)

So, this was all about Python os Module. Hope you like our explanation.

66. Conclusion
Hence, we cover all the Python os module. This will allow you to work your way around the directories without
any problem. If you have any query regarding Python os module, feel free to share with us. Surely we will get
back to you!

Python pprint Module – Python Data Pretty Printer


by DataFlair Team · March 1, 2019

Earlier we have discussed Python OS Module. Today, we will see Python pprint i.e. Python Pretty Print. Also,
we will discuss Python pprint format and its example. This article includes recursive data structures and own
classes in Pretty print in Python. At last, we will see Python pprintpp Module.

So, let’s start the Python pprint tutorial.


Python pprint Module – Python Data Pretty Printer

1. What is Python Pretty Print?


The pprint module lets us pretty-print arbitrary data structures in Python to make them prettier, well-
formatted, and more readable. What it gives us is in a form we can use as input to the interpreter. This is just
the kind of thing for aesthetes and it keeps the output on a single line wherever possible. And when on multiple
lines, it indents it. Let’s import it:

1. >>> from pprint import pprint

Basically, this module has the following class:

class pprint.PrettyPrinter(indent=1, width=80, depth=None, stream=None, *, compact=False)

This constructs a PrettyPrinter instance for us. Let’s talk about its parameters:

 indent gives us the amount of indentation for each recursive level


 width gives us the desired output width
 depth gives us the number of levels to print
 stream lets us set an output stream
 compact lets us fit as many items within the width as we can on each line of output

Now, let’s try an example without pprint. Let’s take a list to work with:

1. >>> data=[(1,{'a':'A','b':'B','c':'C','d':'D'}),(2,{'e':'E','f':'F','g':'G','h':'H','i':'I','j':'J','k':'K','l':'L'}),(3,['m','n']),(4,
['o',' p','q','r','s','t','u','v','w']),(5,['x','y','z']),]
2. >>> print(data)
[(1, {‘a’: ‘A’, ‘b’: ‘B’, ‘c’: ‘C’, ‘d’: ‘D’}), (2, {‘e’: ‘E’, ‘f’: ‘F’, ‘g’: ‘G’, ‘h’: ‘H’, ‘i’: ‘I’, ‘j’: ‘J’, ‘k’: ‘K’, ‘l’:
‘L’}), (3, [‘m’, ‘n’]), (4, [‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’]), (5, [‘x’, ‘y’, ‘z’])]

2. Python pprint Example


So, let’s try printing this with pprint instead.

1. >>> pprint(data)

[(1, {‘a’: ‘A’, ‘b’: ‘B’, ‘c’: ‘C’, ‘d’: ‘D’}),

(2,

{‘e’: ‘E’,

‘f’: ‘F’,

‘g’: ‘G’,

‘h’: ‘H’,

‘i’: ‘I’,

‘j’: ‘J’,

‘k’: ‘K’,

‘l’: ‘L’}),

(3, [‘m’, ‘n’]),

(4, [‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’]),

(5, [‘x’, ‘y’, ‘z’])]

So, what does Python pprint do? It formats an object and writes it to the data stream we pass to it as an
argument. By default, this is sys.stdout.

Learn about Python sys Module.

3. Python pprint Formatting


We can format a data structure without having to write it to a stream. To do this, we use pformat() to build a
string representation, and possible use cases include logging.

1. >>> import logging


2. >>> from pprint import pformat
3. >>> logging.basicConfig(
4. level=logging.DEBUG,
5. format='%(levelname)-8s %(message)s',)
6. >>> logging.debug('Logging pformatted data')

DEBUG Logging pformatted data

1. >>> formatted=pformat(data)

So, we can print or log this string independently:

1. >>> for line in formatted.splitlines():


2. logging.debug(line.rstrip())

DEBUG [(1, {‘a’: ‘A’, ‘b’: ‘B’, ‘c’: ‘C’, ‘d’: ‘D’}),

DEBUG (2,

DEBUG {‘e’: ‘E’,

DEBUG ‘f’: ‘F’,

DEBUG ‘g’: ‘G’,

DEBUG ‘h’: ‘H’,

DEBUG ‘i’: ‘I’,

DEBUG ‘j’: ‘J’,

DEBUG ‘k’: ‘K’,

DEBUG ‘l’: ‘L’}),

DEBUG (3, [‘m’, ‘n’]),

DEBUG (4, [‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’]),

DEBUG (5, [‘x’, ‘y’, ‘z’])]

4. Python Pretty-Printing Our Own Classes


Last, we talked about the repr() built-in function in Python. In that, we observed the repr () method.
Today, let’s see how we can make pprint work with our own classes by making use of the repr () method.

1. >>> class Color:


2. def init (self,name,hex_value):
3. self.name=name
4. self.hex_value=hex_value
5. def repr (self):
6. return(
7. 'I am '+self.name+' and you can find me at '+self.hex_value)
8. >>> colors=[Color('salmon','#FA8072'),Color('olive','#808000'),Color('purple','#800080')]
9. >>> print(colors)

[I am salmon and you can find me at #FA8072, I am olive and you can find me at #808000, I am purple
and you can find me at #800080]

Now see what Python pprint does to this:

1. >>> pprint(colors)

[I am salmon and you can find me at #FA8072,

I am olive and you can find me at #808000,

I am purple and you can find me at #800080]

5. Python Pprint with Recursive Data Structures


Let’s create a list and append it to its end. This makes for a recursive list.

1. >>> from pprint import pprint


2. >>> mylist=[1,2,'c','d']
3. >>> mylist.append(mylist)
4. >>> id(mylist)

45553504

1. >>> pprint(mylist)

[1, 2, ‘c’, ‘d’, <Recursion on list with id=45553504>] #The recursive reference

1. >>> mylist #Pay attention

[1, 2, ‘c’, ‘d’, […]]

 Controlling Depth-

To control how far the Python pretty printer recurses down a nested structure, we can use the depth argument:

1. >>> pprint(data,depth=1)

[(…), (…), (…), (…), (…)]

1. >>> pprint(data,depth=2)

[(1, {…}), (2, {…}), (3, […]), (4, […]), (5, […])]
1. >>> pprint(data,depth=3)

[(1, {‘a’: ‘A’, ‘b’: ‘B’, ‘c’: ‘C’, ‘d’: ‘D’}),

(2,

{‘e’: ‘E’,

‘f’: ‘F’,

‘g’: ‘G’,

‘h’: ‘H’,

‘i’: ‘I’,

‘j’: ‘J’,

‘k’: ‘K’,

‘l’: ‘L’}),

(3, [‘m’, ‘n’]),

(4, [‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’]),

(5, [‘x’, ‘y’, ‘z’])]

Here, the ellipses denote the levels it excludes from the output.

6. Deciding Output Width


We can decide the width for the output- this is the number of columns. The default is 80, but we can change that
with width.

1. >>> mylist=[1,2,'c','d']
2. >>> pprint(mylist)

[1, 2, ‘c’, ‘d’]

1. >>> pprint(mylist,width=-1)

[1,

2,

‘c’,

‘d’]
So, you can also pretty-print the output of the listdir() method or your system’s environment variables with
pprint(dict(os.environ),width=1).

1. >>> pprint(os.listdir())

[‘DLLs’,

‘Doc’,

‘etc’,

‘include’,

‘Lib’,

‘libs’,

‘LICENSE.txt’,

‘man’,

‘NEWS.txt’,

‘opencv_ffmpeg343.dll’,

‘out.log’,

‘python.exe’,

‘python3.dll’,

‘python37.dll’,

‘pythonw.exe’,

‘Scripts’,

‘share’,

‘tcl’,

‘Tools’,

‘vcruntime140.dll’]

You can use the compact flag to make this more compact-

1. >>> pprint(os.listdir(),compact=True)

[‘DLLs’, ‘Doc’, ‘etc’, ‘include’, ‘Lib’, ‘libs’, ‘LICENSE.txt’, ‘man’,


‘NEWS.txt’, ‘opencv_ffmpeg343.dll’, ‘out.log’, ‘python.exe’, ‘python3.dll’,

‘python37.dll’, ‘pythonw.exe’, ‘Scripts’, ‘share’, ‘tcl’, ‘Tools’,

‘vcruntime140.dll’]

7. The pprintpp Module


Before we say goodbye, why don’t we talk about pprintpp? This is another module for pretty printing and we
like to call it pprint++. It is available in the PyPI and you can install it as:

1. Python pip install pprintpp

Let’s import this.

1. >>> import pprintpp

Now, let’s try printing something with this.

1. >>> pprintpp.pprint(data)

Python pprintpp module

 pp-ez

You can also install the pp-ez package to do this:

1. >>> pp.pprint(data)
This gives us the same output. So how is pprint++ different from pprint? One difference is what you can see in
the outputs. Well, the goal of pprint++ is to emit a readable representation of the input that is also largely PEP-8
compliant.

So, this was all in Python pprint. Hope you liked our explanation of Python Pretty Print.

8. Summary
Hence, we discussed the Python pprint module and its method with its attributes. Some among these were
width, depth, and compact. Moreover, we looked at the example of Python pretty print. Also, we saw formatting
in Pretty Print. Happy pretty-printing! This is the time to explore the most asked Python interview questions.

Create Python Virtual Environment – Install Python Packages


by DataFlair Team · September 27, 2018

1. Python Virtual Environment


In this blog, we will discuss what a Python virtual environment is? Moreover, we will study how to create
Virtual Environment in Python Programming Language and how to install Python packages using pip. Along
with this, we talked about installing Python. If you still haven’t installed Python, do it right away.

So, let’s start creating Python Virtual Environment.

Python Virtual Environment and Install Python Packages


2. What is Python Virtual Environment?
Developing a Python application, you may want to use modules that don’t ship with the standard library. Or
sometimes, you need a specific version of a library for a bug to be fixed, or for some other reason.

Does this mean that installing Python once isn’t enough for every application you craft? Maybe application X
needs version 1.0, but application Y needs version 2.0. This leaves one of them unable to run.

To work with this, we create a Python virtual environment. In essence, it is a self-contained directory tree
containing a Python installation for a particular version of Python. Apart from that, it also has a list of additional
packages. This way, application X can have its virtual environment with version 1.0, and B can have its own
with version 2.0.

Lets start with how to create Python Virtual Environment.

3. How to Create a Virtual Environment


in Python?
To create a Python virtual environment and manage it, we use the module venv. Normally, it will install the
latest version of Python for you, but you can choose that. But before we begin, let’s find out which version of
Python we are using.

To do this, type the following in your Command Prompt (for Windows; type ‘cmd’ in search):
python –version

This is what it will look like:

Microsoft Windows [Version 10.0.16299.248]

(c) 2017 Microsoft Corporation. All rights reserved.

C:\Users\lifei>python –version
Python 3.6.0

C:\Users\lifei>
Now, let’s check if we have pip installed.

C:\Users\lifei>pip –version
pip 9.0.1 from c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-packages (python 3.6)

We do. This is because we installed Python from python.org. In case you do not have pip installed, you may
need to install it manually.

Now, let’s begin. In your command prompt, move to the directory you want to work in:

C:\Users\lifei>cd Desktop
Now, type in the following:

C:\Users\lifei\Desktop>python -m venv workwithenv

You will see the following directory on your Desktop (or whichever directory you chose to work with):

Python Virtual Environment and Install Python Packages

Inside this, you can see the following contents:

Python Virtual Environment and Install Python Packages

Python Virtual Environment and Install Python Packages

Virtual Environment and Install Python Packages – sitepackages


Python Virtual Environment and Install Python Packages – scripts

While the directory Include is empty, the other two aren’t:

As you can see, the command created the directory ‘workwithenv’ because it didn’t already exist. It also created
subdirectories containing a copy of the Python interpreter, the standard library, and various supporting files.

Now, to activate the Python Virtual Environment, we will run the batch file activate.bat in the directory Scripts:

C:\Users\lifei\Desktop>workwithenv\Scripts\activate.bat

We get the following output:

(workwithenv) C:\Users\lifei\Desktop>

This script is for the bash shell. If you have any doubt in Python Virtual environment, Please comment. Before
starting with Next topic you can read Python Packages Comprehensive Guide here.

4. Managing Python Packages with pip


Like we said earlier, pip is a program that will let you install, upgrade, and remove Python packages. Using pip,
you can install Python packages from the Package Index (PyPI). Or, you can use pip’s search feature this way:
C:\Users\lifei\Desktop\workwithenv>pip search astronomy
acalib (0.1.3) – Advanced Computing for Astronomy Library
vaex-astro (0.1.5) – Astronomy related transformations and FITS file support
astro-scripts (0.4.0) – Small scripts for astronomy
astrobase (0.3.8) – Python modules and scripts useful for variable star work in astronomy.
astrocats (0.3.32) – Package for downloading, analyzing, and constructing open astronomy catalogs.
astrodbkit (0.6.6) – Astronomy database management using SQL and Python
astroML (0.3) – Tools for machine learning and data mining in Astronomy
astromodels (0.4.1) – Astromodels contains models to be used in likelihood or Bayesian analysis in
astronomy
astroobs (1.4.5) – Provides astronomy ephemeris to plan telescope observations
astropy (3.0) – Community-developed python astronomy tools
astropyp (0.0.dev133) – Astronomy Pypeline Framework and FITS Viewer
astrotoyz (0.1.4) – Astronomy tools built on the Toyz framework
Barak (0.3.2) – A set of astronomy-related routines for generating Voigt profiles from atomic data,
reading and writing data, working with SEDs, passbands and dust extinction laws.
cadcdata (1.2.1) – Client for accessing data at the Canadian Astronomy Data Centre
python-casacore (2.2.1) – A wrapper around CASACORE, the radio astronomy library
cygrid (0.9.8) – Cygrid is a cython-powered convolution-based gridding module for astronomy
DDFacet (0.3.2) – Facet-based radio astronomy continuum imager
f311 (18.1.31.1) – Astronomy-related API, command-line tools, and windowed applications
gammapy (0.7) – A Python package for gamma-ray astronomy
gary (0.1a) – Galactic astronomy and gravitational dynamics.
gastropy (0.0dev) – (g)astronomy
hips (0.2) – Python astronomy package for HiPS
mclearn (0.1.6) – Active learning algorithms with application in astronomy.
novas (3.1.1.4) – The United States Naval Observatory NOVAS astronomy library
palpy (1.8.1) – PAL — A Positional Astronomy Library
PyAstronomy (0.12.0) – A collection of astronomy related tools for Python.
pyzpace (0.2.dev1) – Zach Pace’s astronomy-related python tools
sinistra (0.3.3) – A collection of astronomy related tools.
skyfield (1.1) – Elegant astronomy for Python
SWHT (0.1.2) – Spherical Wave Harmonic Transform for radio astronomy visibility data

C:\Users\lifei\Desktop\workwithenv>

This listed out a list of packages that work with astronomy. Now, we want to search for packages working with
numbers. (We won’t include the output since it’s too long to include here) But I have a feeling we want to work
with the package ‘numpy’ here. Let’s install python packages. I also recommend you to read Python Modules
vs Packages for better understanding.

a. Installing Python Packages


C:\Users\lifei\Desktop\workwithenv>pip install numpy

Collecting numpy

Using cached numpy-1.14.1-cp36-none-win32.whl

Installing collected packages: numpy


Successfully installed numpy-1.14.1

C:\Users\lifei\Desktop\workwithenv>

This is what it looks like in the command prompt:

Python Virtual Environment – Install Python Packages

Now, we look into C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\Lib\site-packages, and we find


this:

Python Virtual Environment – Install Python Packages

Actually, pip has a number of subcommands like search, install, uninstall, and freeze.

You can also install a specific version of a package by following the package name by ==, and then by the
version number:

pip install numpy==1.14.1

In fact, to check what version of numpy you are using, you can type the following in the interpreter:

1. >>> import numpy


2. >>> numpy.version.version
‘1.14.1’

Or, you can do:

1. >>> numpy. version

‘1.14.1’

Running the command to install numpy again will just be ignored by the interpreter.

C:\Users\lifei\Desktop\workwithenv>pip install numpy

Requirement already satisfied: numpy in

c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-packages

b. Checking for Upgrades


However, you can check for upgrades:

C:\Users\lifei\Desktop\workwithenv>pip install –upgrade numpy

Requirement already up-to-date: numpy in

c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-packages

c. Uninstalling a Python Package


To uninstall a package, we do this:

C:\Users\lifei\Desktop\workwithenv>pip uninstall certifi

Uninstalling certifi-2018.1.18:

c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-packages\certifi-

2018.1.18.dist-info\description.rst

c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-packages\certifi-

2018.1.18.dist-info\installer c:\users\lifei\appdata\local\programs\python\python36-

32\lib\site-packages\certifi- 2018.1.18.dist-info\license.txt

c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-packages\certifi-

2018.1.18.dist-info\metadata
c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-packages\certifi-

2018.1.18.dist-info\metadata.json

c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-packages\certifi-

2018.1.18.dist-info\record

c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-packages\certifi-

2018.1.18.dist-info\top_level.txt

c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-packages\certifi-

2018.1.18.dist-info\wheel

c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-

packages\certifi\ init .py

c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-

packages\certifi\ main__.py

c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-

packages\certifi\ pycache \ init .cpython-36.pyc

c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-

packages\certifi\ pycache \ main .cpython-36.pyc

c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-

packages\certifi\ pycache \core.cpython-36.pyc

c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-

packages\certifi\cacert.pem

c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-packages\certifi\core.py

Proceed (y/n)? y

Successfully uninstalled certifi-2018.1.18

C:\Users\lifei\Desktop\workwithenv>
d. Learning About a Python Package
To find out about a particular package, we use the subcommand ‘show’:

C:\Users\lifei\Desktop\workwithenv>pip show numpy

Name: numpy

Version: 1.14.1

Summary: NumPy: array processing for numbers, strings, records, and objects.

Home-page: http://www.numpy.org

Author: NumPy Developers

Author-email: [email protected]

License: BSD

Location: c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-packages

Requires:

e. List the Packages Installed in Python


Now, to list all packages that are installed, we use ‘list’:

C:\Users\lifei\Desktop\workwithenv>pip list

DEPRECATION: The default format will switch to columns in the future. You can use –format=

(legacy|columns) (or define a format=(legacy|columns) in your pip.conf under the [list] section)

to disable this warning.

numpy (1.14.1)

pip (9.0.1)

setuptools (28.8.0)

virtualenv (15.1.0)

This listed the packages alongside the versions installed.


f. Freeze
The freeze subcommand with pip will return a list of packages installed, but in the format that

pip install expects:

C:\Users\lifei\Desktop\workwithenv>pip freeze

numpy==1.14.1

virtualenv==15.1.0

So, this is all about Python Virtual Environment and Install Python Packages. Hope you like our explanation.

5. Conclusion
Hence, in this lesson on Python virtual environment and Python Packages, we learned about how to set up a
virtual environment so all your applications will run without a dispute. Then, we learned how to use pip to
install a package. We also saw subcommands like show, list, freeze, and so. Furthermore, if you have any
query, feel free to share with us!

Python Modules vs Packages | Differences Between Python


Modules and Packages
by DataFlair Team · September 26, 2018

1. Python Modules vs Packages


In our article on Python Modules vs Packages, we discussed what they are, and saw how to create our own. We
also saw where they are located in our file system. But throughout the article, we saw a lot of similarities to
modules. Hence, we dedicate this article to Differences Between Python Modules and Packages.

Python Modules vs Packages


2. What is Python Modules?
A module is a Python file containing Python statements and definitions. For example, a file evenodd.py is a
module, and we call it ‘evenodd’. We put similar code together in one module. This helps us modularize our
code, and make it much easier to deal with. And not only that, a module grants us reusability. With a module,
we don’t need to write the same code again for a new project that we take up.

In our previous article, we created a module evenodd in package two. This is what evenodd.py holds:

1. def check():
2. a=int(input('Enter a number'))
3. if a%2==0: print("Even")
4. else: print("Odd")

a. How to Import a Python Module?


So, as you can see, a module simply contains Python code. Consequently, we can import it, like a package.

1. >>> import one.two.evenodd


2. >>>

To call function check(), we do the following:

1. >>> from one.two.evenodd import check


2. >>> check()

Enter a number7
Odd

1. >>>

Another example would be the constants ‘pi’ and ‘e’ from the ‘math’ module.

1. >>> import math


2. >>> from math import pi
3. >>> math.pi

3.141592653589793

1. >>> math.e

2.718281828459045
We can also import using an alias or using the from..import statement, like we do with packages. To import
everything from a module, we do the following:

1. >>> from math import *


2. >>> e
2.718281828459045

1. >>> pi

3.141592653589793

1. >>>

Let’s update evenodd.py to have two functions- check and evenodd.

1. def check():
2. a=int(input('Enter a number'))
3. if a%2==0: print("Even")
4. else: print("Odd")
5. def add(a,b):
6. return a+b

Now, if we want to import all functions from module evenodd, we can just use the wildcard *:

1. >>> from one.two.evenodd import *


2. >>> check()

Enter a number0
Even

1. >>> add(3,4)

b. Search Path
When we import a module, the interpreter first looks in the current directory. Then, it looks into
PYTHONPATH, an environment variable with a list of directories. Finally, it looks into the installation-
dependent default directory.

1. >>> import sys


2. >>> for i in sys.path:
3. print(i)

C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\Lib\idlelib

C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\python36.zip

C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\DLLs

C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\lib

C:\Users\lifei\AppData\Local\Programs\Python\Python36-32

C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\lib\site-packages
c. Reloading a Python Module
A module is imported only once. This is for efficiency purposes. Let’s add this code to evenodd.py:

1. print("Loading evenodd")
2. num=7

Now, let’s restart the shell, and import evenodd thrice.

1. >>> import one.two.evenodd

Loading evenodd

1. >>> import one.two.evenodd


2. >>> import one.two.evenodd

See? It imported it only once. Because of this, Python gives us a function to let us reload the module when we
want to. This is in the module ‘imp’.

1. >>> import imp


2. >>> imp.reload(one.two.evenodd)

Loading evenodd
<module ‘one.two.evenodd’ from ‘C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\site-
packages\\one\\two\\evenodd.py’>

d. dir()
Finally, dir() will let us check the components of a module.

1. >>> dir(one.two.evenodd)

[‘ builtins ’, ‘ cached ’, ‘ doc ’, ‘ file ’, ‘ loader ’, ‘ name ’, ‘ package ’, ‘ spec ’, ‘add’,


‘check’ , ‘num’] We saw this function when we talked about the Built-in Functions in Python.

3. What is Python Packages?


A package, in essence, is like a directory holding subpackages and modules. While we can create our own
packages, we can also use one from the Python Package Index (PyPI) to use for our projects.

To import a package, we type the following:

import Game.Sound.load

We can also import it giving it an alias:

import Game.Sound.load as load game


You can’t import a function using the dot operator(.) For that, you must type this:

from Game.Sound.load import volume_up

A package must have the file init .py, even if you leave it empty.

But when we import a package, only its immediate modules are imported, not the sub-packages. If you try to
access those, it will raise an AttributeError.

To get a deeper insight into packages, check Python Packages.

4. Differences Between Python Modules and


Packages
So, now that we’ve revised both modules and packages, let’s see how they differ:

1. A module is a file containing Python code. A package, however, is like a directory that holds sub-
packages and modules.
2. A package must hold the file init .py. This does not apply to modules.
3. To import everything from a module, we use the wildcard *. But this does not work with packages.

This was all about the article on Python Modules vs Packages

5. Conclusion
Now that we know what subtle differences exist between a module and a package, let’s take up a challenge and
take up a project of our own. Let’s do this to test our package skills? Okay.

Furthermore, if you have any query, feel free to approach us!

Python Set and Booleans with Syntax


and Examples
by DataFlair Team · May 27, 2019

1. Python Set and Python Booleans


So far, we have learned about various data types in Python. We dealt with strings, numbers, lists, tuples, and
dictionaries. We’ve also learned that we don’t need to declare the type of data while defining it. Today, we will
talk about Python set examples and Python Booleans. After that, we will move onto python functions in further
lessons.
Python Sets and Booleans

2. Sets in Python
First, we focus on Python sets. A set in Python holds a sequence of values. It is sequenced but does not support
indexing. We will understand that as we get deeper into the article with the Python set Examples.

a. Creating a Python Set


To declare a set, you need to type a sequence of items separated by commas, inside curly braces. After that,
assign it to a Python variable.

1. >>> a={1,3,2}

As you can see, we wrote it in the order 1, 3, 2. In point b, we will access this set and see what we get back.

A set may contain values of different types.

1. >>> c={1,2.0,'three'}

1. Duplicate Elements

A set also cannot contain duplicate elements. Let’s try adding duplicate elements to another set, and then access
it in point b.

1. >>> b={3,2,1,2}
2. Mutability

A set is mutable, but may not contain mutable items like a list, set, or even a dictionary.

1. >>> d={[1,2,3],4}

Traceback (most recent call last):

File “<pyshell#9>”, line 1, in <module>

d={[1,2,3],4}

TypeError: unhashable type: ‘list’

As we discussed, there is no such thing as a nested Python set.

1. >>> d={{1,3,2},4}

Traceback (most recent call last):

File “<pyshell#10>”, line 1, in <module>

d={{1,3,2},4}

TypeError: unhashable type: ‘set’

3. The Python set() function

You can also create a set with the set() function.

1. >>> d=set()
2. >>> type(d)

<class ‘set’>

This creates an empty set object. Remember that if you declare an empty set as the following code, it is an
empty dictionary, not an empty set. We confirm this using the type() function.

1. >>> d={}
2. >>> type(d)

<class ‘dict’>

The set() function may also take one argument, however. It should be an iterable, like a list.

1. >>> d=set([1,3,2])
b. Accessing a Set in Python
Since sets in Python do not support indexing, it is only possible to access the entire set at once. Let’s try
accessing the sets from point a.

1. >>> a

{1, 2, 3}

Did you see how it reordered the elements into an ascending order? Now let’s try accessing the set c.

1. >>> c

{1, 2.0, ‘three’}

Finally, let’s access set b.

1. >>> b

{1, 2, 3}

As you can see, we had two 2s when we declared the set, but now we have only one, and it automatically
reordered the set.

Also, since sets do not support indexing, they cannot be sliced. Let’s try slicing one.

1. >>> b[1:]

Traceback (most recent call last):

File “<pyshell#26>”, line 1, in <module>

b[1:]

TypeError: ‘set’ object is not subscriptable

As you can see in the error, a set object is not subscriptable.

c. Deleting a Set
Again, because a set isn’t indexed, you can’t delete an element using its index. So for this, you must use one the
following methods. A method must be called on a set, and it may alter the set. For the following examples, let’s
take a set called numbers.

1. >>> numbers={3,2,1,4,6,5}
2. >>> numbers

{1, 2, 3, 4, 5, 6}
1. discard()

This method takes the item to delete as an argument.

1. >>> numbers.discard(3)
2. >>> numbers

{1, 2, 4, 5, 6}

As you can see in the resulting set, the item 3 has been removed.

2. remove()

Like the discard() method, remove() deletes an item from the set.

1. >>> numbers.remove(5)
2. >>> numbers

{1, 2, 4, 6}

 discard() vs remove()-

These two methods may appear the same to you, but there’s actually a difference. If you try deleting an item
that doesn’t exist in the set, discard() ignores it, but remove() raises a KeyError.

1. >>> numbers.discard(7)
2. >>> numbers

{1, 2, 4, 6}

1. >>> numbers.remove(7)

Traceback (most recent call last):

File “<pyshell#37>”, line 1, in <module>

numbers.remove(7)

KeyError: 7

3. pop()

Like on a dictionary, you can call the pop() method on a set. However, here, it does not take an argument.
Because a set doesn’t support indexing, there is absolutely no way to pass an index to the pop method. Hence, it
pops out an arbitrary item. Furthermore, it prints out the item that was popped.

1. >>> numbers.pop()

Let’s try popping anot/her element.


1. >>> numbers.pop()

Let’s try it on another set as well.

1. >>> {2,1,3}.pop()

4. clear()

Like the pop method(), the clear() method for a dictionary can be applied to a Python set as well. It empties the
set in Python.

1. >>> numbers.clear()
2. >>> numbers

set()

As you can see, it denoted an empty set as set(), not as {}.

d. Updating a Set
As we discussed, a Python set is mutable. But as we have seen earlier, we can’t use indices to reassign it.

1. >>> numbers={3,1,2,4,6,5}
2. >>> numbers[3]

Traceback (most recent call last):

File “<pyshell#56>”, line 1, in <module>

numbers[3]

TypeError: ‘set’ object does not support indexing

So, we use two methods for this purpose- add() and update(). We have seen the update() method on tuples, lists,
and strings.

1. add()

It takes as argument the item to be added to the set.

1. >>> numbers.add(3.5)
2. >>> numbers

{1, 2, 3, 4, 5, 6, 3.5}

If you add an existing item in the set, the set remains unaffected.
1. >>> numbers.add(4)
2. >>> numbers

{1, 2, 3, 4, 5, 6, 3.5}

2. update()

This method can add multiple items to the set at once, which it takes as arguments.

1. >>> numbers.update([7,8],{1,2,9})
2. >>> numbers

{1, 2, 3, 4, 5, 6, 3.5, 7, 8, 9}

As is visible, we could provide a list and a set as arguments to this. This is because this is different than creating
a set.

e. Functions on Sets
A function is something that you can apply to a Python set, and it performs operations on it and returns a value.
Let’s talk about some of the functions that a set supports.

We’ll take a new set for exemplary purposes.

1. >>> days={'Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'}

1. len()

The len() function returns the length of a set. This is the number of elements in it.

1. >>> len(days)

2. max()

This function returns the item from the set with the highest value.

1. >>> max({3,1,2})

We can make such a comparison on strings as well.

1. >>> max(days)

‘Wednesday’

The Python function returned ‘Wednesday’ because W has the highest ASCII value among M, T, W, F, and S.
But we cannot compare values of different types.

1. >>> max({1,2,'three','Three'})

Traceback (most recent call last):

File “<pyshell#69>”, line 1, in <module>

max({1,2,’three’,’Three’})

TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’

3. min()

Like the max() function, the min() function returns the item in the Python set with the lowest value.

1. >>> min(days)

‘Friday’

This is because F has the lowest ASCII value among M, T, W, F, and S.

4. sum()

The sum() functionin Python set returns the arithmetic sum of all the items in a set.

1. >>> sum({1,2,3})

However, you can’t apply it to a set that contains strings.

1. >>> sum(days)

Traceback (most recent call last):

File “<pyshell#72>”, line 1, in <module>

sum(days)

TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

5. any()

This function returns True even if one item in the set has a Boolean value of True.

1. >>> any({0})

False

1. >>> any({0,'0'})
True

It returns True because the string ‘0’ has a Boolean value of True.

6. all()

Unlike the any() function, all() returns True only if all items in the Python set have a Boolean value of True.
Otherwise, it returns False.

1. >>> all({0,'0'})

False

1. >>> all(days)

True

7. sorted()

The sorted() function returns a sorted python set to list. It is sorted in ascending order, but it doesn’t modify the
original set.

1. >>> numbers={1, 2, 3, 4, 5, 6, 3.5}


2. >>> sorted(numbers)

[1, 2, 3, 3.5, 4, 5, 6]

f. Methods on Sets
Unlike a function in Python set, a method may alter a set. It performs a sequence on operations on a set, and
must be called on it. So far, we have learned about the methods add(), clear(), discard(), pop(), remove(), and
update(). Now, we will see more methods from a more mathematical point of view.

1. union()

This method performs the union operation on two or more Python sets. What it does is it returns all the items
that are in any of those sets.

Union in Python Set

1. >>> set1,set2,set3={1,2,3},{3,4,5},{5,6,7}
2. >>> set1.union(set2,set3)

{1, 2, 3, 4, 5, 6, 7}

1. >>> set1

{1, 2, 3}

As you can see, it did not alter set1. A method does not always alter a set in Python.

2. intersection()

This method takes as argument sets, and returns the common items in all the sets.

Intersection Set in Python

1. >>> set2.intersection(set1)

{3}

Let’s intersect all three sets.

1. >>> set2.intersection(set1,set3)

set()

It returned an empty set because these three sets have nothing in common.

3. difference()

The difference() method returns the difference of two or more sets. It returns as a set.
Difference Python Set

1. >>> set1.difference(set2)

{1, 2}

This returns the items that are in set1, but not in set2.

1. >>> set1.difference(set2,set3)

{1, 2}

4. symmetric_difference()

This method returns all the items that are unique to each set.

Symmetric difference set in Python

1. >>> set1.symmetric_difference(set2)

{1, 2, 4, 5}

It returned 1 and 2 because they’re in set1, but not in set2. It also returned 4 and 5 because they’re in set2, but
not in set1. It did not return 3 because it exists in both the sets.

5. intersection_update()

As we discussed in intersection(), it does not update the set on which it is called. For this, we have the
intersection_update() method.

1. >>> set1.intersection_update(set2)
2. >>> set1

{3}

It stored 3 in set1, because only that was common in set1 and set2.

6. difference_update()

Like intersection-update(), this method updates the Python set with the difference.
1. >>> set1={1,2,3}
2. >>> set2={3,4,5}
3. >>> set1.difference_update(set2)
4. >>> set1

{1, 2}

7. symmetric_difference_update()

Like the two methods we discussed before this, it updates the set on which it is called with the symmetric
difference.

1. >>> set1={1,2,3}
2. >>> set2={3,4,5}
3. >>> set1.symmetric_difference_update(set2)
4. >>> set1

{1, 2, 4, 5}

8. copy()

The copy() method creates a shallow copy of the Python set.

1. >>> set4=set1.copy()
2. >>> set1,set4

({1, 2, 4, 5}, {1, 2, 4, 5})

9. isdisjoint()

This method returns True if two sets have a null intersection.

1. >>> {1,3,2}.isdisjoint({4,5,6})

True

However, it can take only one argument.

1. >>> {1,3,2}.isdisjoint({3,4,5},{6,7,8})

Traceback (most recent call last):

File “<pyshell#111>”, line 1, in <module>

{1,3,2}.isdisjoint({3,4,5},{6,7,8})

TypeError: isdisjoint() takes exactly one argument (2 given)

10. issubset()
This method returns true if the set in the argument contains this set.

1. >>> {1,2}.issubset({1,2,3})

True

1. >>> {1,2}.issubset({1,2})

True

{1,2} is a proper subset of {1,2,3} and an improper subset of {1,2}.

11. issuperset()

Like the issubset() method, this one returns True if the set contains the set in the argument.

1. >>> {1,3,4}.issuperset({1,2})

False

1. >>> {1,3,4}.issuperset({1})

True

g. Operations on Sets
Now, we will look at the operations that we can perform on sets.

1. Membership

We can apply the ‘in’ and ‘not in’ python operators on items for a set. This tells us whether they belong to the
set.

1. >>> 'p' in {'a','p','p','l','e'}

True

1. >>> 0 not in {'0','1'}

True

h. Iterating on a Set
Like we have seen with lists and tuples, we can also iterate on a set in a for-loop.

1. >>> for i in {1,3,2}:


2. print(i)

1
2

As you can see, even though we had the order as 1,3,2, it is printed in ascending order.

i. The frozenset
A frozen set is in-effect an immutable set. You cannot change its values. Also, a set can’t be used a key for a
dictionary, but a frozenset can.

1. >>> {{1,2}:3}

Traceback (most recent call last):

File “<pyshell#123>”, line 1, in <module>

{{1,2}:3}

TypeError: unhashable type: ‘set’

Now let’s try doing this with a frozenset.

1. >>> {frozenset(1,2):3}

Traceback (most recent call last):

File “<pyshell#124>”, line 1, in <module>

{frozenset(1,2):3}

TypeError: frozenset expected at most 1 arguments, got 2

As you can see, it takes only one argument. Now let’s see the correct syntax.

1. >>> {frozenset([1,2]):3}

{frozenset({1, 2}): 3}

3. Python Booleans
Finally, let’s discuss Booleans. A Boolean is another data type that Python has to offer.

a. Value of a Boolean
As we have seen earlier, a Boolean value may either be True or be False. Some methods like isalpha() or
issubset() return a Boolean value.
b. Declaring a Boolean
You can declare a Boolean just like you would declare an integer.

1. >>> days=True

As you can see here, we didn’t need to delimit the True value by quotes. If you do that, it is a string, not a
Boolean. Also note that what was once a set, we have reassigned a

Boolean to it.

1. >>> type('True')

<class ‘str’>

c. The bool() function


Like we have often seen earlier, the bool() function converts another value into the Boolean type.

1. >>> bool('Wisdom')

True

1. >>> bool([])

False

d. Boolean Values of Various Constructs


Different values have different equivalent Boolean values. In this example, we use the bool() Python set
function to find the values.

For example, 0 has a Boolean value of False.

1. >>> bool(0)

False

1 has a Boolean value of True, and so does 0.00000000001.

1. >>> bool(0.000000000001)

True

A string has a Boolean value of True, but an empty string has False.

1. >>> bool(' ')


True

1. >>> bool('')

False

In fact, any empty construct has a Boolean value of False, and a non-empty one has

True.

1. >>> bool(())

False

1. >>> bool((1,3,2))

True

e. Operations on Booleans
1. Arithmetic
You can apply some arithmetic operations to a set. It takes 0 for False, and 1 for True, and then applies the
operator to them.

 Addition

You can add two or more Booleans. Let’s see how that works.

1. >>> True+False #1+0

1. >>> True+True #1+1

1. >>> False+True #0+1

1. >>> False+False #0+0

 Subtraction and Multiplication

The same strategy is adopted for subtraction and multiplication.

1. >>> False-True

-1
 Division

Let’s try dividing Booleans.

1. >>> False/True

0.0

Remember that division results in a float.

1. >>> True/False

Traceback (most recent call last):

File “<pyshell#148>”, line 1, in <module>

True/False

ZeroDivisionError: division by zero

This was an exception that raised. We will learn more about exception in a later lesson.

 Modulus, Exponentiation, and Floor Division

The same rules apply for modulus, exponentiation, and floor division as well.

1. >>> False%True
2. >>> True**False

1. >>> False**False

1. >>> 0//1

Try your own combinations like the one below.

1. >>> (True+True)*False+True

2. Relational

The relational operators we’ve learnt so far are >, <, >=, <=, !=, and ==. All of these apply to Boolean values.
We will show you a few examples, you should try the rest of them.

1. >>> False>True

False
1. >>> False<=True

True

Again, this takes the value of False to be 0, and that of True to be 1.

3. Bitwise

Normally, the bitwise operators operate bit-by bit. For example, the following code ORs the bits of 2(010) and
5(101), and produces the result 7(111).

1. >>> 2|5

But the bitwise operators also apply to Booleans. Let’s see how.

 Bitwise &

It returns True only if both values are True.

1. >>> True&False

False

1. >>> True&True

True

Since Booleans are single-bit, it’s equivalent to applying these operations on 0 and/or

1.

 Bitwise |

It returns False only if both values are False.

1. >>> False|True

True

 Bitwise XOR (^)

This returns True only if one value is True and one is False.

1. >>> False^True

True

1. >>> False^False
False

1. >>> True^True

False

 Binary 1’s Complement

This calculates 1’s complement for True(1) and False(0).

1. >>> ~True

-2

1. >>> ~False

-1

 Left-shift(<<) and Right-shift(>>) Operators

As discussed earlier, these operators shift the value by specified number of bits left and right, respectively.

1. >>> False>>2
2. >>> True<<2

True is 1. When shifted two places two the left, it results in 100, which is binary for 4. Hence, it returns 4.

4. Identity

The identity operators ‘is’ and ‘is not’ apply to Booleans.

1. >>> False is False

True

1. >>> False is 0

False

5. Logical

Finally, even the logical operators apply on Booleans.

1. >>> False and True

False

This was all about the article on Python set and booleans.
4. Conclusion
In conclusion, we see that a Python Boolean value may be True or False. You may create it or use it when it’s
returned by a method. We learned how to create, access, update, and delete a set. We saw how it is mutable and
that is why we can’t use indexing to access, update, or delete it. So, we use certain Python set functions and
methods for the same. Lastly, we learned about various operations that we can apply on a set. And we learned
that some bitwise and logical operators mean the same thing on Booleans. See you tomorrow. Hope you liked
our article on python sets and booleans.
Refer Best python books for detailed study.

Python List Comprehension (Syntax & Examples) – Nested List


Comprehension Python
by DataFlair Team · October 21, 2018

1. Python List Comprehension


Previously, we discussed Lists in Python. In that tutorial, what is Python list comprehension and how to use
it? Along with this, we will learn syntax, list comprehension vs lambda expression in Python3. Along with this,
we will study conditionals and nested list comprehension in Python Programming Language.

So, let’s begin the Python list comprehension Tutorial.

Python List Comprehension with Syntax and Examples


2. What is Python List Comprehension?
To get Python list comprehensions back into memory, we’ll take a quick example.

Suppose you want to take the letters in the word ‘anxiety’, and want to put them in a list. Remember that a
python string is iterable.

Using a for loop, you would:

1. >>> mylist=[]
2. >>> for i in 'anxiety':
3. mylist.append(i)
4. >>> mylist

[‘a’, ‘n’, ‘x’, ‘i’, ‘e’, ‘t’, ‘y’]

But with a Python list comprehension, you can do this in one line:

1. >>> [i for i in 'anxiety']

[‘a’, ‘n’, ‘x’, ‘i’, ‘e’, ‘t’, ‘y’]

Now that we’ve got your interest, we’ll dig a little deeper.

3. The syntax of List Comprehension in Python


For a python list comprehension, we use the delimiters for a list- square brackets. Inside those, we use a for-
statement on an iterable (a list, here). We’ll take an example.

1. >>> [i*2 for i in {3,1,2}]

[2, 4, 6]

Here, we return twice of every value in the set {3,1,2} into a new list.

So we guess we can state the syntax for a Python list comprehension as follows:

[expression for item in list]

Note that not every loop has an equivalent list comprehension in Python.

4. Python List Comprehension vs Lambda Expression


Something about this syntax leaves us nostalgic. Remember when we learned about python lambda
expressions in an earlier lesson? A Python 3 lambda expression returns a certain expression’s value which it
calculates using values of the arguments it receives. Let’s create a list from a set using the list comprehension
syntax.
1. >>> myset={3,1,2}
2. >>> makelist=lambda i:list(i)
3. >>> mylist=makelist(myset)
4. >>> mylist

[1, 2, 3]

Here, we first took a set {3,1,2}. Like you’re aware by now, it rearranges itself as {1,2,3}. Then, we defined a
lambda function, and stored it in the variable ‘makelist’. This lambda function takes a value, converts it into a
list, and returns it. Finally, we called makelist on the set myset, and stored it in the variable mylist, which now
holds a list.

1. >>> type(mylist)

<class ‘list’>

To do this using the map function instead, we write the following code:

1. >>> list(map(lambda i:i,myset))

[1, 2, 3]

This code first takes a lambda expression: For each value i, it returns i and maps this on each value in the set
myset. Next,