Learn Python Programming Quickly
Learn Python Programming Quickly
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 effort 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
Different 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
Different 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
Different Python Libraries
Conclusion
References
A FREE GIFT TO OUR READERS
http://www.chrisfordbooks.com/
INTRODUCTION
INTRODUCTION TO PYTHON
$ python3
If you are not welcomed by a license message, then Python
is not installed in your system. It will help if you use a
package manager such as Homebrew to install the latest
version of Python in macOS.
Terminal code :
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
different 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 difficult. 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 different 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 effectively.
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
Every programming language has its prebuilt syntax known
as reserved keywords usually needed to facilitate the
language. All these reserved keywords clearly define a
specific functionality while building the programming
language from scratch.
For example, "if" is a reserved keyword in Python and is
used to create a conditional statement while writing
Programs.
Programmers cannot use reserved keywords while creating
identifiers for other programming components such as
variables, functions, and classes. Python 3 currently has 33
reserved keywords.
Do it Yourself:
Open your Python terminal and enter the following
commands to list out all 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
difference 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 :
first = 10
Program code :
float age = 64;
Example :
a = 64
b = 54
c = a + b
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’
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 efficiently. 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
Program code :
Sample = [USA, China, Russia]
Sample[3]
Output :
Index Error: list index out of range
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
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
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]
> > > len(sample)
Output :
5
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 affect 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 different 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]
You can also sort string elements. The elements will be
ordered using alphabetical order.
Program code :
Sample = [USA, China, Russia, Japan, South
Korea]
Sample.sort()
Sample
Output :
[China, Japan, Russia, South Korea, USA]
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!
You can also use the input() function to print multi-line
strings as an input, as shown below.
Program code:
Prompt = “ This is a great way to know you “
Prompt += “ \n now say what is your age? "
Sample = input(prompt)
Print( “ \n You are “ + sample + “ years old”
)
Output:
This is a great way to know you
now say what is your age? : 25
You are 25 years old
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 different positional arguments. All these
positional arguments can be divided using a separator. You
can use these separators to create different 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 different 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 differs 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
Syntax:
Break
Syntax:
Continue
EXCEPTION HANDLING
Programming languages use exception handling to detect
the common errors and find a way to run the program
instead of getting crashed. Writing valid exceptions is an
essential skill for all the programmers involved in software
development. Exception handling also acts as a great tool
to detect both familiar and strange bugs during the testing
and maintenance stage of the project.
To handle errors, you need to be aware of try and except
statements that can help you to provide a reason for the
encountered error to the user.
Example:
Visit your Facebook page and try to insert an image with a
size of more than 64MB as your profile picture. After a few
minutes of loading, the website will pop you with an error
that says, “Image size is too large”.
Here, the Facebook programmers have created an
exception handling statement that displays a possible error
to the user when image size is exceeded.
Exception handling is also an excellent tool for
programmers to learn how a program responds to different
instances. Many web and mobile application libraries in
Python provide prebuilt exceptions to help programmers
quickly create bug-free applications.
Divide-by-Zero Error
When we divide a number by zero in mathematics, it cannot
be done and results in an undefined value. Even in
programming, it is impossible to define when a number is
divided by zero, and therefore all the core programming
languages provide divide-by-zero error for their users.
We can use this error type to understand exception
handling with try and except statements.
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
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:
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
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
Keyword Arguments is another famous way to pass
arguments to functions. It usually uses a key : value pair to
give arguments to functions. Keyword arguments are
mainly used to avoid confusion when passing arguments.
They also don’t have any order restrictions as the values
are directly linked. However, one major defect is that it
takes more time and sometimes can become complicated
when passing multiple values.
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
In the above example, using default values has simplified
function calls.
Remember that the Python interpreter will use a default
value only when an argument value is not provided during
the function call. If an argument value for the parameter is
provided, then the supplied argument will be used instead
of the default argument value.
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 different separators provided by Python or even use
custom separators from different 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:
Syntax:
Class example
Game = “ Football”
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 differences 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 efficiently extract information from
methods. Also, as a Python programmer, you should find
different 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 different attributes and functions that can
provide important information whenever there is a change
in the sides or when different 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 effectively.
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()
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’)
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
Using the sorted() Function
You can sort elements present in a dictionary in Python
using the sorted() method. While there are different ways,
such as using an items() method or dictionary
comprehension, the most popular way is to use it as an
Iterable argument.
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:
(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)
Program code:
Title = “ This is edited”
Sample.text((23,43), title , (232,342,212) ,
font = result)
The above function uses four arguments to render the
image and place the text provided on the screen.
In the above command, the first argument mentions the
coordinate position of the text. The second argument
mentions the text. The third argument uses RGB mode to
define what color the text should use. The final argument
provides the font style that needs to be used.
Example:
Import re
Sample = “ This is an example” _ regex =
re.compile(sample)
Result = regex.search(“ This is an example”)
Terminal command:
import json
Program code:
json.load(file object)
Program code:
json.loads(content)
# This reads all json functions
Apart from making it easy for communicating with the
server, JSON also provides an easy way to write metadata
that is often required for python web programs. You can
use the json.write() function to add new JSON data to a
module or application.
Program code:
Sample = iter(‘x’,’y’,’z’)
Output:
X
Y
Z
JUPYTER NOTEBOOK
Python has high adaptability to data science projects due to
many third-party libraries that can help data scientists
manipulate data in any way possible.
A notebook is a software tool developed for programmers,
which can provide an output related to visualizations,
media, and equations all in one place. Notebooks help
programmers to manage their data effectively. A data
scientist can use a Jupyter notebook to make the data
science model more engaging and understandable. Because
it is an open-source project, there are many integrations
available from the community.
How to Use a Jupyter Notebook
To be aware of Jupyter, you should have sound knowledge
about Python and Pandas. To install Jupyter in your
machine, you can use the pip package manager.
Program code:
pip3 install Jupyter
UNIT TESTING
Whenever programmers write code, they need to ensure
that the code quality is on par with Python’s guidelines.
Even if it works, complex and messy code can create bugs
down the road and may cause bottleneck situations.
Usually, when a programmer completes software, he needs
to conduct test case execution. During this phase,
programmers should analyze all log tests and reports to be
aware of all potential warnings that may occur.
Normally, programmers need to write manual testing code
to verify the authenticity and maintainability of their code.
However, manual testing is a humongous task and can
sometimes even take more time than the development
phase. Python provides a unit test framework known as
“unittest” to test the code automatically to make
programmers' lives easier.
How Unit Tests Take Place
To conduct a unit test of your code, you must first decide
how to address your testing procedure. For example, you
can test an entire module at once, or you can conduct
testing exclusively on a single function. However, it is
recommended to start testing with small code and expand
further.
What functions does the unit test offer?
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 different mapping technologies to interact
effectively. 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 different 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 different 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 effectively 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 different 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
efficiently. Many also use Matplotlib as a reference tool for
unit testing different 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 different 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, tiff,
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 different 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
different 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
offers 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 different 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 different 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 different layers.
16. Bokeh
Bokeh is one of the popular Python libraries extensively
used by data analysts to create visualisation data with
several effects. 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 different
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 different
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 different 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 differentiable 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