Getting Started With Python Programming
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:
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
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
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
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
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
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. 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
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
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. Web Frameworks
2. Django
3. Flask
1. Python vs Java
2. Python vs Scala
3. Python vs R
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!
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.
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.
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
ii. Compiler
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:
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).
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 (:).
Output: 21
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
iii. Object-Oriented
The Python programming language supports classes and objects. We discussed these above.
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.
You can use it to develop a GUI (Graphical User Interface). One way to do this is through Tkinter.
6. Python Frameworks
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
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.
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++.
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.
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.
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
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.
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.
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.
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.
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.
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.
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
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.
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.
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
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.
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.
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.
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
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.
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
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.
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.
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.
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.
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.
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!
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.
For Reference-
Django
Flask
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.
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
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.
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.
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!
If you want to explore Python more, you need to check how Netflix is using Python
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.
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.
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 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.
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.
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.
– 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.
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
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.
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
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
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:
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
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.
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?
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
So, this was all about our blog post on Python Career Opportunities
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.
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.
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.
a. What to study?
As a fresher in Python, you should study the following things to build a strong foundation in Python.
DataFlair has published a Python Master Guide for you by which you can learn all these topics.
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.
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.
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.
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
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. >>>
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:
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:
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.
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
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.
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.
Ready to build your own model? Speech Emotion Recognition Python Project with Source Code
Check the complete python project with source code – Detecting Parkinson’s Disease with Python
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
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.
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.
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.
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.
One such use-case is to use clustering in a telephone company to determine tower locations for optimum signal
strength.
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.
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.
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.
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.
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.
So, now you know what data science is all about. But why is Python the best choice for it? Here are a few
reasons-
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.
For carrying out data analysis and other scientific computation, you will need any of the following 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.
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.
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.
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?
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.
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.
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.
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.
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!
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.
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–
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.
This should give you an idea of what the Anaconda prompt looks like. Now, to activate this environment, you
can type-
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
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
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
Optimization
Linear algebra
Integration
Interpolation
Special functions
FFT
Signal and Image processing
ODE solvers
c. 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
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
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
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 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.
In this article on Python 3.6, we will discuss the following new features in Python 3.6. Moreover, we will
discuss
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.
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}")
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.
With PEP 515, we can use underscores in numeric literals- between digits and after base specifiers.
1. >>>
0x_FF_FE_FF_FE
4294901758
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:
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]
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
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.
With Python 3.6, no data loss occurs when we use bytes paths on Windows.
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.
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.
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.
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.
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.
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.
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(τ).
6.283185307179586
Reversible ABC- to represent iterable classes. These also provide the method reversed ().
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.
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.
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:
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.
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.
Installing and running Python on your personal computer is no difficult task. It involves just a few simple steps:
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.
This is the default option. It also includes the IDLE (Integrated Development Environment),
This option allows you to choose the features that you want.
Documentation
pip
tcl/tk and IDLE- installs tkinter and the IDLE
Python test suite- This installs the standard library test suite of 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.
You have now installed Python. Now, you can find a list of programs in the Start Menu.
Install Python 3 on Windows
a. Command Prompt
You can run Python on the command prompt in two ways:
python
Now, you can use it as an interpreter. As an example, we have calculated 2+3.
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.
b. The IDLE
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)
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.
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.
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.
Python Applications
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.
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
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:
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.
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
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.
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.
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
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.
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!
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.
Let us see various basic python syntax that is used while doing programming in Python.
A Python program comprises logical lines. A NEWLINE token follows each of those. The interpreter ignores
blank lines.
1. >>> print("Hi
2. How are you?")
Output:
If you face any doubt anywhere in the Python Syntax Tutorial, Please Comment.
Output:
You can also use it to distribute a statement without a string across lines.
1. >>> a\
2. =\
3. 10
4. >>> print(a)
Output:
10
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:
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 (#).
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.
Output:
Hi
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:
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.
chaperone'); Output:
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.
Output:
If you leave a line with just whitespace, the interpreter will ignore it.
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:
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.
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.
printer)) Output:
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:
You can also use the method to print out identifiers that match certain values.
printer='HP')) Output:
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.
Output:
So, this was all about the Python Syntax tutorial. Hope you like our explanation
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.
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.
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
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'>
7
You can also do this to an if-statement.
“Hello ‘user'”
If you use double quotes outside, use single quotes wherever you need to use a quote inside.
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")
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) (#).
You can also use triple quotes (‘’’ ‘’’ or “”” “””) for this purpose.
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.
Hi
To check a function’s docstring, use its doc attribute.
So, this was all about Python indentation, comment and statement. Hope you like our explanation.
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 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
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.
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)
So, this was all in Python Assert. Hope you like our explanation
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.
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.
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.
3. Python int
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
i. type() function
It takes one argument, and returns which class it belongs to.
1. >>> a=9999999999999999999999999999999999999
2. >>> type(a)
<class ‘int’>
1. >>>
isinstance(a,bool) False
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.
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
1. >>> 2/2
1.0
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)
1. >>> a=2+3i
SyntaxError: invalid syntax
1. >>> a=2+j
a=2+j
1. >>> a=2+1j
2. >>> a
(2+1j)
1. >>> a=2+3j
2. >>> b=2+5j
3. >>> a+b
(4+8j)
1. >>> a*=2
2. >>> a
(4+6j)
More often than not, programmers need to deal with numbers other than decimal. To do this, you can use
appropriate prefixes.
1. >>> print(0b111)
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)
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
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.
1. >>> int(2+3j)
int(2+3j)
TypeError: can’t convert complex to int
1. >>> int(3j)
int(3j)
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
1. >>> float(3j)
float(3j)
1. >>> float(0o10)
8.0
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)
bin(2.3)
1. >>> bin(2+3j)
bin(2+3j)
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)
oct(8.0)
vi. hex()
The hex() function returns the hexadecimal value of a number.
1. >>> hex(255)
‘0xff’
1. >>> hex(0)
‘0x0’
1. >>> hex(0)
‘0x0’
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
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.
0.1000000000000000055511151231257827021181583404541015625
Did you see what happened here? The Decimal() function preserved the significance.This was the Decimal
Function Python number type.
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.
3/2
1. >>> print(Fraction(1,3))
1/3
120
1. >>> math.exp(3)
20.085536923187668
1. >>> math.tan(90)
-1.995200412208242
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.
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.
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.
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
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.
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
(5, 2, 6)
We asked for three random values, this gave us 5, 2, and 6.
Let’s learn Python Debugger
-1
1. >>> randrange(-2,4)
1. >>> randrange(-2,4)
1. >>> randrange(-2,4)
-1
1. >>> randrange(-2,4)
2
1. >>> randrange(-2,4)
-2
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
[7, 2, 9, 7]
1. >>> list
[2, 4, 3, 9, 6, 2, 1, 0, 7, 4, 3, 5, 3, 6, 8]
[6, 7, 4, 2, 4, 2]
1. >>> list
[2, 4, 3, 9, 6, 2, 1, 0, 7, 4, 3, 5, 3, 6, 8]
[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
With the seed() and rand() functions/ methods from NumPy, we can generate random numbers. The
functionality is the same as above.
1. >>> seed(7)
2. >>> rand(3)
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.
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
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’.
1. >>> 9lives=9
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
Python is case-sensitive, and so are Python identifiers. Name and name are two different identifiers.
1. >>> name='Ayushi'
2. >>> name
‘Ayushi’
1. >>> Name
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
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
1. >>> False=choice
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
1. >>> age=fav=7
2. >>> print(age,fav)
77
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
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’
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,
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,
1010
1. >>> print('10'+10)
print(’10’+10)
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
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
d. Python Tuples
A tuple is like a list. You declare it using parentheses instead.
1. >>> subjects=('Physics','Chemistry','Maths')
2. >>> subjects
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’)
1. >>> subjects[2]='Biology'
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
1. >>> type(person)
<class ‘dict’>
1. Accessing a value– To access a value, you mention the key in square brackets.
1. >>> person['city']
‘Ahmedabad’
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}
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)
1. >>> int("a")
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")
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
1. >>> bool([1,2])
True
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. >>> list({1,2,2,3})
[1, 2, 3]
1. >>> list({"a":1,"b":2})
[‘a’, ‘b’]
1. >>> list({a:1,b:2})
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)
1. >>> uvw
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
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.
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.
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
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()
func()
print(a)
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
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.
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.
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’.
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.
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
Lowercase letters (a to z)
Uppercase letters (A to Z)
Digits (0 to 9)
Underscore (_)
myVar
var_3
this_works_too
_9lives
lives9
An invalid name:
9lives
c. We cannot use special symbols in the identifier name. Some of these are:
!
@
#
$
%
.
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.
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
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.
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.
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.
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.
False
True
1. >>> '9lives'.isidentifier()
False
1. >>> '9.5okay'.isidentifier()
False
Let’s discuss Python Flask
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.
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.
<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.
However, you cannot use a single quote to begin a string and a double quote to end it, and vice-versa.
Since we delimit strings using quotes, there are some things you need to take care of when using them inside a
string.
If you need to use double quotes inside a Python string, delimit the string with single quotes.
And if you need to use single quotes inside a string, delimit it with double quotes.
When you want to span a Python string across multiple lines, you can use triple quotes.
Hello
Welcome
It preserves newlines too, unlike using a backward slash for the same.
1. >>> a="Hello\
2. Welcome"
3. >>> print(a)
Hello Welcome
1. >>> a="Dogs"
2. >>> a[0]="H"
a[0]=”H”
1. >>> print(a)
‘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’
1. >>> a[:8]
‘Dogs are’
1. >>> a[8:]
‘ love’
1. >>> a[:]
1. >>> a[:-2]
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]
Concatenation is the operation of joining stuff together. Python Strings can join using the concatenation
operator +.
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
’10’+10
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)
1. >>> name='Ayushi'
2. >>> print(f"It isn't {name}'s birthday")
Notice that because we wanted to use two single quotes in the string, we delimited the entire string with double
quotes instead.
I love dogs
I love cats
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))
%d – for integers
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.
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’]”
1. >>> a='Book'
2. >>> a.lower()
‘book’
1. >>> a.upper()
‘BOOK’
d. strip()
It removes whitespaces from the beginning and end of the string.
‘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.
True
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.
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’
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.
True
False
d. Identity
Python’s identity operators ‘is’ and ‘is not’ can be used on strings.
False
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.
”
2. or- If the value on the left is True, it returns True. Otherwise, the value on the right
is returned.
1. >>> not('1')
False
1. >>> not('')
True
This was all about the tutorial on Python strings. Hope you like the Python strings tutorial.
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.
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-
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:
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 -*-
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.
Interactive editing
History substitution
Code completion on systems with support for readline
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. …
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:
So, we conclude that a code object is an attribute of a function object. The dir() function will tell us more about
the function:
(‘a’, ’x’)
(None, 3)
b. The Bytecode
The following command gives us the bytecode:
‘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.
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.
‘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.
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.
It is recommended to check the Python master guide before we start with the operator in Python.
These Python arithmetic operators include Python operators for basic mathematical operations.
Arithmetic Operators in Python
a. Addition(+)
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(*)
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(**)
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(%)
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.
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
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
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
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
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
Adds the values on either side and assigns it to the expression on the left. a+=10 is the same as a=a+10.
1. >>> a+=2
2. >>> print(a)
Output: 9
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
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
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
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
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
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
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.
a. and
If the conditions on both the sides of the operator are true, then the expression as a whole is true.
Output: False
b. or
The expression is false only if both the statements around the operator are false. Otherwise, it is true.
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
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
Output: True
Output: True
b. not in
Output: True
Don’t you know about the trending Python Project at DataFlair? Here it is – Gender and Age Detection
with Python
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
Output: True
b. is not
Output: True
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
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
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
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.
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.
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’
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).
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.
0&0 0
0&1 0
1&0 0
1&1 1
1. >>> '$'&'%'
‘$’&’%’
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
1. >>> 1&True
1. >>> 1.0&1.0
1.0&1.0
Here, 110 is binary for 6, and 101 for 5. &-ing them, we get 100, which is binary for 4.
Compared to &, this one returns 1 even if one of the two corresponding bits from the two operands is 1.
0|0 0
0|1 1
1|0 1
1|1 1
1. >>> 6|1
1. >>> 0b110|0b001
1. >>> True|False
True
XOR (eXclusive OR) returns 1 if one operand is 0 and another is 1. Otherwise, it returns 0.
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
1. >>> 6^3
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.
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.
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.
1. >>> int(0b11111)
31
1. >>> 31>>3
3
As you can see, it gives us 3, whose binary is 11. Makes sense, doesn’t it?
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.
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.
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
1. >>> 3<3
Output: False
Because 3 is equal to 3, and not less than it, this returns False.
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
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’.
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
1. >>> (1,2)<('One','Two')
(1,2)<(‘One’,’Two’)
However, if you get comparable elements at the same indices, it is possible to compare two tuples.
1. >>> (1,'one')<(2,'two')
Output: True
1. >>> (1,'one')<('two',2)
(1,’one’)<(‘two’,2)
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'}
{1:’one’,2:‘two‘}<{1:‘three‘,2:‘four‘}
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.
1. >>> 0.5>False
Output: True
1. >>> 3,4,5>3,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)
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.
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
Likewise, this operator returns True only if the value on the left is greater than or equal to that on the right.
Output: False
Any doubt in Python Comparison Operators? Please Ask us in the comment.
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
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.
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.
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.
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’
‘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.
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
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-
sub for –
mul for *
truediv for /
floordiv for //
mod for %
pow for **
or for |
isub for -=
imul for *=
idiv for /=
imod for %=
ixor for ^=
ior for |=
pos for +
invert 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. >>> 2+a
3
If the interpreter cannot add left to right, it will call radd () instead. Here, radd is in reverse/reflected add.
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
To really understand something, once is never enough. So, let’s take another example of Operator overloading
in Python.
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.
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:
’11’
[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.
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.
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
1. >>> a,b=2,3
2. >>> if a>b:
3. print("a")
4. else:
5. print("b")
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
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:
‘b’
1. >>> a,b
(0.009415785735741311, 0.9675879478005226)
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]
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.
‘b:0.5955717855531699’
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.
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:
Hello
Hello
True
Hello
True
So, this was all in Python Ternary Operator. Hope you like our explanation.
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.
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
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.
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
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:
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
False
This stops at the first False it gets (the 0 at the third position) and returns False.
True
This stops at the first True it gets (the 1 at the fourth position) and returns True.
1. >>> 7>8>check(4)
False
This stops at 7>8 and returns False.
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
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 (**)
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.
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
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.
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
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.
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.
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’>
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.
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.
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.
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.
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.
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.
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.
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’.
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.
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.
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.
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.
1. a=7
2. if a>4: print("Greater")
Greater
1. >>>
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!
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.
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.
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
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.
0
1
2
If we wanted to print 1 to 3, we could write the following code.
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]
1. >>> list(range(12,2,-2))
[12, 10, 8, 6, 4]
[]
1. >>> list(range(2,12,-2))
[]
1. >>> list(range(12,2,2))
[]
1
2
3
2
3
4
You can also iterate on a string.
w
i
s
d
o
m
1. >>> list=['Romanian','Spanish','Gujarati']
2. >>> for i in range(len(list)):
3. print(list[i])
Romanian
Spanish
Gujarati
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.
0
1
2
3
4
5
6
7
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. >>> i=6
2. >>> while(i>0):
3. j=6
4. while(j>i):
5. print("*",end=' ')
6. j-=1
7. i-=1
8. print()
*
**
***
****
*****
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.
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.
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).
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.
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.
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.
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.
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.
You can access this docstring using the doc attribute of the function.
However, if you apply the attribute to a function without a docstring, this happens.
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. 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.
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.
3.0+2=5.0
1. >>> sum2('Hello',2)
sum2(‘Hello’,2)
print(f”{a}+{b}={a+b}”)
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. >>> c=sum(2,3)
Hello
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.
If you then try to access the variable x outside the function, you cannot.
1. >>> x
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. >>> y
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. >>> func1()
As you can see here, the function func1() doesn’t print 2 the second time.
When deleting a function, you don’t need to put parentheses after its name.
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.
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.
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
120
1. >>> facto(1)
1. >>> facto(2)
1. >>> facto(3)
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.
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.
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.
Python function is a sequence of statements that execute in a certain order, we associate a name with it.
This lets us reuse code.
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.
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)
There are various types of Python arguments functions. Let’s learn them one by one:
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.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)
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.
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.
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
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'”
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’
1. >>> bin(7.0)
bin(7.0)
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]
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’
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]=
a[4]=3
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.
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. >>> delattr(fruit,'size')
2. >>> orange.size
orange.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}
16. dir()
dir() returns an object’s attributes.
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.
(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)')
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')
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))
24. frozenset()
frozenset() returns an immutable frozenset object.
1. >>> frozenset((3,2,4))
frozenset({2, 3, 4})
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()
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
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’
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.
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.
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. >>> issubclass(fruit,citrus)
False
36. iter()
Iter() Python built-in functions, returns a python iterator for an object.
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()
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.
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>
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)
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)
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
1. >>> f=open('topics.txt')
2. >>> f
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
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.
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.
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
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')
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.
Hi
You can also use the syntactic sugar @staticmethod for this.
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.
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)
67. zip()
zip() returns us an iterator of tuples.
1. >>> set(zip([1,2,3],['a','b','c']))
1. >>> set(zip([1,2],[3,4,5]))
1. >>> a=zip([1,2,3],['a','b','c'])
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.
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.
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.
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’.
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.
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:
blackverna.drift()
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.
‘Female’
However, you don’t need to define this function if you don’t need it in your code.
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.
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.
As you can see, the ‘self’ parameter told the method to operate on the current object, that is, orange. Let’s take
another example.
95
1. >>> rollone.printavg()
Average=88.66666666666667
You can also assign values directly to the attributes, instead of relying on arguments.
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.
‘Leo’
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.
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 &
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.
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.
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.
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.
Begin
23
2.0 3
False
23
<class ‘int’>
<class ‘function’>
Also see, ython Lambda Expressions.
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.
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.
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.
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.
Output – 7
Let’s take a look at Python Slice Constructor
We can also do this inside class functions:
Output – 8
Output – 6
Or we can ask the user for input.
What value?8
1. >>> t.val
Output – ‘8’
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.
Output – I detoxify
Now statement by statement, let’s see what’s happening.
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
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.
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.
The range() function is an inbuilt function in Python, and it returns a range object. First, let’s see what it looks
like.
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)
1. >>> list(range(3))
[0, 1, 2]
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))
[]
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))
1. >>> list(range(-7,-3))
1. >>> list(range(-3,-7))
[]
This, again, returns an empty list, for -3 lies to the right of -7.
1. >>> list(range(3,3))
[]
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))
list(range(1,7,1.5))
1. >>> list(range(1,7,2))
[1, 3, 5]
1. >>> list(range(1,7,0))
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.
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.
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.
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.
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, ‘a’)
(2, ‘b’)
(3, ‘c’)
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
1. >>> set(zip())
set()
You can see that this returns an empty iterator.
Single argument
(1,)
(2,)
(3,)
This returns tuples holding single values
1. print(i)
(1, ‘a’)
(2, ‘b’)
(3, ‘c’)
This zips elements together from each list. How about more than two?
When we provide multiple lists of different lengths, it stops at the shortest one.
1. >>> set(zip([1,2],[3,4,5]))
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. >>> z=zip([1,2],[3,4,5])
2. >>> a,b=zip(*z)
3. >>> a,b
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.
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().
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.
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
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.
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.
In the examples so far, we hardcoded the expression. What if we wanted to let the user provide one instead?
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.
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
1. >>> eval(expr)
Did you see how easy it was to extract the password from the code? All it took was one call to a function.
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. >>> safe_dict={}
2. >>> safe_dict['x']=x
3. >>> eval(expr,safe_dict)
40
1. >>> eval(expr,safe_dict)
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.
So before we leave, let’s take a rather practical example of Python eval() Function.
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.
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.
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
1. >>> type(exec)
<class ‘builtin_function_or_method’>
Let’s check the help for this.
1. >>> help(exec)
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
1. >>> exec(code)
0
1
4
9
16
25
36
1. >>> import os
2. >>> code=input('What would you like to do today?')
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. >>> 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.
1. >>> dir()
1. >>> a=7
2. >>> def hello():
print("Hello") 3. >>> dir()
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 )
1. >>> exec('print(tan(90))')
-1.995200412208242
1. >>> exec('print(tan(90))',{})
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.
[‘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())',globals(),locals())
So, let’s start the Python repr Function. Hope you like our explanation.
repr(obj, /)
It is true for many object types and most builtins that eval(repr(obj))=obj
1. >>> s='Hello'
2. >>> eval(repr(s))
‘Hello’
1. >>> s
‘Hello’
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.
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.
“‘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:
‘Hello, world!’
eval(‘Hello, world!’)
Hello, world!
This is because we don’t have a variable with that name (Hello, world!)
“‘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. >>> print(o)
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. >>> print(o)
I am 7 and orange
That was pretty cool! In Java, we would use the toString() method for this.
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 ().
Take a look:
1. >>> str(3)
‘3’
1. >>> repr(3)
‘3’
They appear the same. Okay, now take a look at this one:
‘2018-09-07 17:33:24.261778’
1. >>> repr(t)
1. >>> t
Using this ‘official’ representation, we can reconstruct the object, but not with what str() gives us:
eval(‘2018-09-07 17:33:24.261778’)
2018-09-07 17:33:24.261778
1. >>> print(d)
1. >>> str(d)
1. >>> repr(d)
1. >>> f'{d}'
So, this was all in Python repr tutorial. Hope you like our explanation.
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.
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.
To access an entire list, all you need to do is to type its name in the shell.
1. >>> list1
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]
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.
Suppose we want items second through fourth from list ‘list1’. We write the following code for this.
1. >>> list1[1:4]
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]
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[2]='Java'
2. >>> languages
To delete an entire list, use the del keyword with the name of the list.
1. >>> list1
list1
[‘C++’, ‘Python’]
[‘C++’]
1. >>> list1=[1,2,3,4,5,6,7,8]
1. >>> list1[0]=0
2. >>> list1
[0, 2, 3, 4, 5, 6, 7, 8]
2. Reassigning a slice
1. >>> list1[1:3]=[9,10,11]
2. >>> list1
1. >>> list1=[0,0,0]
2. >>> list1
[0, 0, 0]
To get an even deeper look into lists, read our article on Python Lists.
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.
1. >>> colors=('Red','Green','Blue')
(1, 2, 3)
1. >>> a,b,c=mytuple
2. >>>
print(a,b,c) 1 2 3
1. >>> a=(1)
1. >>> type(a)
<class ‘int’>
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’>
del a[0]
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}
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.
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]
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
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.
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.
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']
1. >>> days=['Monday','Tuesday','Wednesday',4,5,6,7.0]
1. >>> languages=[['English'],['Gujarati'],['Hindi'],'Romanian','Spanish']
2. >>> languages
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'
languages[0][0]=’Albanian’
1. >>> days
1. >>> languages=[['English'],['Gujarati'],['Hindi'],'Romanian','Spanish']
2. >>> print(languages)
To access a single element, use its index in square brackets after the list’s name. Indexing begins at 0.
1. >>> languages[0]
[‘English’]
1. >>> languages[1.0]
languages[1.0]
TypeError: list indices must be integers or slices, not float
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’]
1. >>> indices[:4]
1. >>> indices[4:]
[‘four’, ‘five’]
1. >>> indices[:]
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]
This returns item from the list’s beginning to two items from the end.
1. >>> indices[1:-2]
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.
1. >>> colors=['red','green','blue']
1. >>> colors=['caramel','gold','silver','occur']
2. >>> colors
1. >>> colors[2:]=['bronze','silver']
2. >>> colors
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
1. >>> colors[2:2]=['occur']
2. >>> colors
Now if you want to add another item ‘holographic’ to the list, we cannot do it the conventional way.
1. >>> colors[4]='holographic'
colors[4]=’holographic’
So, you need to reassign the whole list for the same.
1. >>> colors=['caramel','gold','silver','bronze','holographic']
2. >>> colors
You can delete a Python list, some of its elements, or a single element.
colors
1. >>> colors=['caramel','gold','silver','bronze','holographic']
2. >>> del colors[2:4]
3. >>> colors
[‘caramel’, ‘gold’, ‘holographic’]
1. >>> colors[2]
‘holographic’
[‘gold’,
‘holographic’]
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
This is a grocery Python list with lists in it, where the lists are according to a category.
1. >>> a=[[[1,2],[3,4],5],[6,7]]
2. >>> a
To access the element 4 here, we type the following code into the shell.
1. >>> a[0][1][1]
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]
1. >>> a*3.0
a*3.0
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
2 is composite
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.
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.
There are some built-in functions in Python that you can use on python lists.
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
1. >>> max(['1','2','3'])
‘3’
But it fails when some are numeric, and some are strings in python.
1. >>> max([2,'1','2'])
max([2,’1′,’2′])
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)
sum(a)
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'])
f. list()
It converts a different data type into a list.
1. >>> list("abc")
It can’t convert a single int into a list, though, it only converts iterables.
1. >>> list(2)
list(2)
g. any()
It returns True if even one item in the Python list has a True value.
1. >>> any(['','','1'])
True
1. >>> any([])
False
h. all()
It returns True if all items in the list have a True value.
1. >>> all(['','','1'])
False
1. >>> all([])
True
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.
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]
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
[]
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]
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
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.
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.
1. >>> percentages=(99,95,90,89,93,96)
2. >>> a,b,c,d,e,f=percentages
3. >>> c
90
1. >>> a=(1)
2. >>> type(a)
<class ‘int’>
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')
1. >>>
1. >>> print(percentages)
1. >>> percentages[1]
95
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]
1. >>> percentages[4:]
(93, 96)
This prints out items from index 4 to the end of the list.
1. >>> percentages[2:2]
()
b. Negative indexing
Now, let’s look at negative indexing. Unlike positive indexing, it begins traversing from the right.
1. >>> percentages[:-2]
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
Lastly, when you provide no indices, it prints the whole Python tuple.
1. >>> percentages[:]
del percentages[4]
So, deleting a single element didn’t work. Let’s try deleting a slice.
del percentages[2:4]
As you can see, that didn’t work either. Now, let’s try deleting the entire tuple.
percentages
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])
1. >>> my_tuple[3]=6
Traceback (most recent call last):
my_tuple[3]=6
See, that failed. Now how about changing an element from the same list]?
1. >>> my_tuple[3][0]=6
2. >>> my_tuple
This worked without a flaw. So we can see that while tuples are immutable, a mutable item that it holds may be
reassigned.
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.
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)
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)
1. >>> max(('Hi','hi','Hello'))
‘hi’
‘hi’ is the greatest out of these, because h has the highest ASCII value among h and H.
1. >>> max(('Hi',9))
max((‘Hi’,9))
c. min()
Like the max() function, the min() returns the item with the lowest values.
1. >>> min(a)
d. sum()
This function returns the arithmetic sum of all the items in the tuple.
1. >>> sum(a)
21
1. >>> sum(('1','2','3'))
sum((‘1′,’2′,’3’))
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)
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.
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)
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
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)
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.
You can iterate on a Python tuple using a for loop like you would iterate on a list.
1
3
2
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])
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.
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.
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))
1. >>> numbers[1]
1. >>> numbers[:-1]
(4, 5)
numbers
We also learned some functions and methods on tuples and lists. You must read our tutorials on them for more
insight.
Unlike in C++, we don’t have arrays to work with in Python. Here, we have a list instead.
1. >>>
colors=['red','blue','green'] We can
1. >>> colors[-2:]
[‘blue’, ‘green’]
1. >>> colors[0]='pink'
2. >>> colors
‘blue’
colors
Now that we’ve refreshed our memories, we can proceed to differentiate between python tuples vs lists.
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]
1. >>> list1=[7,6,5,4,3,2,1,0]
2. >>> list1
[7, 6, 5, 4, 3, 2, 1, 0]
It worked, great.
[7, 5, 4, 3, 2, 1, 0]
This was easy, but could we delete a slice of the list? Let’s try it.
[7, 5, 4]
1. >>> nums=[1,2,3,4,5]
2. >>> nums[1:3]=[6,7,8]
3. >>> nums
[1, 6, 7, 8, 4, 5]
list1
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
1. >>> mytuple[1]=3
mytuple[1]=3
1. >>> mytuple=2,3,4,5,6
2. >>> mytuple
(2, 3, 4, 5, 6)
1. >>> mytuple[3:]
(5, 6)
del mytuple[3:]
As is visible, we can slice it to access it, but we can’t delete a slice. This is because it is immutable.
del mytuple[3]
mytuple
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
1. >>> mylist=[(1,2,3),(4,5,6)]
2. >>> type(mylist)
<class ‘list’>
1. >>> type(mylist[1])
<class ‘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]
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]
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.
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.
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’.
True
1. >>> type(namedtuple)
<class ‘function’>
To use any of its functionality, we must first import it.
1. >>> import collections
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.
1. >>> c=Counter('Hello')
2. >>> c
1. >>> c=Counter(a=3,b=2,c=1)
2. >>> c
1. >>> c=Counter()
2. >>> c.update('bfg')
3. >>> c
1. >>> c['f']
1. >>> c['h']
The elements() method returns a python iterator for the values in the container.
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
1. >>> c.most_common(2)
1. >>> c1&c2
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.
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.
35
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
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
1. >>> o.move_to_end('c',last=False)
2. >>> o
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
1. >>> red.r
255
1. >>> red.g
1. >>> red.b
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
1. >>> red._asdict()
1. >>> colors._make(['1','2','3'])
1. >>> colors(**{'r':255,'g':0,'b':0})
1. >>> red._fields
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)
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, 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. >>> c['a']
1. >>> issubclass(Counter,dict)
True
Now, let’s take a look at python counter syntax.
To initialize or define a counter in python, we use the counter factory function. Yet, in that, we can do it in three
ways:
1. >>> c=Counter(['a','b','c','a','b','a'])
2. >>> c
1. >>> c=Counter(('a','b','c','a','b','a'))
2. >>> c
1. >>> c=Counter("Hello")
2. >>> c
1. >>> c=Counter({'a','b','c','a','b','a'})
2. >>> c
1. >>> c=Counter({'a':3,'b':2,'c':1})
2. >>> c
1. >>> c=Counter(a=3,b=2,c=1)
2. >>> c
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
1. >>> d.update({'e':2,'o':4})
2. >>> d
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’
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()
1. >>> e.most_common(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()
Of course, Python Counters aren’t immutable. You can reassign a count the following way:
1. >>> e['e']=5
2. >>> e
1. >>> b.clear()
2. >>> b
Counter()
7. Python Counter Arithmetic
1. >>> a=Counter({'a':3,'b':2,'c':1})
2. >>> b=Counter({'c':3,'d':2,'e':1})
1. >>> a+b
1. >>> a-b
1. >>> b-a
1. >>> a.subtract(b)
2. >>> a
1. >>> a&b
Counter({‘c’: 1})
1. >>> a|b
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.
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.
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
olors[1]=10
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. >>> type(namedtuple)
<class ‘function’>
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
1. >>> pets=namedtuple('pets',['name','age'])
2. >>> Fluffy=pets('Fluffy',8)
3. >>> Fluffy
pets(name=’Fluffy’, age=8)
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)
1. >>> type(red.red)
<class ‘int’>
1. >>> red.blue=1
red.blue=1
1. >>> red._asdict()
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.
1. >>> Colors._make(['Purple','Violet','Gold'])
1. >>> Colors(**{'red':255,'green':0,'blue':0})
1. >>> red._fields
1. >>> red._replace(green=1)
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.
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
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}
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
1. >>> otherdict.keys()
1. >>> otherdict['d']
2. Traceback (most recent call last):
3. File "<pyshell#364>", line 1, in <module>
4. otherdict['d']
KeyError: ‘d’
To deal with this situation, we have defaultdict in Python. First, we must import it from Python collections
module.
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.
As we discussed, we first import defaultdict from the ‘collections’ module. Let us see this Python defaultdict
example.
Next, we define a python function to return a default value for the keys we don’t initialize.
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.
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.
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()
<class ‘NoneType’>
a[1]
print(1/0)
Python defaultdict supports all operations that a regular dictionary does. These include keys() and len().
1. >>> dir(a)
a. missing (key)
This Python method is called by the getitem () method of the dict class when the requested key isn’t
found.
It returned 0 here because that’s what we specified as a default value through a lambda expression to the
defaultdict() factory function.
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
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.
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
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.
1. >>> issubclass(OrderedDict,dict)
True
1. >>> d=OrderedDict()
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)])
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.
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)])
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.
1. >>> f.pop('e')
1. >>> f
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
Python Dictionary
Optionally, you can put the dictionary in a variable. If you want to use it later in the program, you must do this.
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’>
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.
1. >>> dict3={1:'carrots','two':[1,2,3]}
2. >>> dict3
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])
dict([1,2],[2,4],[3,6])
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.
1. >>> animals={}
2. >>> type(animals)
<class ‘dict’>
1. >>> animals[1]='dog'
2. >>> animals[2]='cat'
3. >>> animals[3]='ferret'
4. >>> animals
1. >>> dict3
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)
1. >>> mydict[48]
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.
1. >>> dict4={1:1,2:2,3:3}
1. >>> dict4[2]=4
2. >>> dict4
{1: 1, 2: 4, 3: 3}
1. >>> dict4[4]=6
2. >>> dict4
{1: 1, 2: 4, 3: 3, 4: 6}
dict4
1. >>> dict4={1:1,2:2,3:3,4:4}
{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.
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)
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.
1. >>> dict4={3:3,1:1,4:4}
1. >>> sorted(dict4)
[1, 3, 4]
Now, let’s try printing the dictionary dict4 again.
1. >>> dict4
{3: 3, 1: 1, 4: 4}
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’>
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()
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)
e. clear()
The clear function’s purpose is obvious. It empties the Python dictionary.
1. >>> dict4.clear()
2. >>> dict4
{}
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)
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)
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}
1. >>> newdict.popitem()
(9, 9)
Let’s restart the shell and reassign the dictionary again and see which pair is popped.
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}
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}
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.
1. >>> dict4
{1: 1, 3: 3, 4: 4}
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
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}
dict1={{1:2,2:4}:8,8:16}
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.
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.
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)
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
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
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.
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
c. date.resolution
resolution returns the smallest possible difference between non-equal date objects.
1. >>> datetime.date.resolution
datetime.timedelta(1)
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:
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()
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()
1. >>> d=datetime.date(2018,12,30)
2. >>> td=datetime.timedelta(0,99999)
3. >>> d1=d+td
4. >>> d1
1. >>> d1<d
False
Any doubt yet in Date time module in Python or Examples? Please comment.
1. >>> t=datetime.time(11,59,59,99999)
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
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
i. replace()
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 ()
1. >>> t. str ()
’22:59:07.099999′
Now in the Python Datetime Module Tutorial Lets move ahead with datetime Objects
1. >>> d=datetime.datetime(1995,12,31,10,0)
a. today()
This method returns the current local datetime.
1. >>> datetime.datetime.today()
b. now()
now() returns the current local date and time, but is more precise than today().
1. >>> datetime.datetime.now()
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())
e. utctimestamp()
This is like the previous one, but it returns the UTC time.
1. >>> datetime.datetime.utcfromtimestamp(time.time())
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
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
a. replace()
Again, this is like we have been doing so far.
1. >>> d.replace(microsecond=7)
b. date()
date() returns a date object from the datetime object.
1. >>> d.date()
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()
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()
j. utctimetuple()
This returns a time tuple of the UTC time.
1. >>> d.utctimetuple()
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()
1. >>> d=datetime.datetime(2018,12,30)
2. >>> td=datetime.timedelta(0,99999)
3. >>> d1=d+td
4. >>> d1
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)
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
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.
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
C:\Users\lifei>cd Desktop
C:\Users\lifei\Desktop>mkdir calc
C:\Users\lifei\Desktop>cd calc
C:\Users\lifei\Desktop\calc>echo >calc.py
C:\Users\lifei\Desktop\calc>
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).
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.
‘calc’
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’>
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.
2.25
1. >>> fd(9,4)
2
We can also import all from a module:
This will import all names other than those beginning with an underscore(_). However, we disparage this use, as
it makes for poorly readable 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:
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.
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. >>> dir(sys)
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()
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.
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.
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.
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.
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.
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)
€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.
1. >>> pickle.dumps(x)
b’\x80\x03K\x07.’
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’.
1. >>> pickle.load(f)
pickle.load(f)
1. >>> f.seek(0)
1. >>> pickle.load(f)
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())
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.
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.
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.
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’.
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.
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.
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.
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:
(If you’re working the interpreter, you may also do the following:
loadgame=Game.Sound.load
Now, if the Sound subpackage has a function volume_up(), we call it this way:
loadgame.volume_up(7)
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.
one.two.evenodd
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
1. def check():
2. a=int(input('Enter a number'))
3. if a%2==0: print("Even")
4. else: print("Odd")
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.
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.
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)
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
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:
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):
Sample usage:
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")
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)
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:
10. dup(fd)
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:
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 )
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):
Sample usage:
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:
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:
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:
fdopen() returns an open file object that is connected to the file descriptor.
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:
Sample usage:
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:
Sample usage:
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:
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. >>> 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:
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:
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 )
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:
Sample usage:
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:
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:
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:
Sample usage:
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:
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:
Sample usage:
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:
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:
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:
46. remove(path)
remove() removes the specified file path. If that path is a directory, it raises an OSError.
Sample usage:
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())}")
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:
Sample usage:
52. stat_float_times([newvalue])
stat_float_times() Python os Module decides whether stat_result denotes time stamps as float objects.
Sample usage:
53. statvfs(path)
Python os Module statvfs() executes a statvfs system call on the specified path.
The structure has the following members:
Sample usage:
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)
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:
59. tmpnam()
tmpnam() will return a unique path name reasonable enough to create a temporary file.
Sample usage:
61. unlink(path)
This Python os Module will remove specified file path. If it is a directory, it raises an OSError.
Sample usage:
Sample usage:
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!
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.
This constructs a PrettyPrinter instance for us. Let’s talk about its parameters:
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’])]
1. >>> pprint(data)
(2,
{‘e’: ‘E’,
‘f’: ‘F’,
‘g’: ‘G’,
‘h’: ‘H’,
‘i’: ‘I’,
‘j’: ‘J’,
‘k’: ‘K’,
‘l’: ‘L’}),
(4, [‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’]),
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.
1. >>> formatted=pformat(data)
DEBUG [(1, {‘a’: ‘A’, ‘b’: ‘B’, ‘c’: ‘C’, ‘d’: ‘D’}),
DEBUG (2,
DEBUG (4, [‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’]),
[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]
1. >>> pprint(colors)
45553504
1. >>> pprint(mylist)
[1, 2, ‘c’, ‘d’, <Recursion on list with id=45553504>] #The recursive reference
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)
(2,
{‘e’: ‘E’,
‘f’: ‘F’,
‘g’: ‘G’,
‘h’: ‘H’,
‘i’: ‘I’,
‘j’: ‘J’,
‘k’: ‘K’,
‘l’: ‘L’}),
(4, [‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’]),
Here, the ellipses denote the levels it excludes from the output.
1. >>> mylist=[1,2,'c','d']
2. >>> pprint(mylist)
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)
‘vcruntime140.dll’]
1. >>> pprintpp.pprint(data)
pp-ez
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.
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.
To do this, type the following in your Command Prompt (for Windows; type ‘cmd’ in search):
python –version
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:
You will see the following directory on your Desktop (or whichever directory you chose to work with):
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
(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.
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.
Collecting numpy
C:\Users\lifei\Desktop\workwithenv>
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:
In fact, to check what version of numpy you are using, you can type the following in the interpreter:
‘1.14.1’
Running the command to install numpy again will just be ignored by the interpreter.
c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-packages
c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-packages
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-
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-
c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-
c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-
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
C:\Users\lifei\Desktop\workwithenv>
d. Learning About a Python Package
To find out about a particular package, we use the subcommand ‘show’:
Name: numpy
Version: 1.14.1
Summary: NumPy: array processing for numbers, strings, records, and objects.
Home-page: http://www.numpy.org
Author-email: [email protected]
License: BSD
Location: c:\users\lifei\appdata\local\programs\python\python36-32\lib\site-packages
Requires:
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)
numpy (1.14.1)
pip (9.0.1)
setuptools (28.8.0)
virtualenv (15.1.0)
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!
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")
Enter a number7
Odd
1. >>>
Another example would be the constants ‘pi’ and ‘e’ from the ‘math’ module.
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. >>> pi
3.141592653589793
1. >>>
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 *:
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.
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
Loading 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’.
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)
import Game.Sound.load
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.
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.
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.
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.
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.
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}
d={[1,2,3],4}
1. >>> d={{1,3,2},4}
d={{1,3,2},4}
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. >>> 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:]
b[1:]
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()
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)
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()
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()
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]
numbers[3]
So, we use two methods for this purpose- add() and update(). We have seen the update() method on tuples, lists,
and strings.
1. add()
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.
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})
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'})
max({1,2,’three’,’Three’})
3. min()
Like the max() function, the min() function returns the item in the Python set with the lowest value.
1. >>> min(days)
‘Friday’
4. sum()
The sum() functionin Python set returns the arithmetic sum of all the items in a set.
1. >>> sum({1,2,3})
1. >>> sum(days)
sum(days)
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, 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.
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.
1. >>> set2.intersection(set1)
{3}
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.
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()
1. >>> set4=set1.copy()
2. >>> set1,set4
9. isdisjoint()
1. >>> {1,3,2}.isdisjoint({4,5,6})
True
1. >>> {1,3,2}.isdisjoint({3,4,5},{6,7,8})
{1,3,2}.isdisjoint({3,4,5},{6,7,8})
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
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.
True
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
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}
{{1,2}:3}
1. >>> {frozenset(1,2):3}
{frozenset(1,2):3}
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’>
1. >>> bool('Wisdom')
True
1. >>> bool([])
False
1. >>> bool(0)
False
1. >>> bool(0.000000000001)
True
A string has a Boolean value of True, but an empty string has False.
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. >>> False-True
-1
Division
1. >>> False/True
0.0
1. >>> True/False
True/False
This was an exception that raised. We will learn more about exception in a later lesson.
The same rules apply for modulus, exponentiation, and floor division as well.
1. >>> False%True
2. >>> True**False
1. >>> False**False
1. >>> 0//1
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
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 &
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 |
1. >>> False|True
True
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
1. >>> ~True
-2
1. >>> ~False
-1
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
True
1. >>> False is 0
False
5. Logical
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.
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.
1. >>> mylist=[]
2. >>> for i in 'anxiety':
3. mylist.append(i)
4. >>> mylist
But with a Python list comprehension, you can do this in one line:
Now that we’ve got your interest, we’ll dig a little deeper.
[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:
Note that not every loop has an equivalent list comprehension in Python.
[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, 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,