PYTHON Unit 1
PYTHON Unit 1
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
It is used for:
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it
is written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a functional way.
o Speed
o Code
o Trends
o Salary
Compilation Java is both compiled and interpreted Python is an interpreted language, i.e., it is
process language. The source code is first compiled and executed simultaneously line
compiled and converted to bytecode, by line.
and afterward, it depends on JIM
whether the bytecode will be collected
or interpreted
Length of The length of the code of java programs Python has shorter lines of code as you
code is more as compared to that of Python directly write the code and it gets
as every program has to be written in a interpreted.
class. For Eg- to write hello world
program, the code is- For eg-
public class HelloWorld {
public static void main(String[] args) { print('Hello, world!')
System.out.println("Hello, World");
}
}
Complexity Java is a statically typed programming Python is dynamically typed and there are
of syntax language. There are hardcore rules for no hardcore rules for semi-colon and braces.
braces and semi-colon. It works on inundation.
Ease of Strongly typed, need to define exact Dynamically typed, no need to define the
typing types of variables. exact type of variables.
Usage It has been in trend for a long time and Data science and machine language are
is vastly used in Android application made very simple, using Python. Also, it is
development, embedded systems, and being used for web development.
web applications.
Salary The java pay for beginners is less as Python developers are less as compared to
trends compared to python beginners, but the Java developers that are why are being paid
trend is changing and python more. Also, the technicality in the work of
developers are taking that spot. python developers is more; that is why they
are being paid more.
Python Comments
Comments can be used to explain Python code.
Creating a Comment
Comments starts with a #, and Python will ignore them:
Multiline Comments
Python does not really have a syntax for multiline comments.
Since Python will ignore string literals that are not assigned to a variable, you can add a
multiline string (triple quotes) in your code, and place your comment inside it:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Variables
Variables are containers for storing data values.
Creating Variables
Python has no command for declaring a variable.
Example
x = 5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even change type after
they have been set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.
Example
x = 5
y = "John"
print(type(x))
print(type(y))
Case-Sensitive
Variable names are case-sensitive.
Example
This will create two variables:
a = 4
A = "Sally"
#A will not overwrite a
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume). Rules for Python variables:
Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"
Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"
Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"
x = y = z = "Orange"
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values
into variables. This is called unpacking.
Unpack a list:
Python Classes/Objects
Python is an object oriented programming language.
Create a Class
To create a class, use the keyword class:
class MyClass:
x = 5
Create Object
Now we can use the class named MyClass to create objects:
Example
Create an object named p1, and print the value of x:
p1 = MyClass()
print(p1.x)
Standard data types
A variable can contain a variety of values. On the other hand, a person's id must be stored as an integer,
while their name must be stored as a string.
The storage method for each of the standard data types that Python provides is specified by Python. The
following is a list of the Python-defined data types.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
The data types will be briefly discussed in this tutorial section. We will talk about every single one of them
exhaustively later in this instructional exercise.
Numbers
Numeric values are stored in numbers. The whole number, float, and complex qualities have a place with
a Python Numbers datatype. Python offers the type() function to determine a variable's data type. The
instance () capability is utilized to check whether an item has a place with a specific class.
When a number is assigned to a variable, Python generates Number objects. For instance,
1. a = 5
2. print("The type of a", type(a))
3.
4. b = 40.5
5. print("The type of b", type(b))
6.
7. c = 1+3j
8. print("The type of c", type(c))
9. print(" c is a complex number", isinstance(1+3j,complex))
Output:
o Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and so on. An integer can
be any length you want in Python. Its worth has a place with int.
o Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate to within 15 decimal
places.
o Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y signify the genuine and
non-existent parts separately. The complex numbers like 2.14j, 2.0 + 2.3j, etc.
Sequence Type
String
The sequence of characters in the quotation marks can be used to describe the string. A string can be
defined in Python using single, double, or triple quotes.
String dealing with Python is a direct undertaking since Python gives worked-in capabilities and
administrators to perform tasks in the string.
When dealing with strings, the operation "hello"+" python" returns "hello python," and the operator + is
used to combine two strings.
Because the operation "Python" *2 returns "Python," the operator * is referred to as a repetition operator.
Example - 1
Output:
string using double quotes
A multiline
string
Example - 2
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
List
Lists in Python are like arrays in C, but lists can contain data of different types. The things put away in the
rundown are isolated with a comma (,) and encased inside square sections [].
To gain access to the list's data, we can use slice [:] operators. Like how they worked with strings, the list
is handled by the concatenation operator (+) and the repetition operator (*).
Example:
Output:
Tuple
In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from various data
types. A parenthetical space () separates the tuple's components from one another.
Because we cannot alter the size or value of the items in a tuple, it is a read-only data structure.
Example:
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
Dictionary
A dictionary is a key-value pair set arranged in any order. It stores a specific value for each key, like an
associative array or a hash table. Value is any Python object, while the key can hold any primitive data
type.
The comma (,) and the curly braces are used to separate the items in the dictionary.
Output:
Boolean
True and False are the two default values for the Boolean type. These qualities are utilized to decide the
given assertion valid or misleading. The class book indicates this. False can be represented by the 0 or
the letter "F," while true can be represented by any value that is not zero.
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
The data type's unordered collection is Python Set. It is iterable, mutable(can change after creation), and
has remarkable components. The elements of a set have no set order; It might return the element's altered
sequence. Either a sequence of elements is passed through the curly braces and separated by a comma
to create the set or the built-in function set() is used to create the set. It can contain different kinds of
values.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Internal Types
o Code
o Frame
o Traceback
o Slice
o Ellipsis
o Xrange
We will briefly introduce these internal types here. The general application programmer would typically not
interact with these objects directly, but we include them here for completeness. Please refer to the source
code or Python internal and online documentation for more information.
In case you were wondering about exceptions, they are now implemented as classes. In older versions of
Python, exceptions were implemented as strings.
1. Code Objects
Code objects are executable pieces of Python source that are byte-compiled, usually as return values from
calling the compile() BIF. Such objects are appropriate for execution by either exec or by the eval() BIF.
All this will be discussed in greater detail in Chapter 14.
Code objects themselves do not contain any information regarding their execution environment, but they are
at the heart of every user-defined function, all of which do contain some execution context. (The actual byte-
compiled code as a code object is one attribute belonging to a function.) Along with the code object, a
function's attributes also consist of the administrative support that a function requires, including its name,
documentation string, default arguments, and global namespace.
2. Frame Objects
These are objects representing execution stack frames in Python. Frame objects contain all the information
the Python interpreter needs to know during a runtime execution environment. Some of its attributes include
a link to the previous stack frame, the code object (see above) that is being executed, dictionaries for the
local and global namespaces, and the current instruction. Each function call results in a new frame object,
and for each frame object, a C stack frame is created as well. One place where you can access a frame
object is in a traceback object (see the following section).
3. Traceback Objects
When you make an error in Python, an exception is raised. If exceptions are not caught or "handled," the
interpreter exits with some diagnostic information similar to the output shown below:
Traceback (innermost last): File "<stdin>", line N?, in ??? ErrorName: error
reason
The traceback object is just a data item that holds the stack trace information for an exception and is
created when an exception occurs. If a handler is provided for an exception, this handler is given access to
the traceback object.
4. Slice Objects
Slice objects are created using the Python extended slice syntax. This extended syntax allows for different
types of indexing. These various types of indexing include stride indexing, multi-dimensional indexing, and
indexing using the Ellipsis type. The syntax for multi-dimensional indexing
is sequence[start1 : end1, start2 : end2], or using the ellipsis, sequence [..., start1 : end1]. Slice
objects can also be generated by the slice() BIF.
Stride indexing for sequence types allows for a third slice element that allows for "step"-like access with a
syntax of sequence[starting_index : ending_index : stride].
Support for the stride element of the extended slice syntax have been in Python for a long time, but until 2.3
was only available via the C API or Jython (and previously JPython). Here is an example of stride indexing:
>>> foostr = 'abcde' >>> foostr[::-1] 'edcba' >>> foostr[::-2] 'eca' >>>
foolist = [123, 'xba', 342.23, 'abc'] >>> foolist[::-1] ['abc', 342.23, 'xba',
123]
5. Ellipsis Objects
Ellipsis objects are used in extended slice notations as demonstrated above. These objects are used to
represent the actual ellipses in the slice syntax (...). Like the Null object None, ellipsis objects also have a
single name, Ellipsis, and have a Boolean TRue value at all times.
6. XRange Objects
XRange objects are created by the BIF xrange(), a sibling of the range() BIF, and used when memory is
limited and when range() generates an unusually large data set. You can find out more
about range() and xrange() in Chapter 8.
For an interesting side adventure into Python types, we invite the reader to take a look at the types module
in the standard Python library.
Python Operators
Introduction:
In this article, we are discussing Python Operators. The operator is a symbol that performs a specific
operation between two operands, according to one definition. Operators serve as the foundation upon
which logic is constructed in a program in a particular programming language. In every programming
language, some operators perform several tasks. Same as other languages, Python also has some
operators, and these are given below -
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
o Arithmetic Operators
Arithmetic Operators
Arithmetic operators used between two operands for a particular operation. There are many arithmetic
operators. It includes the exponent (**) operator as well as the + (addition), - (subtraction), *
(multiplication), / (divide), % (reminder), and // (floor division) operators.
Operator Description
+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b = 20
- (Subtraction) It is used to subtract the second operand from the first operand. If the first operand is less
than the second operand, the value results negative. For example, if a = 20, b = 5 => a - b
= 15
/ (divide) It returns the quotient after dividing the first operand by the second operand. For example,
if a = 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For example, if a = 20, b = 4 => a * b =
(Multiplication) 80
% (reminder) It returns the reminder after dividing the first operand by the second operand. For example,
if a = 20, b = 10 => a%b = 0
** (Exponent) As it calculates the first operand's power to the second operand, it is an exponent operator.
// (Floor It provides the quotient's floor value, which is obtained by dividing the two operands.
division)
Comparison operator
Comparison operators mainly use for comparison purposes. Comparison operators compare the values
of the two operands and return a true or false Boolean value in accordance. The example of comparison
operators are ==, !=, <=, >=, >, <. In the below table, we explain the works of the operators.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= The condition is met if the first operand is smaller than or equal to the second operand.
>= The condition is met if the first operand is greater than or equal to the second operand.
> If the first operand is greater than the second operand, then the condition becomes true.
< If the first operand is less than the second operand, then the condition becomes true.
Assignment Operators
Using the assignment operators, the right expression's value is assigned to the left operand. There are
some examples of assignment operators like =, +=, -=, *=, %=, **=, //=. In the below table, we explain
the works of the operators.
Operator Description
+= By multiplying the value of the right operand by the value of the left operand, the left operand
receives a changed value. For example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and
therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand and assigns the
modified value back to left operand. For example, if a = 20, b = 10 => a- = b will be equal to a =
a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand and assigns the
modified value back to then the left operand. For example, if a = 10, b = 20 => a* = b will be equal
to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and assigns the reminder
back to the left operand. For example, if a = 20, b = 10 => a % = b will be equal to a = a % b and
therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1 to a.
Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. The examples of Bitwise
operators are bitwise OR (|), bitwise AND (&), bitwise XOR (^), negation (~), Left shift (<<), and Right shift
(>>).
Operator Description
& (binary and) A 1 is copied to the result if both bits in two operands at the same location are 1. If not, 0 is
copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will be 1.
^ (binary xor) If the two bits are different, the outcome bit will be 1, else it will be 0.
~ (negation) The operand's bits are calculated as their negations, so if one bit is 0, the next bit will be 1, and
vice versa.
<< (left shift) The number of bits in the right operand is multiplied by the leftward shift of the value of the
left operand.
>> (right The left operand is moved right by the number of bits present in the right operand.
shift)
Logical Operators
The assessment of expressions to make decisions typically uses logical operators. The examples of logical
operators are and, or, and not. In the case of logical AND, if the first one is 0, it does not depend upon
the second one. In the case of logical OR, if the first one is 1, it does not depend on the second one.
Python supports the following logical operators. In the below table, we explain the works of the logical
operators.
Operator Description
and The condition will also be true if the expression is true. If the two expressions a and b are the same, the
be true.
or The condition will be true if one of the phrases is true. If a and b are the two expressions, then an or b m
true and b is false.
not If an expression a is true, then not (a) will be false and vice versa.
Membership Operators
The membership of a value inside a Python data structure can be verified using Python membership
operators. The result is true if the value is in the data structure; otherwise, it returns false.
Operator Description
in If the first operand cannot be found in the second operand, it is evaluated to be true (list, tuple,
or dictionary).
not in If the first operand is not present in the second operand, the evaluation is true (list, tuple, or
dictionary).
Identity Operators
Operator Description
is If the references on both sides point to the same object, it is determined to be true.
is not If the references on both sides do not point at the same object, it is determined to be true.
Operator Precedence
The order in which the operators are examined is crucial to understand since it tells us which operator
needs to be considered first. Below is a list of the Python operators' precedence tables.
Operator Description
** Overall other operators employed in the expression, the exponent operator is given
precedence.
* / % // the division of the floor, the modules, the division, and the multiplication.
<= < > >= Comparison operators (less than, less than equal to, greater than, greater then equal to).
<> == != Equality operators.
Function Description
delattr() Deletes the specified attribute (property or method) from the specified
object
divmod() Returns the quotient and the remainder when argument1 is divided by
argument2
hasattr() Returns True if the specified object has the specified attribute
(property/method)
map() Returns the specified iterator with the specified function applied to each
item
Python Numbers
There are three numeric types in Python:
int
float
complex
Variables of numeric types are created when you assign a value to them:
x = 1 # int
y = 2.8 # float
z = 1j # complex
Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
Integers:
x = 1
y = 35656222554887711
z = -3255522
Float
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
Floats:
x = 1.10
y = 1.0
z = -35.59
Float can also be scientific numbers with an "e" to indicate the power of 10.
Floats:
x = 35e3
y = 12E4
z = -87.7e100
Complex
Complex numbers are written with a "j" as the imaginary part:
Complex:
x = 3+5j
y = 5j
z = -5j
Sequence Type
String
The sequence of characters in the quotation marks can be used to describe the string. A string can be
defined in Python using single, double, or triple quotes.
String dealing with Python is a direct undertaking since Python gives worked-in capabilities and
administrators to perform tasks in the string.
When dealing with strings, the operation "hello"+" python" returns "hello python," and the operator + is
used to combine two strings.
Because the operation "Python" *2 returns "Python," the operator * is referred to as a repetition operator.
List
Lists in Python are like arrays in C, but lists can contain data of different types. The things put away in the
rundown are isolated with a comma (,) and encased inside square sections [].
To gain access to the list's data, we can use slice [:] operators. Like how they worked with strings, the list
is handled by the concatenation operator (+) and the repetition operator (*).
Tuple
In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from various data
types. A parenthetical space () separates the tuple's components from one another.
Because we cannot alter the size or value of the items in a tuple, it is a read-only data structure.
String Operators
Operator Description
+ It is known as concatenation operator used to join the strings given either side of the
operator.
* It is known as repetition operator. It concatenates the multiple copies of the same string.
[:] It is known as range slice operator. It is used to access the characters from the specified
range.
not in It is also a membership operator and does the exact reverse of in. It returns true if a
particular substring is not present in the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases where we need to
print the actual meaning of escape characters such as "C://python". To define any string
as a raw string, the character r or R is followed by the string.
% It is used to perform string formatting. It makes use of the format specifiers used in C
programming like %d or %f to map their values in python. We will discuss how formatting
is done in python.
Method Description
center(width ,fillchar) It returns a space padded string with the original string centred
with equal number of left and right spaces.
decode(encoding = 'UTF8', errors = Decodes the string using codec registered for encoding.
'strict')
find(substring ,beginIndex, It returns the index value of the string where substring is found
endIndex) between begin index and end index.
isalnum() It returns true if the characters in the string are alphanumeric i.e.,
alphabets or numbers and there is at least 1 character.
Otherwise, it returns false.
isalpha() It returns true if all the characters are alphabets and there is at
least one character, otherwise False.
isdecimal() It returns true if all the characters of the string are decimals.
isdigit() It returns true if all the characters are digits and there is at least
one character, otherwise False.
istitle() It returns true if the string is titled properly and false otherwise.
A title string is the one in which the first character is upper-case
whereas the other characters are lower-case.
isupper() It returns true if all the characters of the string(if exists) is true
otherwise it returns false.
ljust(width[,fillchar]) It returns the space padded strings with the original string left
justified to the given width.
partition() It searches for the separator sep in S, and returns the part before
it, the separator itself, and the part after it. If the separator is not
found, return S and two empty strings.
rstrip() It removes all trailing whitespace of a string and can also be used
to remove particular character from trailing.
rsplit(sep=None, maxsplit = -1) It is same as split() but it processes the string from the backward
direction. It returns the list of words in the string. If Separator is
not specified then the string splits according to the white-space.
split(str,num=string.count(str)) Splits the string according to the delimiter str. The string splits
according to the space if the delimiter is not provided. It returns
the list of substring concatenated with the delimiter.
splitlines(num=string.count('\n')) It returns the list of strings at each line with newline removed.
startswith(str,beg=0,end=len(str)) It returns a Boolean value if the string starts with given str
between begin and end.
title() It is used to convert the string into the title-case i.e., The
string meEruT will be converted to Meerut.
translate(table,deletechars = '') It translates the string according to the translation table passed
in the function .
rpartition()
Output:
Example
Consider the following example to understand the real use of Python operators.
Output:
We can use the triple quotes to accomplish this problem but Python provides the escape sequence.
The backslash(/) symbol denotes the escape sequence. The backslash can be followed by a special
character and it interpreted differently. The single quotes inside the string must be escaped. We can apply
the same as in the double quotes.
Example -
Output:
2. \\ Backslash print("\\")
Output:
\
Stack Allocation
The Stack data structure is used to store the static memory. It is only needed inside the particular function
or method call. The function is added in program's call stack whenever we call it. Variable assignment
inside the function is temporarily stored in the function call stack; the function returns the value, and the
call stack moves to the text task. The compiler handles all these processes, so we don't need to worry
about it.
Call stack (stack data structure) holds the program's operational data such as subroutines or function call
in the order they are to be called. These functions are popped up from the stack when we called.
1. int *a;
2. p = new int;
As we know, everything in Python is an object means dynamic memory allocation inspires the Python memory
management. Python memory manager automatically vanishes when the object is no longer in use.
Heap Memory Allocation
Heap data structure is used for dynamic memory which is not related to naming counterparts. It is type
of memory that uses outside the program at the global space. One of the best advantages of heap
memory is to it freed up the memory space if the object is no longer in use or the node is deleted.
In the below example, we define how the function's variable store in the stack and a heap.
Basically, Python language is written in the English language. However, it is defined in the reference
manual that isn't useful by itself. So, we need an interpreter based code on the rule in the manual.
The benefit of the default implementation, it executes the Python code in the computer and it also
converts our Python code into instruction. So, we can say that Python's default implementation fulfills the
both requirements.
Note - Virtual Machines are not the physical computer, but they are instigated in the software.
The program that we write using Python language first converts into the computer-relatable
instructions bytecode. The virtual machine interprets this bytecode.
When we assign the new name or placed it in containers such as a dictionary or tuple, the reference count
increases its value. If we reassign the reference to an object, the reference counts decreases its value if. It
also decreases its value when the object's reference goes out of scope or an object is deleted.
As we know, Python uses the dynamic memory allocation which is managed by the Heap data structure.
Memory Heap holds the objects and other data structures that will be used in the program. Python
memory manager manages the allocation or de-allocation of the heap memory space through the API
functions.
1. a= 10
2. print(a)
3. del a
4. print(a)
Output:
10
Traceback (most recent call last):
File "", line 1, in
print(x)
NameError : name 'a' is not defined
As we can see in the above output, we assigned the value to object x and printed it. When we remove
the object x and try to access in further code, there will be an error that claims that the variable x is not
defined.
Hence, Python garbage collector works automatically and the programmers doesn't need to worry about
it, unlike C.
Example -
Suppose, there is two or more variable that contains the same value, so the Python virtual machine rather
creating another object of the same value in the private heap. It actually makes the second variable point
to that the originally existing value in the private heap.
This is highly beneficial to preserve the memory, which can be used by another variable.
1. x = 20
When we assign the value to the x. the integer object 10 is created in the Heap memory and its reference
is assigned to x.
1. x = 20
2. y = x
3. if id(x) == id(y):
4. print("The variables x and y are referring to the same object")
In the above code, we have assigned y = x, which means the y object will refer to the same object because
Python allocated the same object reference to new variable if the object is already exists with the same
value.
Example -
1. x = 20
2. y = x
3. x += 1
4. If id(x) == id(y):
5. print("x and y do not refer to the same object")
Output:
The variables x and y are not referring the same object because x is incremented by one, x creates the
new reference object and y still referring to 10.
The garbage collector comes into action if the threshold of the number of allocations minus the number
of de-allocation is exceeded.
We can modify the threshold value manually using the GC module. This module provides
the get_threshold() method to check the threshold value of a different generation of the garbage
collector. Let's understand the following example.
Example -
1. Import GC
2. print(GC.get_threshold())
Output:
In the above output, the threshold value 700 is for the first generation and other values for the second
and third generation.
The threshold value for trigger the garbage collector can be modified using the set_threshold() method.
By taking advantage of Python web frameworks (e.g. Flask and Django), Python can be manipulated in the
backend to build effective server-side web applications.
Although web frameworks are not required to construct a sustainable backbone for a web application, it’s rare
that existing open-source libraries wouldn’t be implemented in conjunction with server-side Python
development to speed up the app deployment process.
However, you should note that Python is not directly compiled and interpreted in the web browser.
Although projects such as pyjs can compile Python to JavaScript, Python developers typically interlace Python
and JavaScript to create both server and client-side applications.
In other words, Python is solely executed on the server-side while JavaScript is downloaded to the client-side of
the web browser and executed accordingly.
Although a mountainous number of Python web frameworks and micro-frameworks exist out there, Django,
Flask, and Pyramid take the cake.
Let’s briefly explore Django and Flask below with consideration for their distinct complexity levels and learning
curves.
Django
Established as an open-source Python framework, Django is notorious for building complex data-driven web
application instances.
The framework is packaged with a variety of templates, libraries, and application programming interfaces (APIs)
that allow for scalable web development projects.
It is the most popular large-scale framework, integrated onto leading websites, including Instagram, Pinterest,
Bitbucket, The Washington Times, and Nextdoor.
Flask
Although Flask is better characterized as a micro-framework for Python-driven web applications, it still leads
as an up and coming leader in concise, yet complex, data-driven web app programming.
As a micro-framework, it possesses built-in development servers and support for convenient unit testing.
Additionally, it is prominent as a Unicode-based Python micro-framework that supports RESTFUL request
dispatching.
Flask also has extensive documentation for programmers to get a head start.
Now you understand how each of these frameworks differs, you can better understand the following example
applications of these frameworks in action.
Since Flask has risen to prominence as a scalable, yet compact and efficient, mini-framework, an array of
machine learning applications have been deployed.
Some stand-out examples include computer vision algorithms that can predict gender and diabetic retinopathy
detection based on eye fundus photographs.
Now see what Django – the more complex of the two frameworks – can do for you.
The modern websites below have used Django, along with Sentry, to scalably deploy large-structured web
and mobile applications:
Disqus
Instagram
Spotify
Dropbox
The Washington Post
Mozilla
Pinterest
National Geographic
The Onion
National Aeronautics and Space Administration (NASA)
2. Console-Based Applications
Otherwise known as terminal applications, console-based applications are broadly defined as any Python-
associated app that runs inside the terminal.
In the grand scheme of casual Python development, console-based Python deployments have the following
advantages:
They’re much more fun and fulfilling to write than simple script-based applications.
Terminal apps enable you and involved users to play with complex code without ambiguous layers of
abstraction between you and the user.
You’ll learn about fundamental user interaction issues at a primitive level that doesn’t include wishy-
Command-line Python applications that consume the News API and return up-to-date world and
national events.
A simple terminal-based chatbot application built with ML/Tensorflow.
Data science might be the most salient Python implementation of them all.
By using already-integrated code dependencies, such as Pandas, NumPy, or Matplotlib, amateur and expert-
level Python programmers can seamlessly visualize and manually extract actionable insights from massive public
and private datasets – both off and on the cloud.
At a high level, developers can even synthesize data science manipulations with ML models to extract, visualize,
and predict features from unstructured data (e.g. imaging data, time-series stock market data, or house price
predictions).
What’s more, open-source Github repositories are filled to the brim with business-level Python applications such
as NLP-driven sentiment and toxic comment classification or future sales predictions.
Additionally, data science communities such as Kaggle provide that extra bit of inspiration for you to get started
on novel data science solutions to big corporate problems.
4. Desktop GUI Applications
Admittedly, Python isn’t fully optimized for deploying business-grade desktop GUIapplications, at least not
when you compare it to C and Java libraries.
However, developers can get started with official Python documentation and implement toolkits/frameworks
such as PyQT, Tkinter, Kivy, WxPython, and PyGUI to create lightweight user interfaces with full software
functionality in mind.
For example, this Github repository boasts 15 distinct PyQT-driven projects that use Python-driven UI and
backend components to create responsive and functional Python applications.
A preview of these applications include:
5. Software Development
As Python rises to new and unforeseen popularity, product/project development pipelines have gradually
adapted to Python’s set of frameworks and best practices.
Although software development with Python covers the technical trails of ML/Deep Learning, scripting, and
web/OS-level application development, Python’s most advantageous contribution to software development is
its ability to accommodate project ideation and development and advance applications from insecure to robust.
With Python, rising software developers can effectively fulfill the following development-focused goals:
Advancing Python applications from conception through full-stack execution and app deployment by
applications
Writing secure apps that blockade and deter cybercriminals from exploiting common open patches and
vulnerabilities.
Adopting best practices in code review and portfolio development with your Python applications
6. Business Applications
With modern business applications covering the spectrum of e-commerce, ERP, and much more, having a
scalable and open-source language is crucial.
Python allows businesses to develop scalable and fully functional applications right out of the box.
Platforms such as Tryton can be used by business analysts to develop and deploy Python applications.
The umbrella of business development in Python can encompass many tools including:
7. Image Processing
Python is a useful tool for image manipulation and analysis. With its open-source dependencies, which can
oftentimes be installed on your command line, you can extract and manipulate features with a mere 8-10 lines
of code.
Whether it’s research, education, or industry-level applications, these following Python libraries provide you
with convenient image analysis tools.
Scikit-image
NumPy
Scipy
PIL/Pillow
OpenCV-Python
SimpleCV
Mahotas
SimpleTK
Pgmagick
Pycario
8. Game Development
In addition to research and business applications, Python has a critical role in backend game development with
logic and mods.
Perhaps the most memorable Python applications in game development include the following:
Civilization IV
Battlefield 2
Sims 4
Toontown Online
World of Tanks
EVE Online
Frets on Fire
Additionally, by using open-source game development libraries such as pygame, programmers can build simple
games such as a Dungeon Game and Guessing Game.
9. Web Scraping Applications
By using prebuilt Python libraries such as Beautiful Soup, developers with minimal hands-on Python experience
can extract specific, purposeful data from virtually any webpage.
At a higher level, Python web scraping libraries can be combined with NLP models to effectively scrape the
surface web for textual and visual information associated with specific words, intentions, or emotions.
Examples include:
In nearly every corporate and research-focused department, massive machine learning/deep learning models
and architectures are beginning to be used to solve big data problems.
Whether it’s an ML algorithm that can generate new cancer drugs or a model that detects dangerous highway
activity for an autonomous car, ML is bound to revolutionize every industry sector.
In short, machine learning can be divided into visual and non-visual tasks that are supervised, semi-supervised,
or unsupervised. Examples of business and research-level ML python applications include:
ML frameworks such as Tensorflow/Keras/Pytorch can be used to develop and deploy predictive and generative
models.