Chris Ford - Learn Python Programming Quickly (2021)
Chris Ford - Learn Python Programming Quickly (2021)
Chris Ford - Learn Python Programming Quickly (2021)
QUICKLY
CHRIS FORD
© Copyright Chris Ford 2021 - All rights reserved.
The content contained within this book may not be reproduced, duplicated or
transmitted without direct written permission from the author or the publisher.
Under no circumstances will any blame or legal responsibility be held against the
publisher, or author, for any damages, reparation, or monetary loss due to the
information contained within this book, either directly or indirectly.
Legal Notice:
This book is copyright protected. It is only for personal use. You cannot amend,
distribute, sell, use, quote or paraphrase any part, or the content within this
book, without the consent of the author or publisher.
Disclaimer Notice:
Please note the information contained within this document is for educational
and entertainment purposes only. All e ort has been executed to present
accurate, up to date, reliable, complete information. No warranties of any kind
are declared or implied. Readers acknowledge that the author is not engaged in
the rendering of legal, financial, medical or professional advice. The content
within this book has been derived from various sources. Please consult a licensed
professional before attempting any techniques outlined in this book.
By reading this document, the reader agrees that under no circumstances is the
author responsible for any losses, direct or indirect, that are incurred as a result
of the use of the information contained within this document, including, but not
limited to, errors, omissions, or inaccuracies.
CONTENTS
Introduction
1. Introduction to Python
The Benefits of Learning Python
Di erent Versions of Python
How to Install Python to Get Started
2. Basics of Python
Python Interpreter
IDE (Integrated Development Environment)
Pycharm
Working with Pycharm
Python Style Guide
Python Comments
3. Variables
Understanding Variables
How to Name Variables
How to Define Variables
How to Find the Memory Address of the Variables
Local and Global Variables in Python
Reserved Keywords
Operators in Python
Di erent Types of Operators
Operator Precedence
4. Data Types in Python
What Are Data Types?
Understanding Data Types
Type Casting
5. Lists and Tuples
What Is a List Data Type?
Understanding Tuples
Understanding Dictionaries
Sample Exercise
Exercise:
6. User Input and Output
Why Are Input Values Necessary?
Understanding input() Function
How to Write Clear Prompts for the User
Int() to Accept Numeric Input
Output
Sample Exercise
Exercises:
7. Conditional and Loops
Comparison Operators
What Are Control Flow Statements in Programs?
Programming Structures
If/else Conditional Statements
If Elif else
For loop
While loop
Break and Continue Statements
Exception Handling
Sample Exercise
Exercises:
8. Functions and Modules
What Are Functions?
Using Parameters in the Functions
Passing Arguments
Keyword Arguments
Default Values in Python
Understanding Scope in Python
Understanding the ‘Global’ Statement
How to Import Modules
How to Create Modules
Built-in Function and Modules
String Methods
Sample Exercise
Sample Exercise
Exercise:
9. Fundamentals of Classes
What Are Classes and Objects?
Exercises:
What Are Class and Instance Variables?
What Are Class and Static Methods?
10. Python Inheritance
Method Overriding in Python
Special Methods in Python ( _repr_ and _str_)
11. Files in Python
Understanding Files and File Paths
Exercise:
12. Advanced Programming
Python Recursion
Python Lambda Function
Advanced Dictionary Functions
Threading
Pip Package Manager
Virtual Environment
Using Pillow Library to Edit Images
Mastering Python Regular Expressions (Regex)
Understanding JSON Data
Understanding Sys Module
Iterators and Generators
Jupyter Notebook
Unit Testing
GitHub for Python programmers
Di erent Python Libraries
Conclusion
References
A FREE GIFT TO OUR READERS
http://www.chrisfordbooks.com/
INTRODUCTION
INTRODUCTION TO PYTHON
$ python3
$ python3
Python on Windows
Windows is the popular operating system in the world that
Microsoft developed. Windows systems are not available as
default software in Windows, and hence you need to install
an executable package to start experimenting with Python
programs.
To install Python 3 in Windows, head over to Python.org and
click on the downloads tab, where you can find di erent
executable files according to your operating system.
Download the executable installer which automatically
installs Python according to your preferred location. After
installing the Python installer, make sure that you add
“path” in environment variables using a control panel to
avoid conflicts with any other programming language
interpreters present in the system.
You can confirm whether or not a Python interpreter is
installed in a Windows system using the below command.
Command prompt code :
BASICS OF PYTHON
T outilize
create software applications using Python, you need to
a development environment to perform high-level
programming tasks. This chapter is designed to help readers
understand the importance of a productive development
style that Python programmers should focus on.
PYTHON INTERPRETER
Terminal code :
$ python
The terminal will open a shell window, as shown below.
Output :
>>>
Some examples:
IDLE can be used to test Python code with any simple
arithmetic calculations and for printing statements.
Program code :
>>> print ( “ This is a sample text “ )
When you press enter, the IDLE will enter into REPL mode
and will print the given text on the screen, as shown below.
Output :
This is a sample text
In the above example, print() is a method in Python’s
standard library that programmers can use to output
strings in the terminal window.
Program code :
>>> 2 + 5
Output :
7
Note: Remember that once you start a fresh terminal, all the
ongoing code in the IDLE will destroy itself.
How to Open Python Files in IDLE
Python inbuilt text editor provides you three essential
features that are essential for a coding environment.
The above action will create a file with a .py extension. You
can easily rename it according to your requirements.
Step 4: Analyze the interface in Pycharm
Terminal code :
$ import this
Here are the critical five styling principles that Python
programmers need to be aware of.
1. Beautiful is better than ugly
All Python programmers are suggested to write beautiful
semantically code instead of code that is hard to read and
understand. Here ugly refers to code that is not clean and
unreadable. Remove unnecessary statements or conditionals
that can complicate the code. Use indentations for better
understanding the code according to the structure. Beautiful
code not only rewards you with good readability but also
helps to decrease the runtime required.
2. Explicit is better than implicit
Never try to hide the functionality of the code to make it
explicit unless required. Being verbose makes understanding
the programming logic di cult. This styling principle is also
mentioned to encourage Python programmers to write
open-source code that can be redistributed.
3. Simple is better than complex
Make sure that you write code that approaches the logic
more straightforwardly instead of being complex. If you can
solve a problem with ten conditional statements or with one
method, solve it with one. Make it as simple as possible.
4. Complex is better than complicated
It is not always possible to write simple code that can do
complex actions. To perform complex actions, strive to write
complex code instead of complicated code. Always write code
in a way that you can catch exceptions whenever something
unexpected happens. Exceptions can help you quickly debug
your code.
5. There should be only one way to do it
Python programmers are suggested to use only one
programming logic for a problem all around the project
instead of using three or four logics in di erent instances.
Maintain uniformity to let others easily understand your
program code. Uniformity provides flexibility which can lead
to easy and quick maintainability.
PYTHON COMMENTS
Program code :
# This is a comment, and we will print a
statement
Print (“We have learned about comments”)
Output :
We have learned about comments
Program code :
‘ ’ ’
This is a comment that can be used to write
sentences or paragraphs.
‘ ’ ’
Output :
We have just learned about multi-line comments
VARIABLES
T olanguage,
maximize the potential of Python as a programming
programmers need to start using variables and
operators in their programs. Variables and operators are
fundamental building blocks of programs that can help build
programming logic and create applications that can
manipulate memory e ectively.
Example :
2x + 3y
x = 3 and y = 4
Program code :
print (" This is an example ")
Output :
This is an example
What happens?
Program code :
first = " This is an example"
print(first)
Output :
This is an example
Program code :
first = " This is an example"
print(first)
first = " This is a second example"
print(first)
Output :
This is an example
This is a second example
Syntax format :
Variable name = " Variable value"
Example :
first = 2
# This is a variable with integer data type
second = " United States Of America."
# This a variable with String data type
Program code :
first = 324
id(first)
Output :
1x23238200
Program code :
first = 324
id(first)
first = 456
id(first)
Output :
1x23238200
1x23238200
RESERVED KEYWORDS
Program code :
>>> import keyword
# This statement helps to import a library
>>> keyword.kwlist
# All the reserved keywords will be displayed
OPERATORS IN PYTHON
Example :
2x + 3y = 7
Example :
>>> first = 45
>>> second = 78
>>> first + second
Output :
133
Program code :
A = 42
B = 33
C = A + B
# + is an addition operator
Print(c)
Output :
75
2. Subtraction
The subtraction operator is usually used to find the
di erence between two literal values or lists. ‘-’ is its
symbol.
Program code :
A = 42
B = 33
C = A - B
# - is a subtraction operator
Print(c)
Output :
9
3. Multiplication
Multiplication operator is usually used to find the product
between two literal values or lists. It is represented using the
‘*’ symbol.
Program code :
A = 42
B = 33
C = A * B
# - is a multiplication operator
Print(c)
Output :
1386
4. Division
The division operator is usually used to find the quotient
when two numbers of any data type are divided. Whenever
two numbers are divided, you will usually be given a
floating-point number as a result. The symbol for the
division operator is ‘/’.
Program code :
A = 42
B = 33
C = A \ B
# / is a division operator
Print(c)
Output :
1.272
5. Modulus
Using this special operator, you can find a number modulo
with another number. Mathematically we can call modulo
also as the remainder between two numbers. The symbol of
the modulus operator is ‘%’.
Program code :
A = 42
B = 33
C = A % B
# % is the modulus operator
Print(c)
Output :
9
6. Floor division
Floor division is a special arithmetic operator that provides
the nearest integer value as the quotient value instead of
providing a floating-point number. The symbol of the floor
division operator when writing Python programs is ‘//’.
Program code :
A = 42
B = 33
C = A // B
# // is a floor division operator
Print(c)
Output :
1
OPERATOR PRECEDENCE
When you create and work with mathematical expressions, it
is also important to know when and how to perform a
mathematical operation. For example, when there are
multiple operators in an expression, it is very important to
follow strict rules that exist to calculate them. If not, the
value may completely change.
Python programmers can follow operator precedence rules
to avoid these problems while creating software.
Rules:
Program code :
float age = 64;
Example :
a = 64
b = 54
c = a + b
Here a, b, and c act as variables and '+' and '=' are operators.
The value given to the variables is known as a literal and
represents a data type value. 64 and 54 are the literals in the
above example. A literal usually acts as a directive to insert a
specific value into a variable.
The popular data types in Python are integer, float, string,
and Boolean. Understanding data types in depth and the
operations possible on them is a mandatory prerequisite for
Python programmers.
Strings
Strings are data types that are used to represent text in
programs. Strings are usually enclosed in single quotes and
have a sequence of characters. When you use a string data
type, an 'str' object with a sequence of characters is created.
String data types are necessary because a computer reads
data in the form of binary. It is required to convert
characters using an encoding mechanism so that the
computer can understand and manipulate them according to
our instructions. ASCII and Unicode are some of the popular
encoding mechanisms programming languages use to read
text data.
Until Python 2, there was no way to interact with foreign
languages such as Chinese and Korean e ectively. Python 3,
however, has introduced a Unicode mechanism to deal with
data other than English.
How Are They Represented?
Program code :
a = ' This is a string.'
print(a)
Output :
This is a string.
Program code :
>>> print ( " %s is a great game" %
'football')
Output :
football is a great game
Program code :
>>> print ( " %s is the national sport of %s"
('Baseball', 'USA') )
Output :
Baseball is the national sport of USA
Program code :
>>> print ( " The exchange rate of USD to EUR
is : %5.2f" % (0.7546))
Output :
The exchange rate of USD to EUR is : 0.75
2. Format with .format() string
Python 3 has provided a special method known as .format()
to format strings instead of the traditional modulus (%)
operator. Python 2 also has recently adopted the .format()
method into its standard library.
Example :
>>> print ( “ Football is popular sport in
{}.” .format(' South America') )
Output :
Football is popular sport in South America
Using .format(), we can also format the
strings using indexed based positions.
Program code :
>>> print( ' {3} {2} {1} {0}' .format ( '
again' , 'great' , ' America' , ' Make') )
Output :
Make America great again
Apart from these two ways, you can also format strings in
Python using f-strings. Lambda expressions can be used in
this method and are used when there is a requirement for
advanced formatting scenarios.
While it is tempting to use the placeholder method as it is
easy to implement, we recommend using the .format()
method as it is considered the best practice by many Python
3 experts. The placeholder method usually takes a lot more
time to execute during runtime and is not a good solution,
especially for large projects.
String Manipulation Techniques
Strings are the most utilized data type in programs because
data instantiation usually happens through strings.
Understanding string manipulation techniques is a
prerequisite skill for Python programmers. Many data
scientists and data analysts solely depend on these
manipulation techniques to create rigorous machine
learning models.
The most important string manipulation technique Python
programmers need to be aware of is concatenating and
multiplying the strings.
1. Concatenate
Concatenate refers to joining strings together to make a new
string. To concatenate two strings, you can use the
arithmetic operator ‘+’. You can also separate the added
strings using white space for better readability.
Program code :
Sample = ‘ This is ‘ + ‘ ‘ + ‘ FIFA world cup’
Print( sample)
Output :
This is FIFA world cup
Program code :
Sample = ‘ welcome ‘ * 4
# This makes the string to multiply itself 4
times
Sample1 = ‘ To whoever you are ‘
Print( sample + sample1)
Output :
welcome welcome welcome welcome To whomever
you are
Example :
Sample = ‘ This is a great’
Sample += ‘example’
Print(sample)
Output :
This is a great example
Program code :
Sample = ‘ Today is Monday’
Print(len(sample)
Output :
13
5. Find
Finding a part of the substring in a large string is an
important task for many Python programmers. Python
provides an inbuilt find() function for this purpose. This
method will output the starting index position of the
substring.
Note:
Python programmers can use only positive indexes, and also
the index starts with 0.
Example :
Sample = ‘ This month is August’
Result = sample. Find(“ Augu”)
Print(result)
Output :
12
Program code :
Sample = ‘ This month is August’
Result = sample. Find(“ July”)
Print(result)
Output :
-1
Program code :
Sample = “ Football is a great sport”
Result = sample. Lower()
Print(result)
Output :
football is a great sport
In the above example, if you notice, you can find that all the
uppercase letters are converted into lowercase.
You can perform a similar operation with the help of the
.upper() method, but to convert all the characters in a string
to upper case letters.
Program code :
Sample = “ Football is a great sport”
Result = sample. Higher()
Print(result)
Output :
FOOTBALL IS A HIGHER SPORT
7. title()
A Python programmer can also easily use the title() method
to convert a string to camel case format.
Program code :
Sample = “ Football is a great sport”
Result = sample. Title()
Print(result)
Output :
Football Is a Great Sport
8. Replace strings
A Python programmer often needs to replace a part of the
string. You can achieve this using the inbuilt replace ()
method. However, remember that all the characters in the
string will be replaced whenever you use this method.
Program code :
Sample = “ Football is a great sport”
Result = sample.replace( “ Football”, “
Cricket”)
Print(result)
Output :
Cricket is a great sport
Representing Integers
a = 6
print(a)
Output :
6
Program code :
A = 7.1213
Print(a)
# This represents a floating-point variable
Output :
7.1213
Example :
A = float.hex ( 3.1212)
Print(a)
Output :
'0x367274872489’
Example:
Print ( 100 < 32)
Output :
False
TYPE CASTING
Example:
X = 32
Print(type(x))
# This prints the data type of x
Y = 2.0
Print(type(y)
# This prints the data type of y
Z = x +y
Print(Z)
Print(type(Z))
# implicit type casting occurs
Output :
<class ‘int’>
<class ‘float’>
64.0
<class ‘float’>
X = 32
# This is an int variable with a value ‘32’
Z = float(x)
# Now the int data type is type casted to
float
Print(Z)
Print(type(Z))
Output :
32.0
<int ‘float’>
X = 32.0
# This is an int variable with a value ‘32’
Z = int(x)
# Now the float data type is type casted to
int
Print(Z)
Print(type(Z))
Output :
32
<class ‘int’>
X = 32
# This is an int variable with a value ‘32’
Z = str(x)
# Now the int data type is type casted to
float
Print(Z)
Print(type(Z))
Output :
32
<int ‘string’>
X = 32
# This is a string variable with a value ‘32’
Z = int(x)
# Now the string data type is type casted to
int
Print(Z)
Print(type(Z))
Output :
32
<class ‘int’>
A sinstead
a programmer, you need to deal with a lot of data
of single linear data. Python uses data structures
such as lists, tuples, and dictionaries to handle more data
e ciently. Understanding these data structures that help
Python programmers manipulate and easily modify the data
is an essential prerequisite for beginners.
Example :
[USA, China, Russia]
Here USA, China, and Russia are the elements
in the list. They are string data types.
List to variable:
>>> sample = [USA, China, Russia]
> > > sample
Output:
[USA, China, Russia]
Program code :
>>> sample = [ ]
# This is an empty list
Program code :
>>> sample = [USA, China, Russia]
>>> sample[0]
>>> USA
>>> Sample[1]
>>> China
>>> sample[2]
>>> Russia
Example :
>>> ' Hi’ + sample2
Output:
Hi Russia
Program code :
>>> [USA, China, Russia] [1]
Output :
China
Note : You can only use integer data type for indexes. Usage
of floating-point data type can result in TypeError.
Program code :
>>> sample = [USA, China, Russia] [1.0]
Output :
TypeError: list index should not be float but
should be an integer
Remember that all the list elements can consist of other lists
in them. To be precise, all the parent lists can have child
lists.
Program code :
>>> sample = [[Football, Cricket, Baseball],
USA, China, Russia]
>>> sample[0]
Output :
[Football, Cricket, Baseball]
You can also use child list elements using the following
index format.
Program code :
>>> sample[0][2]
Output :
Baseball
In the above example, the interpreter has first used the first
list in the element and then later for the third element to
print it on the screen.
You can also call list elements using negative indices.
Usually, -1 refers to the last element and -2 to the last
before.
Program code :
sample = [USA, China, Russia]
Sample[-1]
# will print the last element
Output :
'Russia’
Syntax :
Listname index start : index end
Program code :
>>> sample = [USA, China, Russia, Japan, South
Korea]
>>> sample[0 : 2]
Output :
[USA, China, Russia]
Program code :
>>> sample[2 : 3]
Output :
[Russia, Japan]
You can also slice without entering the first or last index
number. For example, if the first index number is not
provided, the interpreter will start from the first element in
the list. In the same way, if the last index number is not
provided, then the interpreter will extend the slicing till the
last element.
Program code :
>>> sample = [USA, China, Russia, Japan, South
Korea]
>>> sample[ : 1]
Output :
[USA, China]
Program code :
>>> sample[2 :]
Output :
[Russia, Japan, South Korea]
If you don’t provide both values, then the whole list will be
given as an output.
Program code :
>>> sample [ : ]
Output :
[USA, China, Russia, Japan, South Korea]
Program code :
>>> sample = [ USA, China, Russia, Japan,
South Korea]
>>> sample[2] = sample[4]
Output :
[USA, China, Russia, Japan, Russia]
Program code :
[4,5,6] + [5,6,7]
[4,5,6,5,6,7]
List Replication
You can multiply two strings using the list replication
technique. To perform the replication technique, you need to
use the "* "operator.
Program code :
[4,5,6] * 3
Output :
[ 4,5,6,4,5,6,4,5,6]
You can also easily remove an element from a list using del
statements. However, remember that when you delete a
middle element, the value of indices will change
automatically, so your results may change. Confirm whether
or not it will a ect any other operation before proceeding
with the deletion.
Program code :
>>> sample = [USA, China, Russia, Japan, South
Korea]
>>> del sample[3]
>>> sample
Output :
[USA, China, Russia, South Korea]
Program code :
>>> 'China’ in [USA, China, Russia, Japan,
South Korea]
Output :
TRUE
Program code :
Sample = [USA, China, Russia, Japan, South
Korea]
'Mexico’ not in sample
Output :
TRUE
Example :
Sample = [USA, China, Russia, Japan, South
Korea]
Result1 = sample[0]
Result2 = sample[2]
Result3 = sample[1]
Program code:
Result1,result2,result3 = sample
However, remember that you can only use this with the exact
elements you have on your list. Otherwise, a type error will
occur and will crash the program.
Finding Value In a List Using The index() Method
Python also provides various inbuilt functions that help
programmers to extract di erent additional data from these
data structures.
Program code :
Sample = [USA, China, Russia, Japan, South
Korea]
Sample.index(‘Japan’)
Output :
3
Program code :
Sample = [USA, China, Russia, Japan, South
Korea]
Sample.index(‘Switzerland ’)
Output :
Type error : list element doesn’t exist
Example :
Sample = [USA, China, Russia, Japan, South
Korea]
Sample.insert(3, ‘Canada’)
Sample
Output :
[USA, China, Russia, Canada, Japan, South
Korea]
Program code :
Sample = [USA, China, Russia, Japan, South
Korea]
Sample.remove(‘Canada ’)
Sample
Output :
Value error : The list element doesn’t exist
Program code :
Sample = [3,5,1,9,4]
Sample.sort()
Output :
[1,3,45,9]
Program code :
Sample = [USA, China, Russia, Japan, South
Korea]
Sample.sort(reverse = True)
Sample
Output :
USA, South Korea, Russia, Japan, China
Program code :
Sample = USA, China, 3,4,5.4
sample.sort()
Sample
Output :
TypeError: These values cannot be compared
UNDERSTANDING TUPLE S
Program code:
Sample = (‘football’ , ‘baseball’ , ‘cricket’)
Print(sample)
# creating a tuples without a parenthesis
Output:
‘football’, ‘baseball’, ‘cricket’
Program code:
Sample = (‘football’ , ‘baseball’ , ‘cricket’)
Print(sample)
# creating a tuples with a parenthesis
Output:
(‘football’, ‘baseball’, ‘cricket’)
Concatenating Tuples
Just like lists, you can add or multiply tuple elements in
Python.
Program code:
Sample1 = (21,221,22112,32)
Sample2 = (‘element’, ‘addition’)
Print( sample1 + sample2)
# This concatenates two tuples
Output:
(21,221,22112,32,’element’,‘addition’)
Program code:
Sample1 = (21,221,22112,32)
Sample2 = (‘element’, ‘addition’)
Sample3 = (sample1,sample2)
Print(sample3)
Output:
( ( 21,221,2212,32), (‘element’, ‘addition’))
Program code:
Sample1 = (‘sport’, ‘games’) * 3
Print(sample1)
Output:
(‘Sport’,’ games’,’ sport’, ‘games’, ‘sport’,
‘ games’)
Program code:
Sample1 = (21,221,22112,32)
Sample1[2] = 321
Print(sample1)
Output:
TypeError: Tuple cannot have an assignment
statement
How to Perform Slicing in Tuples
To perform slicing, you need to enter the starting and ending
index of tuples divided by a colon (:).
Program code:
Sample1 = (21,221,22112,32,64)
Print(sample1[2 : 4])
Output:
(22112,32,64)
Program code:
Sample1 = (21,221,22112,32,64)
Del sample1
Syntax:
Dictionary = [key : value , key : value]
Example :
Sample = {1 : USA , 2 : China , 3 : Brazil , 4
: Argentina}
Print(Sample)
Output:
{1: USA, 2: China, 3: Brazil, 4: Argentina}
Program code:
{1 : USA , 2 : China , 3 : Brazil , 4 : { 1 :
Football , 2 : Cricket , 3 : Baseball } }
SAMPLE EXERCISE
Program code:
#These are sample numbers we have used
sample = [22,32,11,53,98]
# Using a for loop to solve the logic
for num in list1:
# Logic for detecting even numbers
if num % 2 == 0:
print(num, end = " ")
Output:
22,32,98
EXERCISE:
Example :
Sample = input ( “ Do you like football or
baseball more? “)
Print(sample)
When the above example is executed, the user will first see
an output as shown below.
Output:
Do you like football or baseball more? :
Football
Output:
Football
Program code:
Sample = input( “ What is your nationality? :
“ )
Print ( “ So you are from “ + sample +” ! “)
Output:
What is your nationality? France
So you are from France!
Usually, when you obtain input from the user using the
input() function, your input result will be stored in a string
variable. You can verify it using an example.
If your result is enclosed in a single quote, then it is a string
variable.
Storing values in strings is feasible only until you don’t need
it for any other further calculations.
Example :
Sample = input ( “ What is your age? “)
Output:
What is your age? 25
Program code:
>>> sample >= 32
It throws an error because a string cannot be in any way
compared to an integer.
To solve this problem, we can use an int() function that
helps the interpreter enter details into an integer value.
Program code:
Sample = input ( “ What is your age? “)
Output:
What is your age? 25
Program code:
>>> sample = int(sample)
> > > sample >= 32
OUTPUT
Program code:
print( “ This is how the print statement works
“ )
All the statement did is recognize the string in between
parentheses and display it on the screen. This is how a print
statement works usually. You can now learn about some of
the arguments that the print() function supports in Python.
1. String literals
Using string literals in Python, you can format the output
data on the screen. \n is the popular string literal that
Python programmers can use to create a new blank line.
You can use other string literals such as \t, \b to work on
other special instances to format the output data.
Program code:
Print ( " this is \n a great line " )
Output:
This is
a great line
2. End = “ “ Statement
Using this argument, you can add anything specified on the
end once a print() function is executed.
Program code:
Print ( “this is a great line”, end = “great”)
Output:
This is a great line great
2. Separator
The print() function can be used to output statements on the
screen using di erent positional arguments. All these
positional arguments can be divided using a separator. You
can use these separators to create di erent statements using
a single print() function.
Program code:
>>> Print( “ This is “ , “ Great”)
Output:
This is Great
SAMPLE EXERCISE
Program code:
list = []
x = int(input(" What is the list size? : "))
for i in range(0, x):
print("What is the location?", i, ":")
result = float(input())
list.append(item)
print("Result is ", result)
Output:
What is the list size? 5
2.3,5.5,6.4,7.78,3.23
Result is : 2.3,5.5,6.4,7.78,3.23
EXERCISES:
COMPARISON OPERATOR S
Program Code:
34 < 45
Output:
TRUE
Program Code:
45 < 34
Output:
FALSE
In the first example, the left value is lesser than the right
value and hence ‘TRUE’ Boolean value is displayed as an
output. However, the second example does not meet the
condition, and hence ‘FALSE’ Boolean value is displayed on
the terminal.
You can also compare int values with floating-point values
using a less than operator.
Program Code:
5.2 < 6
Output:
TRUE
Program Code:
'Python’ < ‘python’
Output:
TRUE
Program Code:
(3,5,7) < (3,5,7,9)
Output:
TRUE
Program Code:
(3,5,7) < (‘one’, 5,6)
Output:
Error: Cannot be compared
Program Code:
34 >45
Output:
FALSE
Program Code:
45 > 34
Output:
TRUE
In the first example, the left value is not greater than the
right value and the ‘FALSE’ Boolean value is displayed as an
output. However, the second example met the condition, and
the ‘TRUE’ Boolean value is displayed on the terminal.
Exercise:
Find out all di erent types of instances that we have tried for
less than operator on greater than operator on your own.
3. equal (== operator)
We use this operator when we want to check whether or not
two values are equal.
Program Code:
34 == 45
Output:
FALSE
Program Code:
23 == 23
Output:
TRUE
WHAT ARE CONTROL FLOW STATE M E N TS IN PR OGRAM S?
PROGRAMMING STRUCTURE S
Example :
A = 6
Print(a + “is a number” )
Output:
6 is a number
Syntax:
If Condition
Body Statement
Else
Body Statement
Program code:
Sample = 64
If sample % 4 == 0
Print ( “ This is divided by four “)
else :
Print ( “ This is not divided by four “)
Output:
This is divided by four
IF ELIF ELSE
Program code:
Sample = 64
If sample > 0 :
Print ( “ This is a positive real number “)
Elif sample == 0 :
Print( “ The number is zero “)
else :
Print ( “ This is a negative real number “)
Output:
This is a positive real number
FOR LOOP
The for loop usually goes through all the elements in the list
until it is said so.
Example:
Sample = [2,4,6,8,10]
Result = 0
For val in sample :
Result = result + val
Print ( “ The sum of the numbers is “, result)
Output:
The sum of the numbers is 30
In the above example, the for loop has executed all the
numbers in the list until the condition is satisfied.
WHILE LOOP
While loop di ers from for loop slightly. It can loop over any
piece of code again and again until the condition is satisfied.
The for loop is used when a programmer knows how many
times a loop is going to be done, whereas the while loop is
used when a programmer is not aware of the number of
times a loop can happen.
Syntax:
While condition
Body statements of while
Example:
Sample = 10
First = 0
Second = 1
While second <= sample
First = first + second
Second = second + 1
Print ( “ The sum of numbers is: ", first )
Output:
Enter n: 4
The sum of numbers is 10
You can interlink while and for loops with conditional
statements to create complex programming logic.
Syntax:
Break
Syntax:
Continue
EXCEPTION HANDLING
Program code:
Def division(value) :
Return 64 / value
Print( value(4) )
Print( value (0) )
Print ( value(16) )
Output:
16
ZeroDivisionError : Division by zero
In the above example, when we try to call a function with an
argument of 0, the program ends with a ZeroDivisionError.
So, we try to show this error and proceed further with the
program using try and except statements.
What Are Try and Except Statements?
Python programmers need to write the potential error block
that may occur while executing the program in the ‘try’
block and should provide a logical solution about what the
interpreter should do when it catches an exception in the
‘except’ block.
Program code:
Def division(value) :
Try :
Return 64 / value
Except ZeroDivisionError:
print ( “ A number cannot be divided by zero ”
)
Print( value(4) )
Print( value (0) )
Print ( value(16) )
Output:
16
Error: A number cannot be divided by zero
4
SAMPLE EXERCISE
Reverse a given integer number using loops.
program code:
value = 453
result = 0
print(" What is the number? ", value)
while value > 0:
reminder = value % 10
result = (result * 10) + reminder
value = value // 10
print("Reversed Number is ", result)
Output :
What is the number? 453
Reversed number is : 354
EXERCISES:
Make sure that you create Python code for all these exercises
on your own. Only refer to the internet after trying your best
and not being able to crack it.
Program code:
def welcome() :
“This displays a welcome message for the user”
Print ( “Hi! We give you a warm welcome to our
software” )
welcome()
Output:
Hi! We give you a warm welcome to our software
Explanation:
Program code:
def welcome(name) :
“ This displays a welcome message for the user
along with their name”
Print ( “ Hi, “ + name.title() + “ ! \n We
give you a warm welcome to our software” )
welcome(‘tom’)
welcome(‘grace’)
Output:
Hi, Tom! we give you a warm welcome to our
software
Hi, Grace! we give you a warm welcome to our
software
Explanation:
PASSING ARGUMENTS
1. Positional arguments
Program code:
def sports(country, number) :
'” This describes how many times a country has
won FIFA world cup ‘“
Print ( country + “ has won FIFA “ + number +
“ times”)
Sports(‘Brazil’ , 5)
Sports(‘ France’ ,4)
Output:
Brazil has won FIFA 5 times
France has won FIFA 4 times
In the above example, the arguments are provided at the end
of the program using the parameter.
In positional arguments, the change in order can become
messy or sometimes result in errors, as shown below.
Program code:
def sports(country, number) :
'” This describes how many times a country has
won FIFA world cup ‘“
Print ( country + “ has won FIFA “ + number +
“ times”)
Sports(5, Brazil)
Sports(4,France)
Output:
5 has won FIFA Brazil times
4 has won FIFA France times
KEYWORD ARGUMENTS
Program code:
def sports(country, number) :
'” This describes how many times a country has
won FIFA world cup ‘“
Print ( country + “ has won FIFA “ + number +
“ times”)
Sports(country = ‘ Brazil’, number = 5)
Sports(country = ‘ France’ ,number = 4)
Output:
Brazil has won FIFA 5 times
France has won FIFA 4 times
Program code:
def sports(country, number = 5) :
'” This describes how many times a country has
won FIFA world cup ‘“
Print ( country + “ has won FIFA “ + number +
“ times” )
Sports(‘Brazil’)
Sports (‘Argentina’)
Output:
Brazil has won FIFA 5 times
Argentina has won FIFA 5 times
Program code:
def sports(country, number = 5) :
'” This describes how many times a country has
won FIFA world cup ‘“
Print( country + “ has won FIFA “ + number + “
times” )
Sports(‘Brazil’)
Sports (‘Argentina’, 4)
Output:
Brazil has won FIFA 5 times
Argentina has won FIFA 4 times
Program code:
def vegetable() :
Brinjal = 32
Vegetable()
Print(eggs)
Output:
Traceback error
Program code:
def vegetable () :
Print(brinjal)
Brinjal = 32
Vegetable()
Print(brinjal)
Output:
32
32
Program code:
def vegetable() :
Brinjal = 32
Fruits()
Print(brinjal)
def fruit() :
Apple = 21
Brinjal = 42
Vegetable()
Output:
32
Both local and global variables can have the same name.
There won’t be a conflict while writing programs. For
example, a local and global variable named ‘sample’ can be
created without generating any errors. While it is acceptable
to use the same names for variables with a local and global
case, we recommend you not follow it as it may lead to
confusion.
Program code:
def vegetable() :
Global brinjal
brinjal = ‘ tasty’
Brinjal = ‘ global ’
Vegetable()
Print(brinjal)
Output:
Tasty
Syntax:
import (Module name)
Example:
import math
File - sample.py
Def addition(x,y) :
'’’ This is a definition that is created to
add any two numbers ‘’’
Z = x + y
Return Z
Program code:
>>> import sample
Program code:
>>> sample.addition(10,20)
Output:
30
Program code:
Print ( “ Hello world”)
2. abs()
abs() is a Python built-in function that returns the absolute
value for any integer data type. If the provided input is a
complex number, then it returns magnitude. In simple
terms, it will print the positive value of it if a negative value
is provided.
Program code:
C = -67
Print ( abs(c))
Output:
67
3. round()
round() is an inbuilt Python function that provides the
closest integer number for floating-point numbers.
Program code:
C = 12.3
D = 12.6
Print(round(c))
Print(round(d))
Output:
12
13
4. max()
max() is a built-in Python function that will output the
maximum number from the provided input values. max()
function can be performed using any data type, including
lists.
Program code:
A = 4
B = 8
C = 87
Result = max( a,b,c)
Print(result)
Output:
87
5. sorted()
sorted() is a built-in function that programmers can use to
sort out elements in ascending or descending order. Usually,
the sorted built-in function is applied on lists.
Program code:
A = (3,34,43,2,12,56,67)
B = sorted (a)
Print(b)
Output:
(2,3,12,34,43,56,67)
6. sum()
sum() is a particular built-in tuple function that adds all the
elements and provides a result to the user.
Program code:
A = ( 6,8,45,34,23)
Y = sum(a)
Print(y)
Output:
116
7. len()
Length is an inbuilt python function that will return the
length of the object. These are mainly used with lists and
tulles.
Program code:
A = ( 2,4,5)
B = len(A)
Print(B)
Output:
3
8. type()
Type is an inbuilt Python function that provides information
about the arguments and the data type they hold.
Program code:
A = 3.2323
Print(type(a))
Output:
<class ‘float’>
STRING METHODS
1. strip()
strip() is a built-in Python string function that returns a
result after deleting the arguments provided from the string.
Usually, it removes both leading and trailing characters.
Program code:
A = “ Hello world”
Print(a.strip(‘wo’)
Output:
Hell rld
2. replace()
replace() is a built-in Python string function that
programmers can use to replace a part of a string with
another. You can also mention how many times you want to
replace it as an optional parameter.
Program code:
Sample = “ This is a great way to be great”
Print(sample.replace(“great”, “ bad”)
Output:
This is a bad way to be bad
3. split()
You can use this built-in Python function to split a string
according to the separator provided. If no character is
provided, the Python interpreter will automatically use white
space in its place.
Program code:
sample = “ Hello world”
Print( sample.split(‘r’)
Output:
‘ Hello wo’ , ‘rld’
In the above example, the string is split at ‘r’ and is placed in
a list as output.
4. join()
The join() method is a unique string function that can help
you add a separator to the list or tuple elements. You can use
di erent separators provided by Python or even use custom
separators from di erent Python modules. You can only join
string elements in a list. You can’t join integers or floating-
point numbers in a list. You can also use an empty string
instead of a separator.
Program code:
Sample = [‘16’ , ‘32’ , ‘48’ , ‘64]
Result = “ -“
Result = result.join(sample)
Output:
16-32-48-64
SAMPLE EXERCISE
program code:
def sample(s):
d={"Upper":0, "Lower":0}
for c in s:
if c.isupper():
d[“Upper"]+=1
elif c.islower():
d["LOWER_CASE"]+=1
else:
pass
string_test('This is great')
Output:
Upper : 1 , Lower : 10
SAMPLE EXERCISE
program code:
class example:
def pow(self, first, second):
if first==0 or first==1 or second==1:
return first
if first==-1:
if second%2 ==0:
return 1
else:
return -1
if second==0:
return 1
if second<0:
return 1/self.pow(first,-second)
res = self.pow(first,second/2)
if second%2 ==0:
return
res*res
return res*res*first
print(py_solution().pow(2, -3));
Output:
-8
EXERCISE:
1. Create a Python program to randomly generate ten
numbers and that automatically finds the maximum
value in those ten numbers. Use the max() method to
solve this program.
2. Create a list and reverse all the elements in it and add
them consequently.
3. Write a Python program to input ten strings and
reverse each one of them.
4. Write a recursive function to find the factorial of 100
5. Create a 3-page essay using string manipulation
techniques. Represent all of them just like how you
represent them on paper. Use as many methods as you
can.
6. Write a Python program that provides rows related to
Pascal’s triangle.
7. Create a Python program that automatically extracts
an article from Wikipedia according to the input
provided.
8. Create a Python program that can create a color
scheme for all the RGB colors.
9
FUNDAMENTALS OF CLASSES
Class ClassName :
Example:
Class Cat:
Example:
Class Cat():
“ This is used to model a Cat.”
Def __init__(self, breed, age) :
“”“ Initialize breed and age attributes “””
self.breed = breed
self.age = age
Def meow(self) :
“”” This describes about a cat meowing “””
print(self.breed.title() + “ cats meow
loudly”)
Def purr(self)
“”“ This describes about a cat purring “””
print( self.breed.title() + “ cats purrs
loudly”)
Explanation:
First, we have created a class with the name Cat. There are
no attributes or parameters in the parentheses of the class
because this is a new class where we are starting everything
from scratch. Advanced classes may have many parameters
and attributes to solve complex problems that are required
for real-world applications.
Immediately after the class name, a docstring called ‘ This is
used to model a cat’ describes the necessity for this class. It
would be best if you practice writing docstrings more often
to help other programmers understand the details about
your class.
In the next step, we created an _init_ () method and defined
three arguments. This is a unique function that Python runs
automatically when an object instance is created from a
class. _init_ function is a mandatory Python function;
without it, the interpreter will reject the object initiation.
Similarly, we have created two other functions, ‘ meow’ and
‘ purr’, with arguments for each. In this example, these two
functions just print a statement. In real-world scenarios,
methods will perform higher-level functionalities.
You should have observed the ‘ self’ argument in all the
three methods in the above class. self is an automatic
function argument that needs to be entered for every method
in a class.
In a class, all the variables can be called using a dot operator
(.). For example, ‘ self.age’ is an example for calling a
variable using a dot operator.
EXERCISES:
1. Write a Python program that will import all the
essential classes in Pandas machine learning library.
2. Use a built-in module in Python to list out all the
built-in functions that Python supports. Create a
Python program to list out all these functions in a
table format.
3. Using object-oriented programming, create an OOP
model for a library management system. Introduce all
the modules that can be used and list out all the
arguments that need to be given.
4. Write a Python class of shapes to calculate the area of
any figure.
5. Write a class and create both global and instance class
variables.
6. Use Python classes to convert Roman numerical
standard to the decimal system
Static Method
A static method is a specific programming analysis that
python founders provide to help python programmers
understand the importance of static arguments common in
other high-level languages such as Swift and C.
Many objects present in the class are augmented and cannot
be ignored by the instance classes that are present. Not
everyone can use classes to decide what their modifying
function should be.
To understand the di erences between static and instance
classes, you need to know both static and instance method
constructors. All these constructors have parameters that
cannot change because they correlate with functions that are
not easy to create.
Many do not try to understand the essence of Parameters as
they are created to e ciently extract information from
methods. Also, as a Python programmer, you should find
di erent ways to make literals understand why it is essential
to use code that can both be changed and extracted using
data such as class methods. As a programmer, you also need
to be aware of statically supported methods that can interact
with standard modules of other Python software.
10
PYTHON INHERITANCE
Syntax:
Class parent class :
Body of parent class
class child class ( parent class) :
Body of child class
For example, let us suppose that a car is a parent class and
BMW is a child class, then the inheritance syntax will look as
shown below.
Inheritance syntax:
Class car
Print ( “ This is a car class”)
Class BMW(car) :
Print ( “ This is a BMW class”)
The BMW class now uses all the functions present in the Car
class without rewriting them again.
Syntax:
Class parent1 :
Body of parent 1
Class parent2 :
Body of parent 2
Class child( parent1, parent2) :
Body of child
Class shapes :
Def __init__( self, sidesprovided) :
Self.first = sidesprovided
Self.sides = [ 0 for result in
range(sidesprovided)]
Def firstside(self):
Self.sides = [ float(input( “ What side is
this?"+str(result+1)+" : "))
for result in range(self.first)]
def secondside(self):
for sample in range(self.result):
print( "Side",result+1,"is",self.sides
results)
This class has di erent attributes and functions that can
provide important information whenever there is a change in
the sides or when di erent sides are mentioned.
You can use the methods firstside() and secondside() to
display various detailed information about lengths using the
shapes class.
As we have a basic overview of important attributes required
for a shape class, we are now ready to start a child class
called ‘square’.
Program code:
Class square(shapes) :
def __init__(self):
Shapes.__init__(self,4)
# 4 because the square has 4 sides. We can use 3 sides if it is
a triangle and 5 if it is a Polygon
def docalc(self):
First, second,third = self.sides
Result = (first + second + third) / 2
area = (result *(result-first)*(result -
second)*(result-3)) ** 2
print( “The area of the square is %0.8f'
%docalc”)
Program code:
Sample = date. Determine()
Sample.__str__
()
Sample.__repr__
()
Output:
'2021-08-01 22:32:22.27237’
'Datetime.datetime(2021,08,22,32,22)
From the above example, we can understand that the
__str__ function provides a readable format, whereas
__repr__ function is an object code that programmers and
testers can use to reconstruct the object. Reconstitution of
objects can help programmers quickly debug the code and
store those logging instances e ectively.
If you are a unit tester, then using both of these functions is
extremely important to maintain the program.
11
FILES IN PYTHON
Example:
Os.path.join(‘C’, ‘ users’ , ‘ python’)
'C\users\python’
Example:
Os.getcwd()
'C:\\ windows \ program files \ python’
Example:
>>> import os
> >> os.makedirs( ‘ C :\ python\ software\
tutorials’)
Sample.txt:
' This is a sample file with a simple text.’
example.txt:
This is a paragraph
But with different lines
We use this example to determine
How Python detects different lines
And list out to us
>>> sample = open(‘ example.txt’)
> > > sample.readlines()
Output:
\[ ‘ This is a paragraph \n ‘, ‘ But with
different lines \n’, ‘ We use this example to
determine \n’, ‘ How python detects different
lines \n’, ‘ And list out to us \n’]
The above example lists all the lines in a list with a new line
character (\n).
Writing Content to Files With the write() Function
Python provides an option for programmers to write new
data into files using the write() function. It is pretty similar
to a print() function that writes output to the screen. The
interpreter will create a new object file whenever you open a
file using write() mode. You can change the content or
append text at the end of the file in this mode. To open the
file in write mode, you need to append ‘w’ as an argument to
the open() function.
Once you have completed writing the file, you can end it
using the close() method. When you use the close() method,
your file will be automatically saved by Python.
Program code:
Sample = open(‘ example,txt’, ‘w’)
# File now opens in write mode
Sample.write( ‘ This is about working in the
write mode \n’)
Program code:
Sample = open(‘ example.txt’, ‘a’)
# File now opens in write mode
Sample.write( ‘ We are now appending new
content to the file \n’)
# The above-written sentence will be added to
the file
Sample.close()
Now, once written, we need to make sure that the Python has
read the file to print it on the screen.
Program code:
Sample = open(‘ example.txt’)
Result = read(example.txt)
Print(result)
Output:
This is about working in the write mode
We are now appending new content to the file
In the above example, when we print the final result, the
written file content and the appended text are printed on the
computer screen.
Python also provides a shelve module to quickly interact
with data in the file and use them only when needed. To use
the shelve module, you need first to import it and once
imported, you can call them.
Copying Files and Folders
Using Python, you can use the built-in library known as the
shutil module to copy, move, rename, or delete your files.
However, like every other library, you need to import the
library first.
import shutil
Example:
Shutil.copy(‘ C;\\ python.txt’, ‘ C:\\python’)
This command will make Python create a new file with the
name ‘python2.txt’ and copy all the contents from the
python.txt.
Moving and Renaming Files and Folders
A Python programmer can use shutil.move() function to
move a file from one path to another. Remember that when
you move a file, it will be deleted from the current directory
entirely and sent to another location. This function uses two
parameters to complete the task.
Program code:
Shutil.move( ‘ C:\\ sample.txt’ , ‘ C;\\
python’)
Program code:
Shutil.move( ‘ C:\\ sample.txt’ , ‘ C;\\
python.txt’)
In the above example, we renamed the file name
from ‘sample.txt’ to ‘python.txt’
EXERCISE:
ADVANCED PROGRAMMING
PYTHON RECURSION
Example:
Sample = lambda result : result * 2 *
Print(sample(5))
Output:
10
Program code:
Movies = {American Pie : 7 , Schindlers list :
10 , Shashswank redemption : 9 , Avatar : 8}
Maximum = max( Movies, key = movies.get)
Print(Maximum)
Output:
Schindler's list
Program code:
Movies = {American Pie : 7 , Schindlers list :
10 , Shashswank redemption : 9 , Avatar : 8}
Minimum = min( Movies, key = movies.get)
Print(Minimum)
Output:
American pie
Program code:
Movies = {American Pie : 7 , Schindlers list :
10 , Shashswank redemption : 9 , Avatar : 8}
Print(sorted(Movies))
Output:
{American Pie : 7 , Avatar : 8 , Shashwank
redemption : 9 , Schindlers list : 10}
THREADING
instance.start()
Usually, when you end a program, all the threads will exit
automatically. Daemon threads, however, will not exit and
will run in the background. Any software that needs the
ability to track should use daemon threads not to close the
instance completely. Daemon threads utilize significantly
less memory power to make them operate for practical
implementation.
Some additional threading functions:
Terminal command:
$ pip — version
Terminal command:
$ pip install http3
Terminal command:
$ pip show http3
Terminal command:
$ pip uninstall http3
Terminal command:
$ pip search oauth
Terminal command:
$ pip install virtualenv
Terminal command:
$ virtualenv sample
Terminal command:
$ source sample/bin/activate
Terminal command:
(Sample)$ deactivate
Terminal command:
pip install pillow
Terminal command:
from PIL import Image
Program code:
Sample = Image.open(“example.jpg”)
Program code:
from PIL import ImageFont, ImageDraw
Program code:
Result = Imagefont.truetype(‘Helvetica.ttf’,
300)
Example:
Import re
Sample = “ This is an example” _ regex =
re.compile(sample)
Result = regex.search(“ This is an example”)
In the above example, we used the search() function and
regular expression to find a pattern in the string.
Terminal command:
import json
Program code:
json.load(file object)
Program code:
json.loads(content)
# This reads all json functions
Any process that uses the same logic while executing more
than one time is known as an iteration. For example, a loop
in a programming language like Python can be called an
iteration. If a for loop goes through six times, it can be said
to have iterated six times.
In Python, you can use the iter() function to create an
iterator object. You can also use the next() function to find
the next Iterable object.
Program code:
Sample = iter(‘x’,’y’,’z’)
Output:
X
Y
Z
JUPYTER NOTEBOOK
Program code:
pip3 install Jupyter
Once installed, you can open it and create your first Jupyter.
The software will welcome you with an interface that
provides details about your notebooks. Installing Anaconda
will also help you to change and modify these notebooks
easily.
To access your Jupyter notebook, you need to go to a browser
and enter the software's URL address. When the URL is
opened, Jupyter will start a Python server, and you will now
be ready to interact with it as you wish.
The software will save all the Jupyter notebooks in .ipynb
format. Many tools will help you to convert these files into
traditional docs or pdf formats automatically.
Understanding Cells in Jupyter Notebook
The body of the notebook in Jupyter will usually consist of
cells. The most important, however, is the code cell and
markdown cell.
1. Code cell
This contains all the Python code that needs to run
applications. This code can be converted using the kernel,
and an output will be displayed on the screen itself.
2. Markdown cell
This usually contains information about the code in
markdown format. Markdown cell usually will facilitate a
code cell. Also, remember that you can never create a
markdown cell first.
You can edit or write commands on a Jupyter notebook.
Understanding Markdown
Markdown is a special markup language that is created to
make formatting the text easy. Programmers can use it to
write both programs and normal text material.
Every markdown element has its own set of rules. For
example, # will create an H1 heading, whereas ## will create
an H2 heading.
UNIT TESTING
console code:
$ git config —global root “Project name”
console code:
$mkdir. (“Name of the Repository”)
You are now all set to experiment with your Python code and
create open-source projects.
Program code:
pip install requests
2. Scrapy
Web scraping is a popular way to extract data from websites
consistently and automatically. Scrappers also sometimes
can interact with APIS and act as a crawler. Scrapy is a
Python library that provides the ability to scrape the web
data for a Python web developer quickly.
Usually, web scrapers use ‘spiders’ to extract the data, and
as a Python library, Scrapy extends the ability to scrape
using advanced spiders. Scrapy also was inspired by Django;
it doesn’t repeat any code already present in the library. All
Python developers can use Scrapy shell to provide
assumptions about the behavior and performance of a site.
3. SQLAlchemy
The internet is filled with relational databases that save the
data and provide di erent mapping technologies to interact
e ectively. All websites and applications use SQL databases
more due to their data mapper technology.
SQLAlchemy is a Python library developed to act as an
object-relational mapper for software developed using
Python. SQLachemy also operates an active record pattern to
detect data mappers present in a database. Python
programmers can also install additional plugins to automate
the constant maintainability that comes with relational
databases.
4. NLTK
Natural language processing (NLP) is an artificial
intelligence technology that implements cognitive ideas in a
programmatic sense. NLTK (Natural Language Toolkit) is a
set of Python libraries that specialize in NLP technology.
They are primarily written in the English language and
provide various graphical demonstrations according to the
data provided.
At first, programmers developed this Python library to use it
as a teaching resource. However, its adaptability to domains
apart from NLP such as artificial intelligence and machine
learning had made it popular among data scientists. It
provides features such as lexical analysis and named entity
recognition.
5. Twisted
To write any internet-related software in Python, a
programmer should be aware of di erent networking
concepts and should find a way to support them so that
software can interact with them. A Python framework called
Twisted was developed to give programmers an alternative
to having to create networking protocols from scratch every
time.
It supports di erent network protocols such as TCP, UDP,
HTTP, and IMAP. It uses an event-driven programming
paradigm to create callbacks whenever the framework is
used. It provides advanced functions such as foreign loop
support, threading and deferreds. Twisted is the primary
networking library for many famous websites such as cloud
ki, Twitch, and Twilio.
6. NumPy
Python was created to develop desktop and web applications,
but not for numerical or scientific computing. However, in
1995 many scientists found that Python’s simplicity can help
it e ectively correlate with mathematical equations. Once
the implementation of arrays has been announced, Python
has started to get adopted to various scientific and numerical
libraries. NumPy supports the usage of high
multidimensional arrays, thus making it one of the
important python libraries for performing high-level
mathematical functions.
NumPy provides high debugging and binding features for
several other libraries, and hence it is often used with other
popular scientific and machine learning libraries while
writing Python software.
7. SciPy
In the last decade, Python has become the most used
programming language in scientific and technical
computing. Due to its open-source nature, many computer
scientists believe that using Python as the default language
while creating scientific and technical applications can make
them interact better as a community. SciPy provides modules
for di erent scientific domains such as optimization,
interpolation, and image processing.
SciPy also correlates with NumPy while working with high
multidimensional arrays that use mathematical functions.
SciPy’s impact on digital imaging and signal processing also
made it a favorable choice for technical computing.
8. Matplotlib
Matplotlib is used as a companion library for SciPy to plot all
the mathematical equations and high-level mathematical
functions using charts. While looking at the equations and
functions can develop your scientific and technical skills, a
chart can make you interact with data more clearly. Python
programmers use Matplotlib in their software so that the
end-user will understand the purpose of the software more
e ciently. Many also use Matplotlib as a reference tool for
unit testing di erent frameworks more easily.
Matplotlib uses GUI toolkits such as Tkinter to represent
plots beautifully. Additional functions such as GTK tools,
Excel tools, Basemap, and cartopy had made it a critical
Python library for programmers involved with technical and
scientific computing.
9. Pillow
Pillow is a Python library that programmers can use to
manipulate images. Pillow provides di erent modules that
can add additional image-enhancing capabilities to the
software. Pillow is an updated library for the already famous
Python Image Library (PIL). PIL is a legacy project and has
been discontinued from further development. To utilize the
functions that PIL comes with, enthusiastic developers have
forked down in Pillow's name to work with Python3. Forking
down refers to copying an old library into a new library with
added functionalities.
Pillow supports various image files such as jpeg, png, ti ,
and gif. With a pillow, you can crop, rotate, manipulate, or
edit images. Several hundreds of filters are also available for
Python programmers with a few clicks.
10. Beautiful Soup
Beautiful Soup is a Python scraping library that
programmers can use to customize how to parse both HTML
and XML pages. Beautiful Soup creates a detailed parse tree
after scraping and extracting content from these web pages.
It also uses a markup language to perform its parsing
operations. It is also known as a beautiful parser due to its
ability to scrape data without being messy while validating
and conforming information.
Beautiful Soup also works with all of the latest web
frameworks and technologies along with HTML 5 elements.
If you are a web developer who needs to create software that
interacts with web elements, there is no better Python
library than Beautiful Soup.
11. WxPython
WxPython is a Python wrapper to the cross-platform
popular GUI library wxWidgets. wxWidgets is written in C++
and provides many tools that can help programmers create
beautiful desktop applications. Enthusiastic Python
developers have created a wrapper to utilize the universal
functionalities provided by wxWidgets to build desktop and
mobile applications.
It has di erent modules for widget development. For
example, a button module can help you create buttons of
various kinds with a small code.
12. PyQT
PyQT is a Python extensible library that supports the popular
cross-platform GUI library Qt. It can be installed in Python
using a simple plugin. It provides modules that
programmers can use to develop Windows, Linux and macOS
applications. PyQT is also portable and can be used
instantaneously in any operating system.
It has a substantial set of various high-level GUI widgets,
along with an XML and SVG parser. It also provides di erent
modules for regular expressions, Unicode modelling, along
with DOM interfaces.
13. Pygame
Python also has high adaptability with mid-range gaming
technology. Pygame is a popular Python library that provides
various computer graphics and multimedia libraries that
programmers can use to write video games. It o ers multiple
modules to manipulate the gaming experience with the help
of sound, keyboard, mouse, and accelerometer.
Python programmers can also use Pygame to create games
that work with Android smartphones or tablets. It supports
the SDL library that helps programmers to create real-time
interactive games with few lines of code.
14. Pyglet
Pyglet is a Python library that programmers can use to
create advanced games and multimedia software. Pyglet is
highly portable and can help programs to run in all operating
systems without any lag. It extends multimedia software
capabilities by providing full-screen control, multiple
monitors, and di erent format types.
Pyglet also comes with an additional Avbin plugin that
supports various audio and video formats with perfection.
15. Nose2
Nose2 is a Python framework that can automatically detect
unit tests and execute them with a mouse click. While there
are many testing frameworks, Nose2 provides rich plugins
that can make the process swifter. Nose2 also provides better
API facilities that can be interlinked with selenium website
testing.
Using Nose2, you can also run di erent unit testing
processes simultaneously, making it a possible option for
projects with large code. Using Nose2, you can capture log
messages, cover test reports, and organize information with
di erent layers.
16. Bokeh
Bokeh is one of the popular Python libraries extensively used
by data analysts to create visualisation data with several
e ects. This Python library is exclusively developed for
building visualizations for modern web browsers such as
Safari and Opera. Bokeh not only supports high-level
interactive graphics but also can be used for creating
complex plotting graphs.
Many programmers use Bokeh and streaming datasets to
generate high-level graphic visualizations that make them
more attractive and intuitively beautiful. Bokeh has a high-
level relatability with Javascript technology.
17. Pandas
Pandas is a Python library that is primarily used for data
manipulation and can perform various analysis techniques.
It helps data scientists to import data sets from di erent
high-level formats such as JSON, SQL, and Excel so that
these analysts can perform operations such as merging, data
cleaning, and other high-level analysis features.
Pandas is also excellent in terms of aligning data to a
handler and performing hierarchical regeneration
techniques. Many programmers compare Pandas to C
language libraries due to their method implementation.
18. Scikit learn
Machine learning is one of the popular computer
technologies that is expanding its horizon to di erent
Python libraries. Sci-kit learn is one of the popular machine
learning libraries in Python that programmers can use to
create machine learning models. It also supports neural
network algorithms in dense situations.
Sci-kit learn has a remarkable correlation with numerical
and scientific libraries such as NumPy and Scipy. Random
forests, clustering, and K-tree are some of the famous
algorithms that Sci-kit learn consists of.
19. Keras
Neural networking is a computer science domain that
utilizes cognitive concepts in a programmatic sense. Keras is
an open-source Python library that uses Python to create
artificial neural networks, making complex real-world
applications.
It also supports linking to back-end software such as
TensorFlow and Microsoft cognitive toolkit. You need to be
aware of di erent GPU and TPU units to create software
using Keras as your primary framework carefully. Keras can
also be used as a preliminary framework for deep learning
projects.
20. Tensorflow
Tensorflow is a popular machine learning library that is used
to create deep neural networks. Tensor flow uses techniques
of di erentiable programming to create code that can co-
relate with data flow structures that exist on the Internet.
Tensorflow was first developed by Google and later was
adapted to be open source due to its popularity among
Google developers.
Leave a 1-Click Review