0% found this document useful (0 votes)
2 views81 pages

python activity

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 81

Activity1

1)a. compare and contrast excel and python


Given Two Excel Files, We want to compare the values of each column row-wise after
sorting the values and print the changed column name and row number and values change.
Input :
Two Excel files
Output :
Column name : 'location' and Row Number : 0
Column name : 'location' and Row Number : 3
Column name : 'date' and Row Number :1

Code : Python code for comparing two excel files

# Write Python3 code here


# importing Pandas
import pandas as pd
#Reading two Excel Sheets
sheet1 = pd.read_excel(r'Book1.xlsx')
sheet2 = pd.read_excel(r'Book2.xlsx')
# Iterating the Columns Names of both Sheets
for i,j in zip(sheet1,sheet2):
# Creating empty lists to append the columns values
a,b =[],[]
# Iterating the columns values
for m, n in zip(sheet1[i],sheet2[j]):
# Appending values in lists
a.append(m)
b.append(n)

# Sorting the lists


a.sort() b.sort()
# Iterating the list's values and comparing them
for m, n in zip(range(len(a)), range(len(b))):
if a[m] != b[n]:
print('Column name : \'{}\' and Row Number : {}'.format(i,m))

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

Atom is developed by GitHub, which is initially started as an open-source, cross-platform. It


is based on a framework, i.e., Electron which enables cross-platform desktop application
using Chromium and Node.js and generally known as "Hackable Text Editor for the
21st century".

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.

Microsoft Visual Studio


Activity 2

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.

Use Case Diagram– Student Management System


Use case diagram elements:
The use case diagram consist of six graphics elements that represent whole 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.

EXAMPLE OF INPUT() FUNCTION


Python input() Function Example
# Taking input as string
color = input("What color is rose?: ")
print(color)

# Taking input as int


# Typecasting to int
n = int(input("How many roses?: "))
print(n)

# Taking input as float


# Typecasting to float
price = float(input("Price of each rose?: "))
print(price)
Output:

What color is rose?: red


red
How many roses?: 10
10
Price of each rose?: 15.50
15.
raw_input() function
Python raw_input function is used to get the values from the user. We call this function 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 only in Python 2.x version. The Python 2.x has two functions to take
the value from the user. The first one is input function and another one is raw_input()
function. The raw_input() function is similar to input() function in PythonPython raw_input()
example
EXAMPLE OF RAW_INPUT() FUNCTION
In this example, read the user name using raw_input() and display back on the screen using
print():

#!/usr/bin/python
name=raw_input('Enter your name : ')
print ("Hi %s, Let us be friends!" % name);
Sample outputs:

Enter your name : nixCraft


Hi nixCraft, Let us be friends!
In this following example, a string called choice converted to a numeric variable.

#!/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 * '-')

## Get input ###


choice = raw_input('Enter your choice [1-3] : ')

### Convert string to int type ##


choice = int(choice)

### Take action as per selected menu-option ###


if choice == 1:
print ("Starting backup...")
elif choice == 2:
print ("Starting user management...")
elif choice == 3:
print ("Rebooting the server...")
01else: ## default ##

2)c.Identify use of operators and develop algorithms to solve the same& compare and
contrast different types of operators

Arithmetic Operators

Arithmetic operators are used to performing mathematical operations like addition,


subtraction, multiplication, and division.
• In Python 3.x the result of division is a floating-point while in Python 2.x division of 2
integer was an integer and to obtain an integer result in Python 3.x floored (// integer) is
used.

Operator Description Syntax


+ Addition: adds two operands x+y
– Subtraction: subtracts two operands x–y
* Multiplication: multiplies two operands x*y
/ Division (float): divides the first operand by the second x/y
// Division (floor): divides the first operand by the second x // y
% Modulus: returns the remainder when the first operand is divided by the x%y
second
** Power: Returns first raised to power second x ** y

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.

Operator Description Syntax


and Logical AND: True if both the operands are true x and y
or Logical OR: True if either of the operands is true x or y
not Logical NOT: True if the operand is false not x

Bitwise Operators
Bitwise operators act on bits and perform the bit-by-bit operations. These are used to
operate on binary numbers.

Operator Description Syntax


& Bitwise AND x&y
| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR x^y
>> Bitwise right shift x>>
<< Bitwise left shift x<<

Assignment Operators
Assignment operators are used to assign values to the variables.

Operator Description Syntax


= Assign value of right side of expression to left side operand x=y+z
+= Add AND: Add right-side operand with left side operand and a+=b a=a+b
then assign to left operand
-= Subtract AND: Subtract right operand from left operand and then a-=b a=a-b
assign to left operand
*= Multiply AND: Multiply right operand with left operand and then a*=b a=a*b
assign to left operand
/= Divide AND: Divide left operand with right operand and then a/=b a=a/b
assign to left operand
%= Modulus AND: Takes modulus using left and right operands and a%=b
assign the result to left operand a=a%b
//= Divide(floor) AND: Divide left operand with right operand and a//=b a=a//b
then assign the value(floor) to left operand
**= Exponent AND: Calculate exponent(raise power) value using a**=b
operands and assign value to left operand a=a**b
&= Performs Bitwise AND on operands and assign value to left a&=b
operand a=a&b
|= Performs Bitwise OR on operands and assign value to left a|=b a=a|b
operand
^= Performs Bitwise xOR on operands and assign value to left a^=b a=a^b
operand
>>= Performs Bitwise right shift on operands and assign value to left a>>=b
operand a=a>>b
<<= Performs Bitwise left shift on operands and assign value to left a <<= b a=
operand a << b

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.

- Examples Of Decision-Making In Different Scenarios


Deciding what to wear.
Deciding what to eat for lunch.
Choosing which book to read.
Deciding what task to do next.
What is an algorithm development?
Algorithm development is more than just programming. It requires an understanding of the
alternatives available for solving a computational problem, including the hardware,
networking, programming language, and performance constraints that accompany any
particular solution.

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)

Missing Attribute Values: None


Class Distribution:
46.08 percent are L
07.84 percent are B
46.08 percent are R

You can find more details of the dataset here.

Which control statement is used for decision making?


In the case of decision control statements in C language (nested if and if-else), a group of
available statements will get executed in case the conditions we have are true. The execution
of the else part statements won't occur whenever these available conditions happen to be
false.

b. Identify common syntactical errors when using control flow statements


SYNTAX ERRORS: -
leaving out a keyword. -putting a keyword in the wrong place
. -leaving out a symbol, such as a colon, comma or brackets
. -misspelling a keyword
. -incorrect indentation.
-empty block.
ERRORS: Errors or mistakes in a program are often referred to as bugs. They are almost
always the fault of the programmer. The process of finding and eliminating errors is called
debugging. Errors can be classified into three major groups:
-Syntax errors
-Runtime errors
-Logical errors
SYNTAX ERROR:
Python will find these kinds of errors when it tries to parse your program, and exit with an
error message without running anything. Syntax errors are mistakes in the use of the Python
language, and are analogous to spelling or grammar mistakes in a language like English: for
example, the sentence Would you some tea? does not make sense – it is missing a verb
. Common Python syntax errors include:
leaving out a keyword
putting a keyword in the wrong place leaving out a symbol, such as a colon, comma or
brackets
misspelling a keyword incorrect indentation
empty block
Note it is illegal for any block (like an if body, or the body of a function) to be left
completely empty. If you want a block to do nothing, you can use the pass statement inside
the block.
Python will do its best to tell you where the error is located, but sometimes its messages can
be misleading: for example, if you forget to escape a quotation mark inside a string you may
get a syntax error referring to a place later in your code, even though that is not the real
source of the problem. If you can’t see anything wrong on the line specified in the error
message, try backtracking through the previous few lines. As you program more, you will get
better at identifying and fixing errors.
Here are some examples of syntax errors in Python:
myfunction(x, y):
return x + y else:
print("Hello!")
if mark >= 50
print("You passed!")
if arriving:
print("Hi!")
esle: print("Bye!") if flag: print("Flag is set!")

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.

Let’s take an example to make a cup of tea,


Step 1: Start
Step 2: Take some water in a bowl.
Step 3: Put the water on a gas burner.
Step 4: Turn on the gas burner
Step 5: Wait for some time until the water is boiled.
Step 6: Add some tea leaves to the water according to the requirement.
Step 7: Then again wait for some time until the water is getting colorful as tea.
Step 8: Then add some sugar according to taste.
Step 9: Again wait for some time until the sugar is melted.
Step 10: Turn off the gas burner and serve the tea in cups with biscuits.
Step 11: End
Here is an algorithm for making a cup of tea. This is the same for computer science
problems.
There are some basics steps to make an algorithm:

1. Start – Start the algorithm


2. Input – Take the input for values in which the algorithm will execute.
3. Conditions – Perform some conditions on the inputs to get the desired output.
4. Output – Printing the outputs.
5. End – End the execution.
Let’s take some examples of algorithms for computer science problems.

Example 1. Swap two numbers with a third variable


Step 1: Start
Step 2: Take 2 numbers as input.
Step 3: Declare another variable as “temp”.
Step 4: Store the first variable to “temp”.
Step 5: Store the second variable to the First variable.
Step 6: Store the “temp” variable to the 2nd variable.
Step 7: Print the First and second variables.
Step 8: End

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.

Iteration Method Algorithm:

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

Iteration Method Flowchart:


B) Compare and contrast different types of loop

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:

1. The loop always repeats the same number of times.


2. The program calculates the number of repetitions based upon user input.

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.

Here are a couple of examples of sentinel loops

1. Reading an unknown amount of numbers in the range from 0 through 10.


2. int Value;
3. cout << "Enter a list of numbers in the range 0 through 10 (any other number to quit):
"
4. cin >>Value; //Initialize
5. while (Value >= 0 && Value <= 10) { //Test
6. if (Value % 2 == 0) { //Loop Process
7. TotalEven++;
8. }
9. cout << "Enter a list of numbers in the range 0 through 10 (any other number to
quit): "
10. cin >>Value; //Update
11. }
12.
13. Validating input
14. char Upper;
15. cout << "Please enter an upper case letter: ";
16. cin >> Upper; //Initialize
17. while (Upper < 'A' || Upper > 'Z') { //Test
18. cout << "Error: " << Upper << " is not an upper case letter." << endl; //Loop
Process
19. cout << "Please enter an upper case letter: ";
20. cin >> Upper; //Update
21. }

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.

1. Calculating the years to accumulate an amount of money.


2. const float Invest = 100.0;
3. const float Goal = 1000000.00;
4. const float Rate = 0.06;
5. int Years = 0;
6. float Total = Invest; //Initialize
7. while (Total < Goal) { //Test
8. Years++; //Loop Process
9. Total = Total * (1 + Rate); //Update
10. }
11. cout << "It will take " << Years << " years to accumulate $" << Invest << endl;
12. cout << "to the total of $" << Goal << " at " << Rate*100 << "% interest."<< endl;
13.
14. Calculating the Greatest Common Divisor of two numbers. The algorithm is
explained on page 41 of the text.
15. int first;
16. int second;
17. int remainder;
18. cout << "Enter two integers: ";
19. cin >> first >> second;
20. cout << "The greatest common divisor of " << first << " and " << second << " is ";
21. remainder = first % second; //Initialize
22. while (remainder != 0) { //Test
23. first = second; //Loop Process
24. second = remainder;
25. remainder = first % second; //Update
26. }
27. cout << second << "." <, endl;

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.

Special sentinel loop

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;

C) Identify common syntactical errors when using loops .


The good thing about syntax errors is that compiler points out to where the problem might
be.
Let’s look at some most common causes of syntax errors.
• Misspelled reserved keywords
• Missing required spaces
• Missing quotes
• Misuse of block statements (if-else, loops)
• Missing assignment operator (=)
• Invalid variables declaration
• Invalid function calling or defining
We are mentioning strategies to fix syntax errors in python below:
Table of Contents
• Misspelled Reserved Words
• Missing Required Spaces
• Missing Quotes
• Misuse Of Block Statements ( If-Else, Loops)
• Missing Assignment Operator (=)
• Invalid Variables Declaration
• Invalid Function Calling Or Defining
• Conclusion
MISSPELLED RESERVED WORDS

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.

MISUSE OF BLOCK STATEMENTS ( IF-ELSE, LOOPS)


This is similar to missing spaces in addition to the missing semicolon (:). Python has another
rule to use a (:) while ending block statements like loops, if-else.

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.

INVALID FUNCTION CALLING OR DEFINING


Like any other block statement, function declaration has also a syntax. Proper spaces and use
of the colon (:) are necessary. Messing up with the syntax will prevent from execution. The
following example shows an executable function without errors.
Function calling has to have the required cautions to prevent bugs. The following error is
caused by the argument provided which is not defined in the declaration.

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}

Difference and Symmetric Difference


The difference() method will return what is different in two sets.
See the example below.
>>> A = {1, 2, 3}
>>> B = {2, 3, 4}
>>>A.difference(B)
{1}
>>>B.difference(A)
{4}
A and B have common values 2 and 3. A.difference(B) returns {1} because we are getting
the difference with respect to set A. In mathematics it is written as A-B. And B.difference(A)
gives us {4} because it is the difference between A and B with respect to set B. In
mathematics it is written as B-A.
We can get differences of both sets using the symmetric_difference() method
. >>>A.symmetric_difference(B) {1, 4}
>>>B.symmetric_difference(A) {1, 4}
Subset
We will call set A a subset of set B if all the elements of set A are present in set B.
A = {1, 2, 3}
B = {1, 2, 3, 4, 5}
Here A is a subset of B because all the elements of A are present in set B also. We can check
subset in Python using the issubset() method.
>>> A = {1, 2, 3}
>>> B = {1, 2, 3, 4, 5}
>>>A.issubset(B)
True
>>>B.issubset(A)
False
A.issubset(B) returns True because A is a subset of B. But B is not a subset of A. That is why
B.issubset(A) returns False.
Removing Duplicates From a List Using Set
>>> l = [1, 2, 2, 3, 5, 10, 2, 3, 12, 21, 10, 10]
>>> s = set(l)
>>> s {1, 2, 3, 5, 10, 12, 21}
But we are getting a set as result.
But we need a list. Well we can convert it into a list
. >>> lst = [1, 2, 2, 3, 5, 10, 2, 3, 12, 21, 10, 10]
>>> s = set(lst)
>>> s {1, 2, 3, 5, 10, 12, 21}
>>> result = list(s)
>>> result [1, 2, 3, 5, 10, 12, 21]

2.IDENTIFY USE CASES AND SOLVE THEM USING TUPLES


Definition of Tuple:
As we discussed above, a tuple is a data structure which allows storing multiple data at a
single time. When you store data in a tuple, it is kind of heterogeneous which make it the
most powerful feature of python programming language
. Use case for Python Tuple
tup = (1, [2])
# Re-assign first element
tup[0] = 3
Alt Text
This does not mean you really can’t change a tuple. If the underlying tuple element is
mutable then we can change it. This could lead to unintended side effects. For example,
children/inherited class can modify a tuple element initialised by the parent class.
# Add element to existing List element inside
Tuple tup[1].
append(3)
print(tup)
Alt Text
Use Case
Option 1: Using tuple List
The filtering based on the extension type is done with the help of endswith method. Since the
endswith method does not accept list we are looping through all the extension elements. The
code looks readable and takes about 2 microseconds which is not bad, but for every extension
type, we have to run through all the files one more time. I have a suspicion that we can do
much better
. # List of files in the folder
all_files = ['cat.jpg', 'dog.png', 'report.docx', 'sales.csv']
# List of image file extensions
img_exts_lst = ['jpg','png']
# Filter only imag
e files using List img_files = [file for file in all_files for ext in img_exts_lst if
file.endswith(ext)]
print(img_files) # ['cat.jpg', 'dog.png']
Option 2: Using Tuple
Almost similar code but we are able to pass the entire Tuple as parameter to the endswith
method. This removes the extra loop and makes the code even shorter. The code now runs
about 2 times faster. To run your own experiments use this notebook as base.
# List of files in the folder all_files = ['cat.jpg', 'dog.png', 'report.docx', 'sales.csv']
# Tuple of image file extensions img_exts_tup = ('jpg','png')
# Filter only image files using Tuple img_files = [file for file in all_files if
file.endswith(img_exts_tup)]
print(img_files) # ['cat.jpg', 'dog.png']
3. IDENTIFY COMMON SYNTACTICAL ERRORS WHEN WORKING WITH
SETS AND TUPLES

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.

The types of syntax errors in SQL we will look at are:


1.Misspelling Commands
2.Forgetting Brackets and Quotes
3.Specifying an Invalid Statement Order
4.Omitting Table Aliases
5.Using Case-Sensitive Names
Syntax Error 1:Misspelling Commands
This is the most common SQL syntax error among rookie and experienced
developers alike. Let’s see what it looks like. Examine the simple SELECT
statement below and see if you can spot a problem:
SELECT *
FORM dish
WHERE NAME = 'Prawn Salad';
If you run this query, you’ll get an error which states:
Syntax error in SQL statement "SELECT * FORM[*] dish WHERE NAME = 'Prawn
Salad';";
SQL statement: SELECT * FORM dish WHERE NAME = 'Prawn Salad'; [42000-
176]
Each database version will tell you the exact word or phrase it doesn’t
understand, although the error message may be slightly different.
What is wrong here? You misspelled FROM as FORM. Misspellings are commonly
found in keywords (like SELECT, FROM, and WHERE), or in table and column
names.
Most common SQL spelling errors are due to:
“Chubby fingers” where you hit a letter near the right one: SELEVT or FTOM or
WJIRE
“Reckless typing” where you type the right letters in the wrong order: SELETC or
FORM or WHEER

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!

Syntax Error 3: Invalid Statement Order


When writing SELECT statements, keep in mind that there is a predefined
keyword order needed for the statement to execute properly. There is no leeway
here.
Let’s look at an example of a correctly-ordered statement:
SELECT name
FROM dish
WHERE name = 'Prawn Salad'
GROUP BY name
HAVING count(*) = 1
ORDER BY name;
There’s no shortcut here; you simply have to remember the correct keyword
order for the SELECT statement:
SELECT identifies column names and functions
FROM specifies table name or names (and JOIN conditions if you’re using multiple
tables)
WHERE defines filtering statements
GROUP BY shows how to group columns
HAVING filters the grouped values
ORDER BY sets the order in which the results will be displayed
You cannot write a WHERE keyword before a FROM, and you can’t put a HAVING
before a GROUP BY. The statement would be invalid.
Let’s look at what happens when you mix up the statement order. In this instance,
we’ll use the common SQL syntax error of placing ORDER BY before GROUP BY:
SELECT name
FROM dish
WHERE name = 'Prawn Salad'
ORDER BY name
GROUP BY name
HAVING count(*) = 1
The error message we see is pretty intimidating!
Syntax error in SQL statement "SELECT name FROM dish WHERE name = 'Prawn
Salad'
ORDER BY name GROUP[*] BY name HAVING count(*) = 1;"; SQL statement:
SELECT name FROM dish WHERE name = 'Prawn Salad' ORDER BY name
GROUP
BY
name HAVING count(*) = 1; [42000-176]
Solution:
Don’t be discouraged! You can see that all of the keywords are highlighted
correctly and all the quotations and brackets are closed. So now you should check
the statement order. When you’re just beginning your SQL studies, I suggest using
a SELECT order checklist. If you run into a problem, refer to your list for the
correct order.

Syntax Error 4: Omitting Table Aliases


When joining tables, creating table aliases is a popular practice. These aliases
distinguish among columns with the same name across tables; thus the database
will know which column values to return. This is not mandatory when we’re
joining different tables, since we can use the full table names. But it is mandatory
if we join a table to itself.
Suppose we’re writing an SQL statement to find an exhibition’s current location
and the location from the previous year:
SELECT *
FROM exhibit
JOIN exhibit ON (id = previous_id);
The database would return an error:
Ambiguous column name "id"; SQL statement: SELECT * FROM exhibit JOIN
exhibit ON (id = previous_id); [90059-176]
Note: Whenever you encounter “ambiguous column name” in your error
message, you surely need table aliases.
The correct statement (with aliases) would be:
SELECT ex.* , exp.name
FROM exhibit
JOIN exhibit ON (ex.id = exp.previous_id);

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. Identify use cases and solve them using List.


Top 10 Use Cases of Python

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.

Eg: Disqus, YouTube, Eventbrite, Dropbox

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.

Eg: Civilization-IV, Disney’s Toontown Online, Vega Strike

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.

Eg: Inkscape, GIMP, Paint Shop

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.

1. Checking if element present in a list:

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

2. Making a list of unique elements:


To make a list where all list elements are unique, we just have to convert the list into a set and
then convert it back to a list.

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]

3. Merge sets if one or more elements are common:

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}]

2. Identify common syntactical errors when working with List

Invalid Syntax in Python

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.

• SyntaxError Exception and Traceback


When the interpreter encounters invalid syntax in Python code, it will raise
a SyntaxError exception and provide a traceback with some helpful information to help
you debug the error. Here’s some code that contains invalid syntax in Python:

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:

• The file name where the invalid syntax was encountered


• The line number and reproduced line of code where the issue was encountered
• A caret (^) on the line below the reproduced code, which shows you the point in the
code that has a problem
• The error message that comes after the exception type SyntaxError, which can

• Defining and Calling Functions

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.

• Changing Python Versions

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:

3. Reimplement built in list functions.

Python List Functions.

Given below are some important Python list built-in functions. Kindly visit the Python
official documentation page for details of these functions.

Commonly Used Python List Built-in Function

Name Syntax Description


len len(s) Returns the number of element in the list .
list list([iterable]) Creates a list out of an iterable.
range range([start,]stop[,step]) Returns an iterator of integers from start to stop,
with an increment of step.
sum sum(iterable[,start]) Adds all items of an iterable.
min min(iterable[,key, default]) Gets the smallest item in a sequence.
max max(iterable[,key, default]) Gets the largest item in a sequence.
sorted sorted(iterable[,key,reverse]) Returns a new list of sorted items in iterable.
reversed reversed(iterator) Reverses an iterator.
enumerate enumerate(sequence, Returns an enumerate object.
start=0)
zip zip(*iterables) Returns an iterator that aggregates items from each
iterables.
map map(function, iterable,...] Returns iterator that applies function to each item of
iterables.
filter filter(function, iterable) Returns an iterator from elements of iterable for
which function returns true.
iter iter(object[,sentinel]) Converts an iterable into an iterator.
Commonly Used Python List Functions
1. len()
The Python list method len() returns the size(number of items) of the list by calling the list
object’s own length method. It takes in a list object as an argument and doesn’t have a side
effect on the list.
• Syntax: len(s)
2. list()
list() is actually a Python built-in class that creates a list out of an iterable passed as an
argument. As it will be used a lot throughout this tutorial, we will take a quick look at what
this class offers.
• Syntax: list([iterable])
3. range()
The Python list function range() takes in some integers as arguments and generates a list of
integers.
• Syntax: range([start,]stop[,step])
4. sum()
The Python sum() function adds all items in an iterable and returns the result.
• Syntax: sum(iterable[,start])
5. min()
The Python min() function returns the smallest item in a sequence.
• Syntax: min(iterable[,key, default])
6. max()
The Python max() function returns the highest item in a sequence.
• Syntax: max(iterable[,key, default])
7. sorted()
The Python sorted() method returns a new sorted list of items from an iterable.
• Syntax: sorted(iterable[,key,reverse])
8. reversed()
The Python reversed() function returns a reverse iterator in which we can request the next
value or iterate through until we hit the end.
• Syntax: reversed(iterator)
9. enumerate()
The Python enumerate() function returns an enumerate object in which we can request the
next value or iterate through until we hit the end.
• Syntax: enumerate(sequence, start=0)
10. zip()
The Python zip() function returns an iterator that contains an aggregate of each item of the
iterables.
• Syntax: zip(*iterables)
11. map()
The Python map() function maps a function to each item of iterables and returns an iterator.
• Syntax: map(function, iterable,...]
12. filter()
The Python filter() method constructs an iterator from the items of iterables that satisfy a
certain condition
• Syntax: filter(function, iterable)
13. iter()
The Python iter() function converts an iterable into an iterator in which we can request the
next value or iterate through until we hit the end.
Syntax: iter(object[,sentinel])

Other Python List Built-in 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

Python dictionary, the implementation

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

Inside the CPython, dictionary is a C structure, PyDictObject:


structPyDictObject{
PyObject_HEAD
Py_ssize_tma_fill;/* # Active + # Dummy */
Py_ssize_tma_used;/* # Active */
Py_ssize_tma_mask;

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.

Key-Sharing and Ordered Dict

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']

Dictionary Implementation using Hash Tables


Example for the below dictionary:

d = {'banana':'yellow', 'grapes':'green', 'apple':'red'}

used to store as:

entries = [['--', '--', '--'],


[-5850766811922200084, 'grapes', 'green'],
['--', '--', '--'],
['--', '--', '--'],
['--', '--', '--'],
[2247849978273412954, 'banana', 'yellow'],
['--', '--', '--'],
[-2069363430498323624, 'apple', 'red']]
nstead, in the new dict() implementation the data is now being organized in a dense table
referenced by a sparse table of indices as follows:
indices = [None, 1, None, None, None, 0, None, 2]
entries = [[2247849978273412954, 'banana', 'yellow']
[-5850766811922200084, 'grapes', 'green'],
[-2069363430498323624, 'apple', 'red']]
Few mistakes when using Python dictionary

Usually, A dictionary is a collection which is unordered, changeable and indexed. In


Python, dictionaries are written with curly brackets, and they have keys and values. Each
key-value pair in a Dictionary is separated by a ‘colon’, whereas each key is separated by a
‘comma’.

my_dict ={1: 'Geeks', 2: 'For', 3:'Geeks'}

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.

my_dict ={1: 'Geeks', 2: 'For', 3:'Geeks'}

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’}]

c.Identify common syntactical errors when working with dictionary

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.

Using the Wrong Indentation

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:

$ tabs 4# Sets the shell tab width to 4 spaces


$ cat -n indentation.py
1 # indentation.py
2 def foo():
3 for i in range(10)
4 print(i)
5 print('done')
6
7 foo()

$ tabs 8# Sets the shell tab width to 8 spaces (standard)


$ cat -n indentation.py
1 # indentation.py
2 def foo():
3 for i in range(10)
4 print(i)
5 print('done')
6
7 foo()

$ tabs 3# Sets the shell tab width to 3 spaces


$ cat -n indentation.py
1 # indentation.py
2 def foo():
3 for i in range(10)
4 print(i)
5 print('done')
6
7 foo()
Activity 8
8.a) Identify use cases and solve using arrays
What is an Array?
An array is a collection of items of same data type stored at contiguous memory
locations.
This makes it easier to calculate the position of each element by simply adding an offset to
a base value, i.e., the memory location of the first element
element of the array (generally denoted
by the name of the array). The base value is index 0 and the difference between the two
indexes is the offset.
For simplicity, we can think of an array as a fleet of stairs where on each step is placed a
value (let’s
’s say one of your friends). Here, you can identify the location of any of your
friends by simply knowing the count of the step they are on.
Remember: “Location of next index depends on the data type we use”.

Use cases and solve using arrays.

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

each element in an array.

Use Case

We have four buttons on a page.


e. We need to attach an event listener to all of the buttons to

make some jazz happen when one is clicked.


We will need to grab those buttons on the page and send them through .forEach() to solve our

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

the .forEach() method.

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

something cooler than logging the index to the console.

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

element in the array to reduce it to a single value.

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

accumulator and currentValue.

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

provided function on every element in the array.


Use Case

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

new property for the group rights.

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

data the user is requesting.

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

with a truthy value.

Use Case

We will reference our use case for the .map() method. We need to do a quick check on our

data to see if a particular user group has a certain property.


Thanks for reading! If you’d like to hear more of my rambles about code, consider giving me a

follow on Twitter!

Example 1. Common Errors

// 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

int[ ] myFunction( ); // cannot return an entire array


int* myFunction( ); // this is OK

Example 2. Errors in Reading Arrays

// Examples in reading input


charsomeString[11]; // holds up to 10 characters plus the null character

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

cin.getline(someString,11); // reads at most 10 characters or until end of line


// inserts null character at end
// if the line contains 9 or less characters, the new line character is removed
// if the line contains more than 9 characters, the extra characters (if any) and the newline
// are kept.

cin.get(someString,11); // reads at most 10 characters or until end of line


// inserts null character at end
// Unlike getline above, the new line character is never removed.

cin.get(someString,11,'#'); // reads at most 10 characters or until the character '#' is found

// to handle getting one line of input, even if it is too long


// ignoring the extra characters (if any)
cin.get(someString, 11);
cin.ignore(200,'\n'); // ignore up to 200 characters but stop at the first newline is less than
200
// assumes that there will be less than 200 characters extra on this line.

Type Mismatch (Run-time Error ’13’), When Adding (Concatenating) Strings


Application-Defined or Object-Defined Error (Run-Time error ‘1004’) When Referencing
Ranges Using the String Notation “A1:B1”
Getting Incorrect Results When Adding (Concatenating) Strings in a Loop
Contents [hide]
Type Mismatch (Run-time Error ’13’), When Adding (Concatenating) Strings:
Application-Defined or Object-Defined Error (Run-Time error ‘1004’) When Referencing
Ranges Using the String Notation “A1:B1”:
Getting Incorrect Results When Adding (Concatenating) Strings in a Loop:

Type Mismatch (Run-time Error ’13’), When Adding (Concatenating) Strings:


You might be attempting to make the string “Data10” by adding the string “Data” and
the number 10, and suddenly a msgbox shows up saying: Type Mismatch (Run-time Error
’13’). The reason is that strings can only be added (Concatenated) with another string. You
can’t add a string with another data type. The following examples will all cause the Type
Mismatch (Run-time error ’13’) exception:

Sub Example1()

Dim strTemp As String

Dim intTemp As Integer

intTemp = 10

'Type Mismatch Error

strTemp = "Data" + intTemp

End Sub

Sub Example2()

Dim strTemp As String

'Type Mismatch Error

strTemp = "Data" + 10

End Sub

Sub Example3()

Dim strTemp As String

'Type Mismatch Error

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.

• Some programs might have thousands or millions of lines and to manage


such programs it becomes quite difficult as there might be too many of
syntax errors or logical errors present in the program, so to manage such
type of programs concept of modular programming approached.
• Each sub-module contains something necessary to execute only one aspect of the desired
functionality.
• Modular programming emphasis on breaking of large programs into small problems to
increase the maintainability, readability of the code and to make the program handy to make
any changes in future or to correct the errors.

Points which should be taken care of prior to modular program development:

1. Limitations of each and every module should be decided.


2. In which way a program is to be partitioned into different modules.
3. Communication among different modules of the code for proper execution of the entire
program.

Advantages of Using Modular Programming Approach –

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.

Print the given 3 string after modifying and concatenating

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:

Input: how are you


Output\: h*ware$ou

Input: geeks for geeks


Output: g**ksfor$ee$$

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

// CPP program to modify the given strings


#include <iostream>
#include <string.h>
using namespace std;

// Function to modify the given three strings


string modifyStr(string str1, string str2, string
str3)
{
// Modifying first string
for (int i = 0; i < str1.length(); i++) {
if (str1[i] == 'a' || str1[i] == 'e' ||
str1[i] == 'i' || str1[i] == 'o' ||
str1[i] == 'u')
str1[i] = '*';
}
// Modifying third string
for (int i = 0; i < str3.length(); i++) {
if (str3[i] != 'a' && str3[i] != 'e' &&
str3[i] != 'i' && str3[i] != 'o' &&
str3[i] != 'u')
str3[i] = '$';
}
// Concatenating the three strings
return (str1 + str2 + str3);
}
// Driver code
int main()
{
string str1 = "how";
string str2 = "are";
string str3 = "you";
cout << modifyStr(str1, str2, str3);
return 0;
}
Activity 10

10)a.Identify and present pros and cons of modules and packages

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.

Example of Python Module:


import math
from math import pow
pow(2,8)
print(pow)
What are Python Packages?
A package is the form of a collection of tools which helps in the initiation of the code. A
python package acts as a user-variable interface for any source code. This makes a python
package work at a defined time for any functionable code in the runtime.
Example of Python Package:
import math
print("math package")
Differences between Python Modules and Packages
1. A package holds the file __init__.py for every user-oriented code. But this does not apply
to modules in runtime for any user-specific codes.
2. A module is a file containing Python code in run time for a user-specific code. A package
also modifies the user interpreted code in such a way that it gets easily functioned in the run
time.
A python “module” consists of a unit namespace, with the locally extracted variables. And
some parsed functions as:
Constants and variables
Class definitions of properties
Really any old value or new one.
A module usually corresponds to a single file.
A debugging tool in the user interface library.
There are a few generally used tools that help the coder build a new platform using the
modules for a good execution of codes. This installs and distributes packages all over the
library in runtime also.

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.

Understanding the differences between Python Modules and Packages


A Package consists of the __init__.py file for each user-oriented script. However, the same
does not apply to the modules in runtime for any script specified to the users.
A module is a file that contains a Python script in runtime for the code specified to the users.
A package also modifies the user interpreted code in such a manner that it gets easily
operated in the runtime.
A python "module" contains a unit namespace, with the variables that are extracted locally
along with some parsed functions like:

Constants and Variables


Any old or new value
Class definitions of properties
A module generally corresponds to a single file
A debugging tool in the user interface library.
Activity 11
11)a. Identify the Applications of Pandas

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.

7. Natural Language Processing (NLP):

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.

10. Big Data:

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.

b.perform data analysis using pandas module on a data set such as

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.

We can analyse data in pandas with:

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.

Code #1: Creating Series


# Program to create series

# Import Panda Library

import pandas as pd

# Create series with Data, and Index

a = pd.Series(Data, index = Index)

Here, Data can be:


1. A Scalar value which can be integer Value, string
2. A Python Dictionary which can be Key, Value pair
3. A ND array
Note: Index by default is from 0, 1, 2, …(n-1) where n is length of data.

Code #2: When Data contains scalar values

# Program to Create series with scalar values

# Numeric data

Data =[1, 3, 4, 5, 6, 2, 9]

# Creating series with default index values

s = pd.Series(Data)

# predefined index values

Index =['a', 'b', 'c', 'd', 'e', 'f', 'g']

# Creating series with predefined index values

si = pd.Series(Data, Index)

Output:
Scalar Data with default
de Index

Scalar Data with Index

Code #3: When Data contains Dictionary

# Program to Create Dictionary series

dictionary ={'a':1, 'b':2, 'c':3, 'd':4, 'e':5}

# Creating series of Dictionary type

sd = pd.Series(dictionary)

Output:
Dictionary type data

Code #4:When Data contains Ndarray

# Program to Create ndarray series

# Defining 2darray

Data =[[2, 3, 4], [5, 6, 7]]

# Creating series of 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

# Program to Create DataFrame


# Import Library

import pandas as pd

# Create DataFrame with Data

a = pd.DataFrame(Data)

Here, Data can be:


1. One or more dictionaries
2. One or more Series
3. 2D-numpy Ndarray

Code #2: When Data is Dictionaries

# Program to Create Data Frame with two dictionaries

# Define Dictionary 1

dict1 ={'a':1, 'b':2, 'c':3, 'd':4}

# Define Dictionary 2

dict2 ={'a':5, 'b':6,


':6, 'c':7, 'd':8, 'e':9}

# Define Data with dict1 and dict2

Data = {'first':dict1, 'second':dict2}

# Create DataFrame

df = pd.DataFrame(Data)

Output:
DataFrame with two dictionaries

Code #3: When Data is Series

# Program too create Dataframe of three series

import pandas as pd

# Define series 1

s1 = pd.Series([1, 3, 4, 5, 6, 2, 9])

# Define series 2

s2 = pd.Series([1.1, 3.5, 4.7, 5.8, 2.9, 9.3])

# Define series 3

s3 = pd.Series(['a', 'b', 'c', 'd', 'e'])

# Define Data

Data ={'first':s1, 'second':s2, 'third':s3}

# Create DataFrame

dfseries = pd.DataFrame(Data)

Output:

DataFrame with three series


Activity 12
12a. Identify use cases on files concept 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.
Let’s take an example to make a cup of tea,
Step 1: Start
Step 2: Take some water in a bowl.
Step 3: Put the water on a gas burner.
Step 4: Turn on the gas burner
Step 5: Wait for some time until the water is boiled.
Step 6: Add some tea leaves to the water according to the requirement.
Step 7: Then again wait for some time until the water is getting colorful as tea.
Step 8: Then add some sugar according to taste.
Step 9: Again wait for some time until the sugar is melted.
Step 10: Turn off the gas burner and serve the tea in cups with biscuits.
Step 11: End
Here is an algorithm for making a cup of tea. This is the same for computer science problems.
There are some basics steps to make an algorithm:
1. Start – Start the algorithm
2. Input – Take the input for values in which the algorithm will execute.
3. Conditions – Perform some conditions on the inputs to get the desired output.
4. Output – Printing the outputs.
5. End – End the execution.
Let’s take some examples of algorithms for computer science problems.
Example 1. Swap two numbers with a third variable
Step 1: Start
Step 2: Take 2 numbers as input.
Step 3: Declare another variable as “temp”.
Step 4: Store the first variable to “temp”.
Step 5: Store the second variable to the First variable.
Step 6: Store the “temp” variable to the 2nd variable.
Step 7: Print the First and second variables.
Step 8: End

12b. Explore regular expressions and present how they can be used for file anipulation

Text Manipulation Using Regular Expressions


Abstract—In this paper we are proposing a proficient approach of using flat files or synthetic
files as database. Realizing that there are much of disadvantages of using text file as a
database, in this literature we are striving to reduce some specific hindrances with the help of
regular expressions (regex). Regular expression is therefore an unbelievable powerful
language which is no longer just for the programmers rather it is showing up in all sorts of
places today. In this paper, we are using regex to recommend a productive method of data or
text manipulation in the flat files. Hence an improved data manipulation procedure in the text
file can lay a huge impact in the path of up gradation of the flat file system.
I. INTRODUCTION
In this recent technological world, we are all being accustomed with all types of advanced
techniques. Among all these advanced techniques we have become quite aware about
database management system.
Activity 13
13)a. compare and contrast error and exception
Summary
• Types of program errors
• Syntax, semantic, and logical errors
• Compile time and runtime errors
• Test drivers
• Debugging techniques
• Exception handling
• The most common types of exceptions
• The throws clause and the throw statement
• Catching exceptions by means of the try-catch construct
• Propagation of exceptions
• Exceptions when reading from a file
10.1 Types of program We distinguish between the following types of errors:
1. Syntax errors: errors due to the fact that the syntax of the language is not respected.
2. Semantic errors: errors due to an improper use of program statements.
3. Logical errors: errors due to the fact that the specification is not respected.
From the point of view of when errors are detected, we distinguish:
1. Compile time errors: syntax errors and static semantic errors indicated by the compiler.
2. Runtime errors: dynamic semantic errors, and logical errors, that cannot be detected by the
compiler
(debugging).
10.2 Syntax errors
Syntax errors are due to the fact that the syntax of the Java language is not
10.2 Syntax errors
Syntax errors are due to the fact that the syntax of the Java language is not respected.
Let us see some examples of syntax errors.
Example 1: Missing semicolon:
int a = 5 // semicolon is missing
Compiler message:
Example.java:20: ’;’ expected
int a = 5
Example 2: Errors in expressions:
x = ( 3 + 5; // missing closing parenthesis ’)’
y = 3 + *10.3 Semantic errors
Semantic errors indicate an improper use of Java statements.
Let us see some examples of semantic errors.
Example 1: Use of a non-initialized variable:
int i;
i++; // the variable i is not initialized
Example 2: Type incompatibility:
int a = "hello"; // the types String and int are not compatible
Example 3: Errors in expressions:
String s = "...";
int a = 5 - s; // the - operator does not support arguments of type String 5; // missing argument
b
etStrin x; // Strin is not defined
system.out.println("hello"); // system is not defined
String s;
s.println(); // println is not a method of the class String
Example 5: Array index out of range (dynamic semantic error)
int[] v = new int[10];
v[10] = 100; // 10 is not a legal index for an array of 10 elements
The array v has been created with 10 elements (with indexes ranging from 0 to 9), and we are
trying to access
the element with index 10, which does not exist. This type of error is not caught during
compilation, but causes
an exception to be thrown at runtime.
10.5 logic al errors
Logical errors are caused by the fact that the software specification is not respected. The
program is compiled
and executed without errors, but does not generate the requested result.
Let us see some examples of logical errors:
Example 1: Errors in the performed computation:
public static int sum(int a, int b) {
return a - b ;
}
// this method returns the wrong value wrt the specification that requires
// to sum two integers
EString s = br.readLine();
while (s != null) {

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:

In order to perform a test that is complete, we should follow some guidelines:


• verify each functionality (each method);
• perform the tests according to a specific order (the order of method application is often
important);
• ensure that each statement is executed at least once (for example, when we have a
conditional statement,
we have to perform the test for various configurations of the input, in such a way that the
boolean condition
becomes respectively true and false);
• detect a10.7 Techniques for detecting errors (debugging)
If the testing phase signals the presence of logical errors, or if we are not able to detect the
cause for a runtime
error, it is necessary to debug the program.
There are two ways in which we can obtain information that is helpful for debugging a
program:
1. by inserting output statements in the code;
2. by executing the program by means of a debugger.
10.8 Debugging by inserting output statements
This debugging technique is based on inserting in suitable positions of the source code
statements that print
the content of variables that could contain wrong values causing an error.
Example:
int a, b, x;
a = 5;
b = Integer.parseInt(kb.readLine()); // reading of b
... // statements that do not change b
x = a/b;
To debug this program statement we can verify, by printing the value of b on the screen, that
the error occurs
when the variable b has value 0.
°c Diego Calvanese Lectnd test special cases (for example, an empty file as input to a method
that reint a, b, x;
a = 5;
b = Integer.parseInt(kb.readLine()); // reading of b
... // statements that do not change b
System.out.println("b = " + b);
x = a/b;
Once the causes for the error have been identified and corrected, the print statements can be
removed before
closing the debugging session.
Note: If it is necessary to explore the content of objects, rather than of simple variables of
primitive data types,we can make use of the toString() method, which provides information
on the content of the object. We could also redefine toString() so as to simplify the reading of
the state of the object during debugging.

You might also like