python activity
python activity
python activity
1)b. Identify various python IDEs and identify differences between them
There are some Python IDEs which are as follows:
o PyCharm
o Spyder
o PyDev
o Atom
o Wing
o Jupyter Notebook
o Thonny
o Rodeo
o Microsoft Visual Studio
o Eric
PyCharm
PyCharm was developed by the Jet Brains, and it is a cross-platform Integrated Development
Environment (IDE) specially designed for python. It is the most widely used IDE and
available in both paid version and free open-source as well. It saves ample time by taking
care of routine tasks.
Play Video
It is a complete python IDE that is loaded with a rich set of features like auto code
completion, quick project navigation, fast error checking and correction, remote development
support, database accessibility, etc.
Spyder
Spyder is an open-source that has high recognition in the IDE market and most suitable for
data science. The full name of Spyder is Scientific Python Development Environment. It
supports all the significant platforms Linux, Windows, and MacOS X.
It provides a set of features like localized code editor, document viewer, variable explorer,
integrated console, etc. and supports no. of scientific modules like NumPy, SciPy, etc.
PyDev
PyDev is defined as one of the commonly used Python IDE, which is an external plugin for
Eclipse. It is a natural choice of the Python developers that are coming from the Java
background and very popular in the market as Python interpreter.
Aleksandar Totic is famous for his contribution to Mosaic browser and worked on Pydev
project during 2003-2004.
Pydev has a feature which includes Django integration, automatic code completion, smart
indents and block indents, etc.
Atom
Wing
It is defined as a cross-platform IDE that is packed with necessary features and with decent
development support. Its personal edition is free of cost. The pro version comes with a 30
days trial for the developers to try it out.
Jupyter Notebook
Jupyter is one of the most used IPython notebook editors that is used across the Data Science
industry. It is a web application that is based on the server-client structure and allows you to
create and manipulate notebook documents. It makes the best use of the fact that python is an
interpreted language.
Eric Python
The Eric Python is an editor which is developed in Python itself and can be used for both
professional and non-professional work.
Rodeo
Rodeo is defined as one of the best IDE for python that is most widely used for data science
projects like taking data and information from different resources.
2)a. IDENTIFY USE CASES LIKE READING STUDENT NAME AND CONTACT
DETAILS AND DISPLAY IN A REQUIRED FORMAT
How To Identify Use Cases
This article will define a candidate use case and how to identify use cases.
It will identify the resources you can use as the source material to identify your use cases. It
will also explain what techniques you can apply to generate so input() and raw_input()
function.
Why we need input() and raw_input() function in python
The main reason is the user-friendly code which is interactive. It makes the code interactive
instead of hard coding. We use input() and raw_input() function to accept the user inputs
according to their own value.
Table of Contents
1.Candidate Use Case Definition
2.Candidate Use Case Context
3.Source Material for Identifying Candidate Use Cases
4.Techniques for Generating Source Material
5.How To Identify Use Cases
6.Verifying Candidate Use Cases
7.Conclusion
Candidate Use Case Definition
A candidate use case is nothing more than a first guess at a use case that is relevant in the
problem domain. It may ultimately remain or be rejected in consultation with the
stakeholder(s).
You’ll also need to identify the actors alongside the use cases.
Candidate Use Case Context
The business analyst may be identifying candidate use cases in a number of different
contexts:
Existing business process is being changed for some benefit (e.g. cost reduction);
Brand new system is being created in support of a new business or new business unit;
New business process to satisfy regulatory changes; New business process to exploit an
opportunity (e.g. provides an opportunity for profit);
Existing system is being replaced by new technology platform.
Use Case Diagram – Student Management System
The use case diagram are usually referred to as behavior diagram used to describe the actions
of all user in a system. All user describe in use case are actors and the functionality as action
of system.
The Use case diagram is a collection of diagram and text together that make action on goal of
a process.
Use case diagram for student information system project. In Student information system there
is a only one actor Admin can do all the activities to run the system.
Systems
Actors
Use cases
Association
Dependencies
Generalization
2)b.COMPARE AND CONTRAST INPUT () AND RAW INPUT ()
Difference between input() and raw_input() functions in Python
Developers often have a need to interact with users, either to get data or to provide some sort
of result. Most programs today use a dialog box as a way of asking the user to provide some
type of input. While Python provides us with two inbuilt functions to read the input from the
keyboard.
input ( prompt )
raw_input ( prompt )
input() function
Python input() function is used to take the values from the user. This function is called to tell
the program to stop and wait for the user to input the values. It is a built-in function. The
input() function is used in both the version of Python 2.x and Python 3.x. In Python 3.x, the
input function explicitly converts the input you give to type string. But Python 2.x input
function takes the value and type of the input you enter as it is without modifying the type.
#!/usr/bin/python
name=raw_input('Enter your name : ')
print ("Hi %s, Let us be friends!" % name);
Sample outputs:
#!/usr/bin/python
# Version 1
## Show menu ##
print (30 * '-')
print (" M A I N - M E N U")
print (30 * '-')
print ("1. Backup")
print ("2. User management")
print ("3. Reboot the server")
print (30 * '-')
2)c.Identify use of operators and develop algorithms to solve the same& compare and
contrast different types of operators
Arithmetic Operators
Comparison Operators
Comparison of Relational operators compares the values. It either
returns True or False according to the condition
.
Operator Description Syntax
Greater than: True if the left operand is greater than the right x>y
< Less than: True if the left operand is less than the right x<y
== Equal to: True if both operands are equal x == y
!= Not equal to – True if operands are not equal x != y
>= Greater than or equal to True if the left operand is greater than or equal x >= y
to the right
<= Less than or equal to True if the left operand is less than or equal to the x <= y
right
is x is the same as y x is y
is not x is not the same as y x is not
y
= is an assignment operator and == comparison operator.
Logical Operators
Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is
used to combine conditional statements.
Bitwise Operators
Bitwise operators act on bits and perform the bit-by-bit operations. These are used to
operate on binary numbers.
Assignment Operators
Assignment operators are used to assign values to the variables.
Identity Operatorsis and is not are the identity operators both are used to check if two
values are located on the same part of the memory. Two variables that are equal do
not imply that they are identical.
is True if the operands are identical
is not True if the operands are not identical
Activity 3
3)a. identify use cases that involve decision making and develop algorithms to solve the
same.
DECISION MAKING:
decision-making (also spelled decision making and decision making) is regarded as the
cognitive process resulting in the selection of a belief or a course of action among several
possible alternative options. It could be either rational or irrational. The decision-making
process is a reasoning process based on assumptions of values, preferences and beliefs of the
decision-maker.[1] Every decision-making process produces a final choice, which may or
may not prompt action.
In Python, the selection statements are also known as Decision control statements or
branching statements. The selection statement allows a program to test several conditions and
execute instructions based on which condition is true.
Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as
outcome. You need to determine which action to take and which statements to execute if
outcome is TRUE or FALSE otherwise.
Following is the general form of a typical decision making structure found in most of the
programming languages –
Python programming language assumes any non-zero and non-null values as TRUE, and if it
is either zero or null, then it is assumed as FALSE value.
Python programming language provides following types of decision making statements.
Click the following links to check their detail.
Decision Tree is one of the most powerful and popular algorithm. Decision-tree algorithm
falls under the category of supervised learning algorithms. It works for both continuous as
well as categorical output variables.
Data-set Description :
Title : Balance Scale Weight & Distance Database
Number of Instances : 625 (49 balanced, 288 left, 288 right)
Number of Attributes : 4 (numeric) + class name = 5
Attribute Information:
Class Name (Target variable): 3
L [balance scale tip to the left]
B [balance scale be balanced]
R [balance scale tip to the right]
Left-Weight: 5 (1, 2, 3, 4, 5)
Left-Distance: 5 (1, 2, 3, 4, 5)
Right-Weight: 5 (1, 2, 3, 4, 5)
Right-Distance: 5 (1, 2, 3, 4, 5)
Activity 4
4. a) Identify use cases that involve iteration and develop algorithms to solve the same
An algorithm is a process or set of rules which must be followed to complete a
particular task. This is basically the step-by-step procedure to complete any task. All the
tasks are followed a particular algorithm, from making a cup of tea to make high scalable
software. This is the way to divide a task into several parts. If we draw an algorithm to
complete a task then the task will be easier to complete.
The algorithm is used for,
• To develop a framework for instructing computers.
• Introduced notation of basic functions to perform basic tasks.
• For defining and describing a big problem in small parts, so that it is very easy to
execute.
Characteristics of Algorithm
1. An algorithm should be defined clearly.
2. An algorithm should produce at least one output.
3. An algorithm should have zero or more inputs.
4. An algorithm should be executed and finished in finite number of steps.
5. An algorithm should be basic and easy to perform.
6. Each step started with a specific indentation like, “Step-1”,
7. There must be “Start” as the first step and “End” as the last step of the algorithm.
Iteration in algorithms
An algorithm is a plan, a set of step-by-step instructions to solve a problem. There are three
basic building blocks (constructs) to use when designing algorithms:
• sequencing
• selection
• iteration
These building blocks help to describe solutions in a form ready for programming.
1. Start
2. Read values of x0 and e.
*Here x0 is the initial approximation
e is the absolute error or the desired degree of accuracy, also the stopping criteria*
3. Calculate x1 = g(x0)
4. If [x1 – x0] <= e, goto step 6.
*Here [ ] refers to the modulus sign*
5. Else, assign x0 = x1 and goto step 3.
6. Display x1 as the root.
7. Stop
When you are programming with loops, it helps to understand that there are only a few basic
formats that are used repeatedly. If you can master these variations and recognize when they
are needed, then programming will become much easier. All loops have a basic structure.
There will be a variable (at least one) that will control how many times the loop runs. It is
necessary to do the following to this variable in each loop that you write.
• Initialize the loop control variable. These statements will be in red in the following
examples. Initialization should occur before the loop starts.
• Test the loop control variable. These statements will be in blue in the following
examples. Testing is done within the parenthesis of the while statement.
• Update the loop control variable. These statements will be in green in the following
examples. Updating is done somewhere inside the loop, usually as the last statement
in the loop.
If you do not do all three of these steps in every loop that you write, then you will be writing
incorrect loops that will either never loop, or will loop forever. If you create a loop that runs
forever, press CTRL-C to stop your program.
Count Loops
These are loops that everyone seems to love. People love them so much that they try to use
them inappropriately. The only time to use a count loop is when the program can determine
ahead of time how many times the loop will repeat. This is not always possible. There are
generally two ways that the number of repetitions of a loop will be know ahead of time:
When designing a loop, the first question to ask is, "How many times will the loop repeat?"
Here are examples of count loops.
1. Always repeats the same number of times. Notice the use of a constant to control the
loop.
2. const int ListSize = 10;
3. int NumbersEntered = 0; //Initialize
4. int TotalEven = 0;
5. int Value;
6. while (NumbersEntered < ListSize) { //Test
7. cin >> Value;
8. if (Value % 2 == 0) { //Loop Process
9. TotalEven++;
10. }
11. NumbersEntered++; //Update
12. }
13. The program calculates the number of repetitions from user input.
14. int ListSize;
15. int NumbersEntered = 0; //Initialize
16. int TotalEven = 0;
17. int Value;
18. cout << "How many numbers will be entered? ";
19. cin >> ListSize;
20. while (NumbersEntered < ListSize) { //Test
21. cin >> Value;
22. if (Value % 2 == 0) { //Loop Process
23. TotalEven++;
24. }
25. NumbersEntered++; //Update
26. }
Sentinel Loops
Often, it will be necessary to write loops that repeat until a certain value is entered. These are
known as sentinel loops. Think of a sentinel as a red flag. The loop will continue until you
wave a red flag at it. The sentinel can be a single value or it can be an entire range of values.
Sentinel loops are more useful than count loops, since they allow for an undetermined
amount of repetitions. There are two common places for using a sentinel loop
1. Reading an unknown amount of input from the user. This is the most flexible way to
read data from the user. The program will be able to accept any amount of input from
the user.
2. Validating input. If it is necessary to verify that a user's input falls within a certain
range, then a sentinel loop is required. It is now known ahead of time how many times
the user will enter an invalid number. It is not enough to validate the first input from
the user. What if the user types another invalid input?
Sentinel loops still have three steps for the loop control variable: initialize, test and update.
However, with sentinel loops, the initialize and update staements look the same. This can be a
little confusing the first time it is seen, but if you remember that one statement is being used
to initialize the loop control variable and that the other is being used to update it, then it may
make a little more sense.
Notice that the sentinel loops can be used to test for good values, or to test for bad values. It
is important to remember the abstractions: initialize, test and update. Initialize before the
loop, test in the while statement parenthesis, update inside the loop (usually at the bottom).
Conditional Loops
Conditional loops have common traits with sentinel and count loops. They are like sentinel
loops in that it is unknow before time how may times they will repeat. They are like count
loops in that they terminate as the result of a calculation, instead of based upon user input. A
count loop uses a simple calculation to determine when the loop should end. Count loops can
use very complicated calculations.
As you can see from these loops, conditional loops combine qualities of both the sentinel and
the count loops. The exit from the loop depends on some initial input from the user and a
cacluation based upon that input.
There is a special sentinel loop that can be used with cin. There is a special character that
terminates all text files: CTRL-Z. Whenever C++ encounters this character when reading a
file, it terminates all input from that file. The cin stream is considered a text file. So it is
possible to use the CTRL-Z character to indicate to a program that no more input is available.
What makes this type of loop so appealing is that the initialization, test, and update are all in
the same place. The statement cin >> first returns a value of true if a valid input is entered. It
will return false if an invalid input, like CTRL-Z, is entered.
int Value;
int Count = 0;
cout << "Please enter number " << Count+1 << " (CTRL-Z to exit): ";
while (cin >> Value) { //Initialze, Test, Update
Count++;
cout << "Please enter number " << Count+1 << " (CTRL-Z to exit): ";
}
There is a problem with using the CTRL-Z character: once an invalid input is encountered, no
more valid input can be received. In the following example, after pressing CTRL-Z to end the
loop, the program will fail when trying to read the letter after the loop. The program will
always display the intial value of the letter ('A') to the screen.
int Value;
int Count = 0;
cout << "Please enter number " << Count+1 << " (CTRL-Z to exit): ";
while (cin >> Value) {
Count++;
cout << "Please enter number " << Count+1 << " (CTRL-Z to exit): ";
}
char Letter = 'A';
cout << "Enter a letter: ";
cin >> Letter;
cout << "You entered " << Letter << endl;
This can be remedied by resetting the state of the cin stream to a valid state. This is done with
the cin.clear() statement. Here is the same example again, but this time the program will wait
to read a letter from the user and will display it properly.
int Value;
int Count = 0;
cout << "Please enter number " << Count+1 << " (CTRL-Z to exit): ";
while (cin >> Value) {
Count++;
cout << "Please enter number " << Count+1 << " (CTRL-Z to exit): ";
}
cin.clear();
char Letter = 'A';
cout << "Enter a letter: ";
cin >> Letter;
cout << "You entered " << Letter << endl;
The compiler threw an error message as “prin not defined”. It’s not defined as a user-defined
or built-in keyword, therefore it confuses the compiler to where this word lies.
MISSING REQUIRED SPACES
Unlike other programming languages, python has the requirement for an indented block. That
is why many programmers have trouble wrapping this concept in the early stages.
Most languages might’ve executed this code (ignoring the terminators), but not python. The
print statement in line 3 should have a space of a tab.
MISSING QUOTES
When missing quotes in a string, the compiler confuses the purpose of the string and
doesn’t identify it. Note how the error is “name hi not defined”, even though it’s supposed to
be a string, not a variable. The compiler mistook it as a variable not defined and nowhere
guessed the possibility of a string.
Notice how the error changed to the literal error when a quote is added. The compiler
recognized it as a string and END OF LINE error is thrown.
The error is “invalid syntax”. Not very descriptive, that is why an if-else colon (:) is required
to fix this bug. It’s the same with while blocks.
MISSING ASSIGNMENT OPERATOR (=)
Notice that the compiler is not throwing an error to indicate that the assignment
operator is being misused. But it’s trying to compare the variable game to the string “me”,
finding undefined variable.
INVALID VARIABLES DECLARATION
There are many ways to violate the variable naming convention. You cannot use special
characters to expect underscore (_), or use a number at the beginning variable and many
others.
Here is another invalid way to declare a variable.
CONCLUSION
There are many syntax errors in python that are frustrating. Many errors are obvious and
easily eliminated while some errors are confusing. In this article, many common syntax errors
were discussed with explanations to the cause of their occurrence by performing some code
snippets.
Activity 5
5. IDENTIFY USE CASES AND SOLVE THEM USING SETS
Python Sets and Their Different Use Cases A Python
set is a collection of unordered data with no duplicate values. Like a list a set is also a
sequence of data. But unlike a list a set can’t have duplicate elements in it. Python sets are
same as mathematical sets and support operations of mathematical set theory like intersection
and union. But it is not required to be a pro in set theory to understand Python sets! In this
article we will see how to create a set and also some important use cases of sets
. Initializing a Set
To initialize a set we need to use set().
>>> my_set = set()
>>> my_set set()
>>> Here we have created an empty set named my_set.
Now let’s initialize another set with some values.
>>> s1 = {1, 2, 3, 4, 5}
>>> s1 {1, 2, 3, 4, 5}
Look how we created s1 with curly brackets. But when initializing an empty set we can’t use
curly brackets because it will create a dictionary
. >>> my_set
= {} >>> type(my_set)
We can also convert a list into a set.
>>> my_list = [1, 2, 3, 4, 5]
>>> s2 = set(my_list) >>>
s2 {1, 2, 3, 4, 5}
One important thing to notice here is if the list has duplicate values after converting it into a
set the duplicates will disappear.
>>> my_list = [1, 2, 3, 4, 5, 5, 5, 5, 5]
>>> s2 = set(my_list)
>>> s2 {1, 2, 3, 4, 5}
Add and Update We can use add()
to add one value to a set
. >>> s1 = {1, 2, 3}
>>>s1.add(4)
>>> s1 {1, 2, 3, 4}
We have to use update() to add multiple values.
>>> s1 = {1, 2, 3}
>>> s1.update([4, 5, 6])
>>> s1 {1, 2, 3, 4, 5, 6}
Remove and Discard
Intersection
Intersection is a concept of set theory in mathematics. An intersection of two sets is another
set which contains the values that are common in both sets.
Suppose we have two sets
A = {1, 2, 3}
B = {3, 4, 5}
Intersection of A and B = {3}
Because 3 is the only element that is common in both sets. In Python we can accomplish
intersection operation using the intersection() method.
>>> A = {1, 2, 3}
>>> B = {3, 4, 5}
>>> result = A.intersection(B)
>>> result {3}
We can have intersection of more than two sets also.
>>> A = {1, 2, 3, 4, 5}
>>> B = {2, 3, 4, 10, 11}
>>> C = {100, 3, 8, 2, 1, 4}
>>> result = A.intersection(B, C)
>>> result {2, 3, 4}
Union
An union of two sets is another set which contains all the values from both sets. If we
consider sets A and B from the previous example, their union would be {1, 2, 3, 4, 5}. Union
will take 3 once as it is in both sets.
We can accomplish union using the union() method in Python
. >>> A = {1, 2, 3}
>>> B = {3, 4, 5}
>>> result = A.union(B)
>>> result {1, 2, 3, 4, 5}
Union of more than two sets is also possible.
>>> A = {1, 2, 3}
>>> B = {3, 4, 5}
>>> C = {5, 6, 7}
>>> result = A.union(B, C)
>>> result {1, 2, 3, 4, 5, 6, 7}
People tend to make the same kinds of syntax mistakes, so their mistakes are usually
easy to spot and very much the same. After you read this article, you should be able to
remember and avoid (or fix) these common SQL syntax errors. Knowing what errors
to look for is very important for novice SQL coders, especially early on. New coders
tend to make more mistakes and spend more time looking for them.
Solution:
Use an SQL editor that has syntax highlighting: the SELECT and WHERE keywords
will be highlighted, but the misspelled FORM will not get highlighted.
If you’re learning with interactive SQL courses in LearnSQL.com, the code editor
puts every SELECT statement keyword in light purple. If the keyword is black, as it
is with any other argument, you know there’s a SQL syntax error. (In our example,
FORM is black).
So if we correct our statement we get:
SELECT *
FROM dish
WHERE NAME = 'Prawn Salad'
The keyword is now the right color and the statement executes without an error.
Syntax Error 2: Forgetting Brackets and Quotes
Brackets group operations together and guide the execution order. In SQL (and in
all of the programming languages I use), the following order of operations …
SELECT *
FROM artist
WHERE first_name = 'Vincent' and last_name = 'Monet' or last_name = 'Da Vinci';
… is not the same as:
SELECT *
FROM artist
WHERE first_name = 'Vincent' and (last_name = 'Monet' or last_name = 'Da
Vinci');
Can you figure out why?
A very common SQL syntax error is to forget the closing bracket. So if we look at
this erroneous statement :
SELECT *
FROM artist
WHERE first_name = 'Vincent' and (last_name = 'Monet' or last_name = 'Da Vinci';
We get a syntax error code with the position of the error (the 102nd character
from the beginning):
ERROR: syntax error at or near ";" Position: 102
Remember: brackets always come in pairs.
The same is true with single quotes ( ‘ ‘ ) or double quotes ( ” ” ). There is no
situation in SQL where we would find a quote (either a single quote or a double
quote) without its mate. Column text values can contain one quote ( e.g.
exp.last_name = "O'Reilly") and in these situations we must mix two types of
quotes or use escape characters. ( In SQL, using escape characters simply means
placing another quote near the character you want to deactivate – e.g.
exp.last_name = 'O'’Reilly.)
Solution:
Practice, practice, practice. Writing more SQL code will give you the experience
you need to avoid these syntax errors. And remember people usually forget the
closing bracket or quotation mark. They rarely leave out the opening one. If
you’re running into problems, take a close look at all your closing punctuation!
Solution:
Practice using table aliases for single-table SELECT statements. Use aliases often –
they make your SQL more readable.
Syntax Error 5: Using Case-Sensitive Names
This SQL syntax error only occurs when you need to write non-standard names for
tables or database objects.
Let’s say that you need to have a table named LargeClient and for some reason
you add another table called LARGECLIENT. As you already know, object names in
databases are usually case-insensitive. So when you write a query for the
LargeClient table, the database will actually query LARGECLIENT.
To avoid this syntax error, you must put double quotes around the table name.
For example:
SELECT * FROM
"LargeClient"
WHERE cust_name = 'Mijona';
When creating a table, you will need to use double quotes if:
The table will have a case-sensitive name.
The table name will contain special characters. This includes using a blank space,
like “Large Client”.
Solution:
Avoid using these names if you can. If not, remember your double quotes!
Everybody Makes SQL Syntax Errors
Those are the five most common syntax errors in SQL code. You’ll probably make
them many times as you learn this language. Remember, everybody makes
mistakes writing code. In fact, making mistakes is a normal and predictable part of
software development.
So don’t be discouraged. When you make mistakes in the future, try to analyze
your code in a structured way. With a structured analysis, you can find and
correct your syntax errors quicker.
Activity-6
1.Web Applications: Python aids in the rapid development of web applications that are both
scalable and secure.This is made possible and easier with the availability of web frameworks
like Django, Pyramid and Flask. These frameworks offer easy integration with various
protocols like HTTPS, SSl, etc and also support JSON and XML.
2.Data Science Implementations: Data science is a relatively new field that has gained
significant importance in recent years and Python is the go-to choice for developers working
on Data Science.Unlike Java, Python offers many libraries to handle Data science projects
like Pandas, NumPy, etc. Additionally, Python also offers data libraries like Matplolib,
Seaborn, etc for rich data visualizations. Data science is one of the most lucrative career
prospects in the technology industry today and for anyone who wants to start with Data
science should know Python first.
3.Artificial Intelligence: Python is extremely popular in the field of machine learning or AI.
Despite the age-old language, Python has evolved to fit into multiple new
technologies.Python is a stable language that can handle the huge set of computations
required for building complicated machine learning modules. Sensorflow, Numpy, Keras,
Scikit-learn are some of the popular libraries offered by Python to work on machine learning
and artificial intelligence projects.
4.Game Development: Python is versatile as it supports multiple use cases. Apart from
normal web development to complex AI, Python also aids in Game development.Python
libraries like PySoy and PyGame enable 3D game development. No matter what field you are
in, Python already has a library for you to get started easily.
5.Internet of things: One of the standout features of Python is its ability to connect with
hardware devices easily. Whether it comes to IoT or Robotics, Python can be useful.Python
offers smooth integration with Raspberry PI hardware platform which can be used to develop
embedded applications, Robotics and IoT projects. Python can easily run on Linux and for
microcontrollers, one can use MicroPython. Eg: PyBoard.
6.Web Scraping Applications: With Python, developers can extract huge volumes of data
from multiple websites by entering the URLs. Some of the popular libraries for web scraping
in Python are Selenium and PythonRequest. Python easily ranks no.1 choice for developing
web scraping applications.
7.Desktop GUI Applications: So far, we’ve been talking about Python mainly as the
backend but we can develop rich frontend applications using Python. Tkinter library in
Python can be used for designing user interfaces. Python toolkits like PyQT, Kivy, PyGUI,
etc. helps in designing UI applications across platforms.
8.Enterprise applications: Python can be used to develop complex and huge enterprise-
level applications since it is both scalable and secure. Python is largely used for database
handling and it supports multiple database requests simultaneously. The most important
functionalities of Python like readability and scalability make it a top choice for ERP
applications. Python offers a simple and easy-to-understand syntax which makes it easily
readable.
Tryton is a Python platform that enables the development of business softwares and ERP.
Odoo is an open-source ERP framework provided by Python that is used by more than 7
million users worldwide to develop ERP applications.
9.Image Recognition and text processing: Developers can also use Python to develop
image recognition softwares and also help in text processing. Python supports both 2D and
3D image generation and animation using packages like Blender, Houdini, 3ds Max,
Lightwave, etc.
10.API benefits: Python offers an easy to integrate Python SDK which is used to develop
and integrate with third party applications using API. Python offers various libraries which
makes connecting and working APIs a breeze.
Use cases
There are many real-world use-cases of sets in python, few are listed below.
To check whether an element is present in a list we can always use a for loop to iterate and
check or also we can use in operator.
list_a = [1,2,3,4,5]
for i in list_a:
if(i == 2) :
print Trueprint(2 in set_a)--------------------------------------------------------------------True
True
But a more efficient way of doing it is converting the list into a set and check the presence
using in operator.
list_a = [1,2,3,4,5]
set_a = set(list_a)print(2 in set_a)--------------------------------------------------------------------
True
list_a = [1,5,2,3,3,4,5,1]
set_a = set(list_a)
list_a = list(set_a)print(list_a)--------------------------------------------------------------------
[1, 2, 3, 4, 5]
To merge sets that have common elements, we can either check if sets are not disjoint
using isdisjoint() method or we can check the intersection using intersection() method then if
both sets do intersect, we can use union() method to merge the sets.
If we have a list of such sets then we have to use loops and recursion to merge all the sets.
def merge_if_intersect(m_list):
for i,set1 in enumerate(m_list):
for j,set2 in enumerate(m_list[i+1:],i+1):
if not set1.isdisjoint(set2): #or set1.intersection(set2)
m_list[i]=set1.union(m_list.pop(j))
return merge_if_intersect(m_list)
return m_listlist_a = [{1,2,3},{4,5},{5,6},{3,7},{8}]merged_list = merge_if_intersect(list_a)
print(merged_list)--------------------------------------------------------------------
[{1, 2, 3, 7}, {4, 5, 6}, {8}]
When you run your Python code, the interpreter will first parse it to convert it into Python
byte code, which it will then execute. The interpreter will find any invalid syntax in Python
during this first stage of program execution, also known as the parsing stage. If the
interpreter can’t parse your Python code successfully, then this means that you used invalid
syntax somewhere in your code. The interpreter will attempt to show you where that error
occurred.
When you’re learning Python for the first time, it can be frustrating to get a SyntaxError.
Python will attempt to help you determine where the invalid syntax is in your code, but
the traceback it provides can be a little confusing. Sometimes, the code it points to is
perfectly fine.
You can’t handle invalid syntax in Python like other exceptions. Even if you tried to wrap
a try and except block around code with invalid syntax, you’d still see the interpreter raise
a SyntaxError.
1# theofficefacts.py
2ages={
3 'pam':24,
4 'jim':24
5 'michael':43
6}
7print(f'Michael is {ages["michael"]} years old.')
You can see the invalid syntax in the dictionary literal on line 4. The second entry, 'jim', is
missing a comma. If you tried to run this code as-is, then you’d get the following traceback:
$ python theofficefacts.py
File "theofficefacts.py", line 5
'michael': 43
^
SyntaxError: invalid syntax
There are a few elements of a SyntaxError traceback that can help you determine where the
invalid syntax is in your code:
You might run into invalid syntax in Python when you’re defining or calling functions. For
example, you’ll see a SyntaxError if you use a semicolon instead of a colon at the end of a
function definition:
>>>
>>>deffun();
File "<stdin>", line 1
deffun();
^
SyntaxError: invalid syntax
The traceback here is very helpful, with the caret pointing right to the problem character. You
can clear up this invalid syntax in Python by switching out the semicolon for a colon.
In addition, keyword arguments in both function definitions and function calls need to be in
the right order. Keyword arguments always come after positional arguments. Failure to use
this ordering will lead to a SyntaxError:
>>>
>>>deffun(a,b):
... print(a,b)
...
>>>fun(a=1,2)
File "<stdin>", line 1
SyntaxError: positional argument follows keyword argument
Here, once again, the error message is very helpful in telling you exactly what is wrong with
the line.
Sometimes, code that works perfectly fine in one version of Python breaks in a newer
version. This is due to official changes in language syntax. The most well-known example of
this is the print statement, which went from a keyword in Python 2 to a built-in function in
Python 3:
>>>
>>> # Valid Python 2 syntax that fails in Python 3
>>>print'hello'
File "<stdin>", line 1
print'hello'
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello')?
This is one of the examples where the error message provided with the SyntaxError shines!
Not only does it tell you that you’re missing parenthesis in the print call, but it also provides
the correct code to help you fix the statement.
Python 3.8 also provides the new SyntaxWarning. You’ll see this warning in situations
where the syntax is valid but still looks suspicious. An example of this would be if you were
missing a comma between two tuples in a list. This would be valid syntax in Python versions
before 3.8, but the code would raise a TypeError because a tuple is not callable:
>>>
>>>[(1,2)(2,3)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable
This TypeError means that you can’t call a tuple like a function, which is what the Python
interpreter thinks you’re doing.
In Python 3.8, this code still raises the TypeError, but now you’ll also see
a SyntaxWarning that indicates how you can go about fixing the problem:
Given below are some important Python list built-in functions. Kindly visit the Python
official documentation page for details of these functions.
14. all()
The Python all() function returns True if all the elements of an iterable are true, or if the
iterable is empty.
• Syntax: all(iterable)
15. any()
The Python any() function returns True if at least one item of the iterable is true. Unlike all(),
it will return False if the iterable is empty.
• Syntax: any(iterable)
Activity 7
7.1 Identify The Use Cases And Solve Them Using
Dictionary.
Comprehensions in Python are syntactic constructs that are
used to build sequences from other sequences. Essentially,
comprehensions are a fancy form of writing for loops that are
more concise and readable.
All comprehensions can be rewritten using for loops but the
vice-versa doesn’t hold true. At large, there are four types of
comprehension techniques in Python. List Comprehensions Dictionary
Comprehensions Set Comprehensions Generator Comprehensions
The goal of this piece is to show you the power of dictionary
comprehensions and how to leverage it in different ways. Before
we explore a few interesting cases, let’s understand the syntax
as it can confuse a lot of developers when starting out.
Syntax of Dictionary Comprehensions
Consider the following code that creates a dictionary from a range of numbers with the value
being the square of the key:
square_dict = {num: num*num for num in range(1, 6)}
print(square_dict)
#Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Now let’s analyze the syntax of the dictionary expression using
the above code as a reference:
The above syntax represents the minimal form of writing a dictionary comprehension. The
output of the dictionary comprehension is highlighted in green. All the key-value pairs are
assigned to the constructed dictionary. The iterable doesn’t have to be a dictionary. It can be
any python object on which you can loop over — list, tuple, strings, etc. Unlike list
comprehensions, a dictionary comprehension can iterate over a group of keys and values
simultaneously as well. By invoking the items() method on a dictionary, you can convert it
into a list of tuples of key-value to loop over. You can also set a conditional statement after
the for loop in dictionary comprehension as shown below
fruits = ['Apple', 'Orange', 'Papaya', 'Banana', '']
fruits_dict = {f:len(f) for f in fruits if len(f) > 0}
print(fruits_dict)
#Output
{'Apple': 5, 'Orange': 6, 'Papaya': 6, 'Banana': 6}
Now that we’ve got a good look at the syntax of dictionary
comprehensions, let's move onto its applications.
1. Word Frequency
Often a case comes up where you need to build a dictionary that
holds the count of each word in a string. The classic way of
doing this using for loops would be:
s = 'I felt happy because I saw the others were happy and
because I knew I should feel happy'dict = {}
for token in s.split(" "):
dict[token] = dict.get(token, 0) + 1
But we can make it significantly shorter using dictionary
comprehensions as shown below:
frequency_dict = {token: s.split().count(token) for token in
set(s.split())}#Output
{'felt': 1, 'and': 1, 'should': 1, 'others': 1, 'saw': 1, 'were': 1, 'knew':
1, 'happy': 3, 'feel': 1, 'the': 1, 'because': 2, 'I': 4}
2. Modifying Keys and Values of a Dictionary
With a large dictionary, there might come a point where you
need to append a single character to all of them. It could be a
simple $ symbol for instance.
In another scenario, you might need to remove a character from
a key or value string. Here’s an example of how to create a new
dictionary by modifying keys and values using dictionary
comprehension:
d = {'My_Article1': '1', 'My_Article2' : '2'}my_dict = { k[3:] : '$'
+ v for k, v in d.items()}#Output
{'Article1'
3. Filter Dictionaries by a Group of Keys
You probably might be interested in only a part of a dictionary
that has a certain set of keys. Here’s an example that filters and
creates a new dictionary based on a list of keys:
d = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
keys = [1, 2]my_dict = {key: d[key] for key in keys}
#Output
{1: 'a', 2: 'b'}
But the above code would throw an error when the list
of keys contains an extraneous value not present in the
dictionary. So, instead of iterating over keys , we’ll look to find
the common keys in d and keys using sets as shown below:
my_dict = {key: d[key] for key in
set(keys).intersection(d.keys())}
Here’s a third case, where we’re filtering the dictionary by keys
containing a specified string:
d = {'num_1': 'a', '2': 'b', 'num_3': 'c', '4': 'd'}filter_string =
'num'
filtered_dict = {k:v for (k,v) in d.items() if filter_string in k}
#Output
{'num_1': 'a', 'num_3': 'c'}: '$1', 'Article2': '$2'}
4. Invert the Mapping of a Dictionary
In cases, where your dictionary has unique keys and values and
would like to invert the mapping from k:v to v:k you could do it
with a for loop in the following way:
d = {'1': 'a', '2': 'b', '3': 'c', '4': 'd'}my_dict = {}
for k,v in d.items():
my_dict[v] = k
By using dictionary comprehension, we can do the same thing
in a single line as:
my_dict = {v: k for k, v in d.items()}
#Output
{'a': '1', 'b': '2', 'c': '3', 'd': '4'}
5. Tuples and Sparse Vectors to Dictionary
Next up, we have a tuple list where each element holds the
country code and name. We’ll create a dictionary out of it using
comprehension technique with the country name being the key,
and country-code being the value:
tuples = [("US", '+1'), ("Australia", '+61'), ("India", '+91')]
my_dict = {k[0]: k[1] for k in tuples}
Sparse vectors generally contain a lot of zero values. We can
consider keeping only non-zero values in a dictionary we can
save some space. By using the following dictionary
comprehension technique, we can convert a sparse vector to
key-value pairs with the key being the index from the sparse
vector:
values = [0,0,21,0,0,0,100]
my_dict = { values.index(v) : v for v in values if v}
#Output
{2: 21, 6: 100}
There’s another way of writing the above dictionary
comprehension that’s slightly more readable:
my_dict = {n: v for n,v in enumerate(values) if v}
if v indicates to add the key and value to the dictionary only if
the sparse vector’s element isn’t False, 0, None, etc.
6. Sorting A Dictionary
There are different ways to sort a dictionary. We can do it with
keys or values, in ascending or descending orders. Let’s take a
look.
Here’s an example to sort by keys in ascending and descending order:
d = {"a": 3, "b": 4, "d": 1, "c": 2}
dk_ascending = {k: d[k] for k in sorted(d)}
#Output
{'a': 3, 'b': 4, 'c': 2, 'd': 1}dk_descending = {k: d[k] for k in
sorted(d, reverse=True)}
#Output
{'d': 1, 'c': 2, 'b': 4, 'a': 3}
The below example shows how to sort by value in ascending
and descending order:
d = {"a": 3, "b": 4, "d": 1, "c": 2}
dv_ascending = {k: d[k] for k in sorted(d, key=d.get)}
#Output
{'d': 1, 'c': 2, 'a': 3, 'b': 4}dv_descending = {k: d[k] for k in
sorted(d, key=d.get, reverse=True)}
#Output
{'b': 4, 'a': 3, 'c': 2, 'd': 1}
7. Flattening List of Dictionaries into Single Dictionary
Let’s say we have an unknown number of dictionaries present
in a Python List as shown below:
l = [{'a':1}, {'b':2}, {'c':3, 'd' : 4}]
Now, we’d like to flatten the list into a dictionary such that all
the sub-dictionaries are merged into a single dictionary.
technique:
my_dict = {k: v
for d in l
for k, v in d.items()
}#Output
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
b.Reimplement built in dictionary functions
Dictionary is a really useful data type built into Python, basically it is a number of objects
that are indexed by keys, the key here must be hashable. Here is one simple dictionary usage:
>>>d={'fengsp':10,'amy':12}
>>>d['fengsp']
10
>>>deld['fengsp']
>>>d.keys()
['amy']
We retrieve the value a lot of times, the retrieval of one object by the key must be a very fast
operation. For the CPython itself, several language features are supported with the help of
dictionaries, for example, class instances use a dictionary to store attributes, the performance
of the dictionary is essential.
The PyDictObject
PyDictEntry*ma_table;
PyDictEntry*(*ma_lookup)(PyDictObject*mp,PyObject*key,longhash);
PyDictEntryma_smalltable[PyDict_MINSIZE];
};
typedefstruct{
Py_ssize_tme_hash;
PyObject*me_key;
PyObject*me_value;
}PyDictEntry;
The fields in the data structure are:
ma_fill
Number of active and dummy entries. If you delete a key, the entry will become
a dummy entry and ma_fill remains the same, if you add a new key and the new
key doesn't occupy a dummy entry, this is increased by 1.
DUMMY='dummy'
# I am not clever enough to understand how the algorithm is came up with,
# this eventually covers every integer between 0 and ma_mask.
defopen_addressing_in_cpython(table,key,hash):
free_slot=None
perturb=hash
i=slot_index=hash&ma_mask
whiletable[slot_index]isnotNoneandtable[slot_index].key!=key:
iftable[slot_index].keyisDUMMYandfree_slotisNone:
free_slot=slot_index
i=(5*i+perturb+1)
slot_index=i&ma_mask
perturb>>=5
iftable[slot_index]isNoneandfree_slotisnotNone:
returnfree_slot
returnslot_index
Free List
Many dictionary instances are created and destroyed frequently, in order to reduce the
number of creation and destruction, a free_dicts array is used to hold dictionary objects that
are not in use anymore, it is simply one cache. If we need a PyDictObject, it would be taken
from the free list if available.
The dictionary uses more memory than is necessary when used as an object attributes
container as the keys are the same and they are replicated for each instance. Since Python 3.6,
attribute dictionaries share keys with other attribute dictionaries of instances of the same
class, for example if you have a class like this:
classUser(object):
def__init__(self,username,email):
self.username=username
self.email=email
The attribute dictionary would be stored like this:
# this is shared between attribute dictionaries
# this is also ordered
keys=[
(5317300778844242624,'username'),
(268341141884068675,'email'),
]
# this hash table just stores the index to the key entries
# it is compact
index_table=[0,None,None,1,None,None,None,None]
# this is values
values=['user01','user01@example.com']
print(my_dict)
Output:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
We generally use dictionaries to access the items with its key value, inside square brackets.
print(my_dict[1])
print(my_dict[2])
print(my_dict[3])
Output:
Geeks
For
Geeks
Common mistakes while using dicts and overcomes
• To access the value of the key, we generally use dict_name[key_name] instead we
should use get() method to get rid of the exceptions thrown all throughout your code.
• To update the value of the key, we generally use dict_name[key_name]=’new_value’
instead we should update(key=value) method to get rid of the exceptions thrown all
throughout your code.
• To copy the dictionary, we generally use dict_name = new_dict_name instead we
should use copy() method to get rid of the exceptions thrown all throughout your code.
When not to use dicts
• Dicts are useful but they’re not the only associative array structure in Python. Often
there is a more specialised container type like set, tuple etc.
• Numeric values with different types can be equal (e.g. 1 == 1.0), in which case they
represent the same key.
• Given a dictionary of list values, the task is to combine every key-value pair in every
combination.
• Input :
{“Name” : [“Paras”, “Chunky”],
“Site” : [“Geeksforgeeks”, “Cyware”, “Google”] }
• Output:
[{‘Site’: ‘Geeksforgeeks’, ‘Name’: ‘Paras’}, {‘Site’: ‘Cyware’, ‘Name’: ‘Paras’},
{‘Site’: ‘Google’, ‘Name’: ‘Paras’}, {‘Site’: ‘Geeksforgeeks’, ‘Name’: ‘Chunky’},
{‘Site’: ‘Cyware’, ‘Name’: ‘Chunky’}, {‘Site’: ‘Google’, ‘Name’: ‘Chunky’}]
You saw earlier that you could get a Syntax Error if you leave the comma off of a dictionary
element. Another form of invalid syntax with Python dictionaries is the use of the equals sign
(=) to separate keys and values, instead of the colon:
>>>
>>>ages={'pam'=24}
File "<stdin>", line 1
ages={'pam'=24}
^
Syntax Error: invalid syntax
Once again, this error message is not very helpful. The repeated line and caret, however, are
very helpful! They’re pointing right to the problem character.
This type of issue is common if you confuse Python syntax with that of other programming
languages. You’ll also see this if you confuse the act of defining a dictionary with
a dict() call. To fix this, you could replace the equals sign with a colon. You can also switch
to using dict():
>>>
>>>ages=dict(pam=24)
>>>ages
{'pam': 24}
You can use dict() to define the dictionary if that syntax is more helpful.
There are two sub-classes of SyntaxError that deal with indentation issues specifically:
1. Indentation Error
2. Tab Error
While other programming languages use curly braces to denote blocks of code, Python
uses whitespace. That means that Python expects the whitespace in your code to behave
predictably. It will raise an Indentation Error if there’s a line in a code block that has the
wrong number of spaces:
1# indentation.py
2deffoo():
3 foriinrange(10):
4 print(i)
5 print('done')
6
7foo()
This might be tough to see, but line 5 is only indented 2 spaces. It should be in line with
the for loop statement, which is 4 spaces over. Thankfully, Python can spot this easily and
will quickly tell you what the issue is.
There’s also a bit of ambiguity here, though. Is the print('done') line intended to
be after the for loop or inside the for loop block? When you run the above code, you’ll see
the following error:
$ python indentation.py
File "indentation.py", line 5
print('done')
^
Indentation Error: unindent does not match any outer indentation level
Even though the traceback looks a lot like the Syntax Error traceback, it’s actually
an Indentation Error. The error message is also very helpful. It tells you that the indentation
level of the line doesn’t match any other indentation level. In other words, print('done') is
indented 2 spaces, but Python can’t find any other line of code that matches this level of
indentation. You can fix this quickly by making sure the code lines up with the expected
indentation level.
The other type of Syntax Error is the Tab Error, which you’ll see whenever there’s a line
that contains either tabs or spaces for its indentation, while the rest of the file contains the
other. This might go hidden until Python points it out to you!
If your tab size is the same width as the number of spaces in each indentation level, then it
might look like all the lines are at the same level. However, if one line is indented using
spaces and the other is indented with tabs, then Python will point this out as a problem:
1# indentation.py
2deffoo():
3 foriinrange(10):
4 print(i)
5 print('done')
6
7foo()
Here, line 5 is indented with a tab instead of 4 spaces. This code block could look perfectly
fine to you, or it could look completely wrong, depending on your system settings.
Python, however, will notice the issue immediately. But before you run the code to see what
Python will tell you is wrong, it might be helpful for you to see an example of what the code
looks like under different tab width settings:
1 .forEach()
The .forEach() method comes in handy when you want to manipulate some data but you don’t
need to return any data. All this method does is executes a function (that you provide) once for
Use Case
problem. Using the .querySelectorAll() method returns us a NodeList which we will treat just
like an array. We store that NodeList into a variable so we can send it through
We cycle over each button in the array and add an event listener to each button that logs the
button at a particular index when clicked. That was pretty easy and of course you’ll want to do
2 .reduce()
The .reduce() method is helpful when we want to reduce data down to a single value. This
method simply applies a function against an accumulator (gathers the values) and each
Use Case
We are dealing with a shopping cart with multiple line items and we need to give the customer
a single total value for checkout. We have an array of the line items purchase prices. We will
need to write a function to provide to the .reduce() method that will handle two arguments
Once we have written that function to give the .reduce() method all we have to do is call the
reduce method on our array and pass the newly created function to the method.
3 .map()
The .map() method is useful if we need to make changes to data and return that data in a new
array. A good rule of thumb is to never manipulate your core data. Simply make a copy of that
data with any changes. The .map() method creates a new array with the results of calling a
We have an array of objects for users. Without corrupting the original data we would like to
add a new group property to this set of users. We could achieve this with less code and much
easier with the .forEach() method we mentioned earlier, but that would not return us a new
array. We should create a new variable to store the array of objects in. That new variable
should map over the users array and return a new object with the current properties and one
4 .filter()
The .filter() method is super helpful when you need to filter through a data set and return only
the data you need. This method creates a new array with all elements that pass the user
implemented function.
Use Case
We need to return data to a user based on search terms. Those search terms are tracked
through an input in the UI. We filter our data based on the search terms and return only the
5 .some()
The .some() method is helpful when you are looking for a truthy value in data. A great thing
about this method is it will exit immediately once an element in your data returns true.
The .some() method executes a function once for each element in an array until it finds one
Use Case
We will reference our use case for the .map() method. We need to do a quick check on our
follow on Twitter!
// the following statements are not allowed and will cause compiler errors
inta[10], b[10];
a = b; // cannot assign an entire array - visual c++ gives left operand not a l-value
a[3] = b[3]; // this is OK
cin >> someString; // reads next bunch of non-whitespace characters into somestring
// inserts null character are end
// assumes that this will be 10 or less characters
Sub Example1()
intTemp = 10
End Sub
Sub Example2()
strTemp = "Data" + 10
End Sub
Sub Example3()
Cells(1, 1) = "Data" + 10
End Sub
Activity-9
1. Optimize previously written programs by using modular programming approach
Modular programming is the process of subdividing a computer program into separate sub-
programs. A module is a separate software component. It can often be used in a variety of
applications and functions with other components of the system.
1. Ease of Use :This approach allows simplicity, as rather than focusing on the entire
thousands and millions of lines code in one go we can access it in the form of modules. This
allows ease in debugging the code and prone to less error.
2. Reusability :It allows the user to reuse the functionality with a different
interface without typing the whole program again.
3. Ease of Maintenance : It helps in less collision at the time of working on
modules, helping a team to work with proper collaboration while working on a large
application.
Given three strings(without spaces). The task is to print the new string after modifying the
three given string as follows:
• Replace all the vowels present in the first string with “*”.
• Don’t change anything in the second string.
• Replace all the consonants in the third string with “$”.
• Concatenate all of the three string to obtain the new string.
Examples:
Approach:
The idea is to traverse the first string and keep checking if any character is a vowel or not.
Replace the character in the first string which is vowel with “*”. Similarly, traverse the third
string and keep checking if any character is not a vowel. If a character in the third string is
not a vowel(then it is a consonant), replace it with ‘$’.
Finally, concatenate the three strings and print the newly concatenated string.
Below is the implementation of the above approach:
• C++
• Java
• Python3
• C#
• Javascript
This article is a sum of major differences in modules and packages in python. For many
coders, it’s very hard to identify when and where a module or a package should be used.
In this article, a clear set of differences will make it easy for the coder to work more
efficiently while dealing with both modules and packages.
What are Python Modules?
A module is a python statement which contains multiple functions in it. Modules act as a pre-
defined library in the code, which is accessible to both coder and user.
The python modules also store pre-defined functions from the library while the execution of
code is going on.
Using a well structured and standard layout for the package makes it easy to employ user-
specific tools. It also simplifies the executions in runtimE.
While streaming on any media channel like Netflix or Spotify, we have been surprised by the
recommendations these sites provide which are almost always close to heart. Well, the magic
behind all of this is Deep Learning.
recommendations. These systems are one of the most widespread applications of Pandas. In
most of these cases, the models are coded in python and pandas is the best library to use
when you have handled such data in these models.
Pandas can handle a large amount of data which helps it in learning the tonnes of data it
requires to build a good recommendation system. Functions like mapping and GroupBy are
instrumental in making these recommendation systems workable.
2. Economics:
Data analysis is a constant need for Economics because it's always changing. The data needs
to be analysed to create patterns and trends which are then analysed and interpreted to
understand how the economy in various sectors is faring, something which is of extreme
importance to economists.
A lot of modern-day economists have taken to pandas and python to handle huge datasets and
interpret that data. Pandas have an extensive list of inbuilt tools and functions that make it the
efficient package it is.
Tools like file-handling and data frames are extremely useful to access data and manipulate it
to get the results we want. These applications of Pandas has helped Economists all over the
world to make breakthroughs and studies they could not do earlier.
3. Neuroscience:
Understanding how our brains (and consequently the entire nervous system) work has been
an unfulfilled wish of doctors since time immemorial because they believe that it will help
discover answers to many mysteries that our body holds.
Machine Learning, driven by the numerous applications of pandas, has helped this field a lot.
Once again, pandas' great capability of data manipulation has played a huge role. They have
helped compile copious amounts of data and analysed it to produce results which are quite
significant for neuroscientists.
4. Prediction of stocks:
one of the biggest datasets in the world. Although it is almost impossible to predict the
changes in stock market, with the correct application of Pandas and some help from a few
libraries like MatPlotLib and NumPy, you can easily make models which can predict (to a
large extent) how the stock market will turn out to be.
This is only possible because of the huge datasets we have in terms of the previous behaviour
of the stocks which inform the system about their behaviour both individual ad
codependently. By learning these behaviours and movements, a good model will be able to
predict with quite a bit of accuracy as to what your next move should bFew things in the
world are as volatile as the stock market. This is literally e.
5. Advertising:
With the advent of the 21st century, no field has progressed more than marketing has.
Advertising has become more and more personalized. This change has once again been
driven by Deep Learning and Machine Learning.
6. Statistical analysis:
Statistics itself means dealing with loads of data. Hence a library like pandas is able to help in
various ways because it basically deals with various forms of data handling and its functions.
The basic functions of mean, median, and mode are quite helpful while performing
calculations based on statistics. There are loads of other functions in pandas which help you
with getting better results in Statistics.
A very common buzzword right now, Natural Language Processing or NLP has announced
its arrival to the world in style. The main purpose of this concept is to help computers
understand the normal human language and the various nuances it possesses. This is quite a
difficult task to accomplish, but with pandas at your service along with Scikit-Learn, you can
create a basic model for NLP which you can enhance later on. You can use various functions
and other libraries to help you out.
8. Analytics:
Analytics is everywhere. Whether you want to analyse a website or analyse any other
platform, pandas helps you in doing it all. Its efficient data handling capabilities and dynamic
data manipulation combined with its amazing visualization capabilities play a huge role in
helping it ace this field.
9. Data science:
Most of the examples we have discussed are a part and parcel of data science. It is a huge
umbrella which covers any and every field that deals with the analysis, handling, and
manipulation of data. Therefore almost all of pandas applications fall under it.
Python has a great link with Spark and Hadoop. Therefore Pandas can work with Big data
too.
Conclusion:
We hope that by reading the examples given above, you have now come to know about the
various fields in which pandas can be applied in our day to day lives. You now know where
to use all of your knowledge in Pandas and also have a good understanding of its true power.
If you still have any queries, fire them down below in the comments section.
Pandas is the most popular python library that is used for data analysis. It provides highly
optimized performance with back-end source code is purely written in C or Python.
1. Series
2. Data Frames
Series:
Series is one dimensional(1-D) array defined in pandas that can be used to store any data
type.
import pandas as pd
# Numeric data
Data =[1, 3, 4, 5, 6, 2, 9]
s = pd.Series(Data)
si = pd.Series(Data, Index)
Output:
Scalar Data with default
de Index
sd = pd.Series(dictionary)
Output:
Dictionary type data
# Defining 2darray
snd = pd.Series(Data)
Output:
Data as Ndarray
DataFrames:
DataFrames is two-dimensional(2
imensional(2-D)
D) data structure defined in pandas which consists of
rows and columns.
Code #1: Creation of DataFrame
import pandas as pd
a = pd.DataFrame(Data)
# Define Dictionary 1
# Define Dictionary 2
# Create DataFrame
df = pd.DataFrame(Data)
Output:
DataFrame with two dictionaries
import pandas as pd
# Define series 1
s1 = pd.Series([1, 3, 4, 5, 6, 2, 9])
# Define series 2
# Define series 3
# Define Data
# Create DataFrame
dfseries = pd.DataFrame(Data)
Output:
12b. Explore regular expressions and present how they can be used for file anipulation
Exption handling 3
int a, b, x;
a = 10;
b = Integer.parseInt(kb.readLine());
x = a / b; //ERROR if b = 0
This error occurs only for a certain configuration of the input (b = 0).
Example 2: File does not exist:
FileReader f = new FileReader("pippo.txt");
The error occurs only if the file pippo.txt does not exist on the harddi Example 3:
Dereferencing of a null reference: