100% found this document useful (1 vote)
127 views50 pages

Python Notes 1

The document discusses the process of solving problems using computers including understanding the problem, analyzing it, developing a solution, and coding and implementation. It also covers tools for designing programs like algorithms, flowcharts and decision tables. Debugging techniques and types of errors are explained.

Uploaded by

zagirakhushua
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
100% found this document useful (1 vote)
127 views50 pages

Python Notes 1

The document discusses the process of solving problems using computers including understanding the problem, analyzing it, developing a solution, and coding and implementation. It also covers tools for designing programs like algorithms, flowcharts and decision tables. Debugging techniques and types of errors are explained.

Uploaded by

zagirakhushua
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 50

Python Notes

Planning the computer program


A computer performs many tasks exactly in the same manner as it is told
to do. This places responsibility on the user to instruct the computer in a
correct and precise manner, so that the machine is able to perform the
required job in a proper way. A wrong or ambiguous instruction may
sometimes prove disastrous.
In order to solve a problem by the computer, one has to pass though
certain stages or steps. They are
1. Understanding the problem
2. Analyzing the problem
3. Developing the solution
4. Coding and implementation.

1. Understanding the problem - Understanding the problem can be easily


understood with the help of following Example:
Calculate the average grade for all students in a class.
You need to know: What input data/information is available ? What
does it represent ? What format is it in ? Is anything missing ? Do I
have everything that I need ? What output information am I trying to
produce ? What do I want the result to look like … text, a picture, a
graph … ? What am I going to have to compute ?

2. Analyzing the problem: After understanding thoroughly the problem to


be solved, we look different ways of solving the problem and evaluate
each solution. The idea here is to search an appropriate solution to the
problem under consideration.

3. Developing the solution: Here the overview of the sequence of


operations that was the result of analysis stage is expanded to form a
detailed step by step solution to the problem under consideration. This is
done with the help of algorithm, pseudo code and flowcharts.

4. Coding and implementation: The last stage of the problem solving is


the conversion of the detailed sequence of operations into a language
that the computer can understand. Here each step is converted to its
equivalent instruction or instructions in the computer language that has
been chosen for the implantation.
Program Design
To produce an effective computer program, it is necessary to find the
logical solution of a problem and write every instruction in the correct
sequence. However, the instruction sequence or the logic of the program
may be very complex. Hence, before writing its code we must design the
program. We can use many tools for the designing of a computer
program. Some of the tools which can be used to design a program are:
Algorithm, flowchart, decision table, pseudo code etc.

Algorithm: The term algorithm refers to the logic of the program. It is a


step by step description of how to arrive at a solution to a given problem.

The characteristics of an Algorithm are as follow:


1. Each instruction should be precise and unambiguous.
2. No instruction should repeat infinitely.
3. It should give the correct result at the end.

Advantages of an algorithm
1. It is a step-by-step representation of a solution to a given problem
,which is very easy to understand
2. It has got a definite procedure.
3. It is independent of programming language.
4. It is easy to debug as every step got its own logical sequence.

Disadvantages of an algorithm
1. It is time consuming process.
2. It is difficult to show branch and looping in the algorithm.

Example of algorithms: Write an algorithm to find area of a rectangle.


Step 1: Start
Step 2: Take length and breadth and store them as L and B?
Step 3: Multiply by L and B and store it in area
Step 4: Print area
Step 5: Stop
Flow chart
Flowchart is a program designing tool in which standard graphical
symbols are used that illustrates the sequence of operations to be
performed to solve a given problem. In other words, it is a pictorial
representation of an algorithm or a process. It is also known as the Flow
Diagram. In a Flowchart the commands or statements of algorithm are
shown as a special type of shapes. Different types of shapes are used
for different types of statements, and within those figures, that statement
is written briefly. These shapes are connected with each other with the
help of arrows, which show the flow of operation or processing.

The basic Symbol used in making flowcharts are as follows

1. Terminal :- The Oval is used to show the beginning and end of the
Flowchart. It is necessary that Flowchart has a Start and Stop terminal.
A flowchart should have only one Start and one Stop terminal.

2. Input/Output :- Parallelogram shape is used to show the input and


output operation in the algorithm or program. For example, if there is a
need to get input from the keyboard, disk, tape, or any other device in
the program, then use the Read or Input inside this box.

3. Processing :- Rectangular shape is used to show the processing


section of an algorithm. In it, the formulas and instructions are written,
through which the data is being processed. When processing has more
than one instruction, then they are written in the same box.

4. Decision :-The Rhombus/Diamond is used to show the decision


section. It is used in the place where we want to perform certain task
only when a particular condition holds true or false. In this case for each
possible situation arising, different flow-lines are used to represent the
flow of execution.

5. Flow-lines :- The arrow shape is used to show the flow lines, these are
used to connect different shapes such as input output box, terminal,
decision box, and connector etc. It is also used to show the flow of the
execution of the program. The flow of execution of the program is
determined by the direction of arrow mark on the flow line.
6. Connectors :- The spherical / Circle shapes are used to represent the
connectors. These are used when the flowchart is so large that it cannot
come to one page or the flow line of flowchart starts cutting each other.

Example : Create a flowchart to find the sum of two numbers

Decision Table- Decision table, also known as the logic table is a


powerful graphical tool used to analyze and represent complex
proceeding logic. It uses a tabular format to represent the various
actions to be taken for various combination of conditions. The decision
tables are extremely useful when a program involve a large number of
conditions.

Condition Stub : This section lists all the possible conditions which could
apply to a particular problem.

Condition entry : This section of the decision table contains the different
combination of the conditions given in the condition stub , each
combination is referred as a “Rule” its value is generally represented as
Y/N.
Action Stub : This section lists the actions resulted from a given set of
conditions.

Action Entry : This section shows the actions to be taken for each
combination of conditions.

Advantages of Decision Table :


1. Easier to draw and modify in comparison to algorithm and flowchart.
2. Decision rules are clearly structured.
3. It helps to better understand the decision logic of a problem.

Disadvantages –
1. It is used only for the representation of actions performed based upon
the various conditions. So, it is difficult to write a complete program on
the basis of decision table.
2. Decision tables are larger in size.
For example: In the following figure, the decision table calculates the
shipment cost in an online shop. The cost depends on the value of the
order, the weight of the parcel, and whether the shipment is to a foreign
country. If the order value is less than $500, and the parcel weight is less
than 3kg, and the shipment is to the same country, then the shipment
cost is $20. If any of these values evaluate to false, the system moves to
the next row. If all rows evaluate to false, the system returns the default
value of $60 for the shipment cost:
Decision table

Debugging and Error Types


De-bugging a program is the process of finding and resolving errors.
Debugging is an essential part of programming. Even for an experienced
programmer most codes will not work in the first attempt due to syntax
errors, mathematical errors and logical flaws. These errors or bugs have
to be corrected before your program would yield desired results.
There are 3 kinds of errors (bugs) in the code:

1. Syntax errors: The code does not follow the rules of the language; for
example, a single quote is used where a double quote is needed; a
colon is missing; a keyword is used as a variable name. ¨

2. Runtime errors: In this case, your code is fine but the program does
not run as expected (it “crashes”). For example, if your program is meant
to divide two numbers, but does not test for a zero divisor, a run-time
error would occur when the program attempts to divide by zero

3. Logic errors: These can be the hardest to find. In this case, the
program is correct from a syntax perspective; and it runs; but the result
is unanticipated or outright wrong. For example, if your program prints
“5+2 = 3”.

Basic Debugging Techniques


Although there is no precise procedure for fixing all bugs, there are a
number of useful strategies that can reduce the debugging effort. Below
are several useful strategies to help with this.

● Incremental program development. One of the most effective


ways to localize errors is to develop the program incrementally,
and test it often, after adding each piece of code. It is highly likely
that if there is an error, it occurs in the last piece of code that you
wrote. With incremental program development, the last portion of
code is small; the search for bugs is therefore limited to small code
fragments.
● Use debuggers- Debugger is a tool that help to identify and
remove bugs. Through this tool we can set breakpoints in the
program to check the results of a particular section of the program.
● Backtracking- One option is to start from the point where to
problem occurred and go back through the code to see how that
might have happened.
Documentation
All large software development projects, irrespective of application,
generate a large amount of associated documentation. The
documents associated with a software project and the system
being developed have a number of associated requirements:

1. They should act as a communication medium between


members of the development team.
2. They should be a system information repository to be used by
maintenance engineers.
3. They should provide information for management to help them
plan, budget and schedule the software development process.
4. Some of the documents should tell users how to use and
administer the system.
Generally we can divide the documentation produced into two
classes:
1. Process documentation : These documents record the process
of development and maintenance. Plans, schedules, process
quality documents and organizational and project standards are
process documentation.
Process documentation falls into a number of categories:
1. Plans, estimates and schedules . These are documents
produced by managers which are used to predict and to
control the software process.
2. Reports : These are documents which report how resources
were used during the process of development.
3. Standards : These are documents which set out how the
process is to be implemented. These may be developed from
organizational, national or international standards
4. Working papers : These are often the principal technical
communication documents in a project. They record the
ideas and thoughts of the engineers working on the project,
are interim versions of product documentation, describe
implementation strategies and set out problems which have
been identified.
5. Memos and electronic mail messages : These record the
details of everyday communications between managers and
development engineers.

2. Product documentation: This documentation describes the


product that is being developed. Product documentation includes
user documentation which tells users how to use the software
product and system documentation which is principally intended
for maintenance engineers.
The main documents included in product documentation are :
installation guide, reference manual, system administration guide,
functional description, validation document etc.

Programming Methodology
When programs are developed to solve real-life problems like
inventory management, payroll processing, student admissions,
examination result processing, etc. they tend to be huge and
complex. The approach to planning for software development and
controlling the development process is called programming
methodology.

Types of Programming Methodologies - There are many types of


programming methodologies prevalent among software
developers, two of the most common programming methodologies
are as follow :
1. Procedural Programming : Problem is broken down into
procedures, or blocks of code that perform one task each. All
procedures taken together form the whole program. It is
suitable only for small programs that have low level of
complexity. Example: For a calculator program that does
addition, subtraction, multiplication, division, square root and
comparison, each of these operations can be developed as
separate procedures. In the main program each procedure
would be invoked on the basis of user’s choice. This
methodology is suitable for solving small problems.
2. Object-oriented Programming : Here the solution revolves
around entities or objects that are part of problem. The
solution deals with how to store data related to the entities,
how the entities behave and how they interact with each
other. Example: If we have to develop a payroll management
system, we will have entities like employees, salary
structure, leave rules, etc. around which the solution must be
built. Software developers may choose one or a combination
of more than one of these methodologies to develop a
software.
Note that in each of the methodologies discussed, problem has to be
broken down into smaller units. To do this, developers use any of the
following two approaches: Top-down approach and Bottom-up
approach

● Top-down or Modular Approach : In this approach the problem is


broken down into smaller units, which may be further broken down
into even smaller units. Each unit is called a module. Each module
is a self-sufficient unit that has everything necessary to perform its
task. The following illustration shows an example of how you can
follow modular approach to divide the problem into different
modules while creating a program.

Advantages of top-down approach:


1. Using this approach, the problem solving process of big problem
becomes easy.
2. This approach utilize the resources in a proper manner
according to the project.
3. Testing and debugging is easier and efficient.
4. In this approach, project implementation is smoother and
shorter.
5. This approach is good for detecting and correcting time delays.

Disadvantages of Top- Down approach


1. This approach is not suitable for solving highly complex
problems.
2. This approach is less flexible (updation in the program) in
comparison to bottom up approach.

● Bottom-up Approach - In bottom-up approach, system


design starts with the lowest level of components, which are
then interconnected to get higher level components. This
process continues till a hierarchy of all system components is
generated. However, in real-life scenario it is very difficult to
know all lowest level components at the beginning.

Advantages of Bottom up Approach


1. Flexible: This approach is very flexible. Addition of new features and
modification of features is easier.
2. Reusability: As the parts of the program are created independent,
therefore the possibility of reusing them increases.
3. Reliability: This approach is more reliable, because in this case each
part of the program is independently created and tested first then it is
integrated.
4. Lower Cost: In this approach the components are reused therefore the
cost of the software development decreases.
Disadvantages of Bottom Up Approach
1. It is difficult to evaluate the progress of the project in this approach.
2. The idea about the final product is obtained at end only.

Introduction to python
● Python is a high level general purpose Programming language.
● It was created by Guido van Rossum, and released in 1991.
● Python works on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc).
● Python has a simple syntax similar to the English language.
● It is an object-Oriented Language.
● Python is case sensitive.
● It does not have a command terminator.
● It uses indentation.
● Single line comments are written using #.
● Multi line comments are written using ‘’’.
● Python runs on an interpreter system, meaning that code can be
executed as soon as it is written.
● Extension for a python file is .py and extension for python
notebook is .ipynb

Installing python and code editor


Latest version of Python can be downloaded from the official website -
https://www.python.org/downloads/

There are multiple code editors to code python:-


Pycharm
Python shell
Jupyter notebook
Google colab

Elements of python program

Atom - The basic building blocks of Python code, including identifiers,


literals, and keywords. The smallest part of code which can not be
divided further.

Identifiers: Names used to identify variables, functions, classes, etc.


They must follow certain rules:
Can contain letters (a-z, A-Z), digits (0-9), and underscores (_).
Must start with a letter (a-z, A-Z) or an underscore (_).
Case-sensitive.

Examples of identifiers:
variable_name
function_name
Class
module_name
_private_variable

Literals – constant values stored inside the python identifiers and


variables. They represent fixed values and can be of various types:
Numeric Literals: Representing numbers.
String Literals: Representing text.
Boolean Literals: Representing True or False.
None Literal: Representing the absence of a value.
Keywords - Reserved words that have special meanings in Python and
cannot be used as identifiers. There are 32 keywords in python.

Operators in Python

Operators are used to perform operations on the operands.


For example – 2 + 3 = 5, here 2 and 3 are operands and ‘ + ‘ is called
operator.
1. Arithmetic Operators:
These operators perform basic mathematical operations.

2. Comparison Operators:
These operators compare values and return a boolean (True or False)
result.
3. Logical Operators:
These operators perform logical operations and also return a boolean
result.

4. Assignment Operators:
These operators are used to assign values to variables.
5. Membership Operators:
These operators test whether a value is a member of a sequence (e.g., a
string, list, or tuple).

Conditional Statements
conditional statements carry out various calculations or operations
according to whether a particular Boolean condition is evaluated as true
or false.
Python supports three types of conditional statements:-
1. if
2. if-else
3. if-elif-else
Syntax for conditional statements
If statement:-
if(condtion):
Statement to be executed after fulfilling the condition

For if-else
if <conditional expression> :
Statement
else :
Statement

For If-elif-else
if <conditional expression>
Statement
elif:<conditional expression>
Statement
else
Statement

Loops in python
Loops allow us to execute a statement multiple times to avoid writing the
same code again.
Python supports following types of loops:-
1. While loop
2. For Loop
3. Nested loops
While Loop
In python, a while loop is used to execute a block of statements
repeatedly until a given condition is satisfied. And when the condition
becomes false, the line immediately after the loop in the program is
executed.
Syntax-
while expression:
statement(s)

For Loop
• For loops are used for sequential traversal.
• It can be used to iterate over a range and iterators.
Syntax-
for iterator_var in sequence:
statements(s)

Nested Loop
Nested loops in Python are loops within loops. This means that one loop
is nested inside another loop. Nested loops are commonly used when
working with 2D arrays, matrices, or multi-level data structures, where
you need to iterate over rows and columns, or traverse through nested
collections of data.

Syntax of nested loop-


for outer_variable in outer_sequence:
for inner_variable in inner_sequence:
# Code block to be executed for each combination of outer and
inner variables

Loop Terminating statements


1. break Statement:
The break statement is used to terminate the execution of a loop
prematurely. When the break statement is encountered inside a loop, the
loop immediately exits, and the program continues with the next
statement after the loop.
Example :-
for i in range(5):
if i == 3:
break (exit the loop when i equals 3)
print(i)

2. continue Statement:
The continue statement is used to skip the rest of the code inside a loop
for the current iteration and proceed to the next iteration of the loop.
Example:
for i in range(5):
if i == 2:
continue (skip the rest of the loop for i equals 2)
print(i)
In this example, when i equals 2, the continue statement is encountered.
As a result, the print statement and any subsequent code in the loop for
that iteration are skipped, and the loop proceeds to the next iteration.
3. pass Statement:
The pass statement is a null operation and is used when a statement is
required syntactically but you do not want to execute any code. It acts as
a placeholder and does nothing when executed.
Example:
for i in range(5):
pass (do nothing )

Strings

Strings in python are used to represent Unicode character values.


Python does not have a character data type; a single character is also
considered as a string.
We denote or declare the string values inside single quotes or double
quotes. To access the values in a string, we use the indexes and square
brackets.
Operations:
1. Concatenation: Joining two or more strings together using the +
operator.
string1 = "Hello"
string2 = "World"
concatenated_string = string1 + ", " + string2
Output: "Hello, World"

2. Repetition: Repeating a string multiple times using the * operator.


string = "Hello"
repeated_string = string * 3
Output: "HelloHelloHello"

3. Indexing: Accessing individual characters in a string using index


notation.
string = "Hello"
print(string[0])
Output: "H"
Negative indexing- print(string[-2]) #output “l”

4. Slicing: Extracting a portion of the string using slice notation.


string = "Hello, World!"
print(string[0:5])
Output: "Hello"

Methods

upper(): Converts the first character to uppercase


lower(): Converts string into lower case
count(): Returns the number of times a specified value occurs in a
string
find(): Searches the string for a specified value and returns the
position of where it was found, returns -1 if searched value is not found
index(): Searches the string for a specified value and returns the
position of where it was found, returns error if searched value is not
found
isalnum(): Returns True if all characters in the string are alphanumeric
isalpha(): Returns True if all characters in the string are in the alphabet
isnumeric(): Returns True if all characters in the string are numeric
join(): Converts the elements of an iterable into a string
lstrip(): Returns a left trim version of the string
partition(): Returns a tuple where the string is parted into three parts
replace(): Returns a string where a specified value is replaced with a
specified value
rsplit(): Splits the string at the specified separator, and returns a list
rstrip(): Returns a right trim version of the string
split(): Splits the string at the specified separator, and returns a list
startswith(): Returns true if the string starts with the specified value
strip(): Returns a trimmed version of the string
swapcase(): Swaps cases, lower case becomes upper case and
vice versa
title(): Converts the first character of each word to upper case
Note: All string methods returns new values. They do not change the
original string.

List

List is a collection data type in python. It is ordered and allows duplicate


entries as well. Lists in python need not be homogeneous, which means
it can contain different data types like integers, strings, and other
collection data types. It is mutable in nature and allows indexing to
access the members in a list.
To declare a list, we use the square brackets.
List is like any other array that we declare in other programming
languages. Lists in python are often used to implement stacks and
queues. The lists are mutable in nature. Therefore, the values can be
changed even after a list is declared.

Operations:
1. Indexing: Accessing individual elements in a list using index
notation.
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # Output: 1

2. Slicing: Extracting a portion of the list using slice notation.


my_list = [1, 2, 3, 4, 5]
print(my_list[1:4]) # Output: [2, 3, 4]

3. Concatenation: Combining two lists into one using the + operator.


list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2 # Output: [1, 2, 3, 4, 5, 6]

4. Repetition: Repeating a list multiple times using the * operator.


my_list = [1, 2]
repeated_list = my_list * 3 # Output: [1, 2, 1, 2, 1, 2]

Methods:
1. append(): Adds an element to the end of the list.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]

2. extend(): Extends the list by appending elements from another list.


list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]

3. insert(): Inserts an element at a specified position in the list.


my_list = [1, 2, 3]
my_list.insert(1, 10)
print(my_list) # Output: [1, 10, 2, 3]

4. remove(): Removes the first occurrence of a specified value from


the list.
my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list) # Output: [1, 3, 2]

5. pop(): Removes and returns the element at a specified index


(default is the last element).
my_list = [1, 2, 3]
popped_element = my_list.pop(1)
print(popped_element) # Output: 2

6. index(): Returns the index of the first occurrence of a specified


value in the list.
my_list = [1, 2, 3, 2]
index = my_list.index(2)
print(index) # Output: 1

7. count(): Returns the number of occurrences of a specified value in


the list.
my_list = [1, 2, 3, 2]
count = my_list.count(2)
print(count) # Output: 2

8. sort(): Sorts the elements of the list in ascending order (or with a
custom function).
my_list = [3, 1, 2]
my_list.sort()
print(my_list) # Output: [1, 2, 3]

9. reverse(): Reverses the elements of the list in place.


my_list = [1, 2, 3]
my_list.reverse()
print(my_list) # Output: [3, 2, 1]
10. clear(): Removes all elements from the list.
my_list = [1, 2, 3]
my_list.clear()
print(my_list) # Output: []

Tuple

A tuple is an immutable data type in python, almost similar to a list in


python in terms of indexing and having duplicate members. It is a
collection data type that stores python objects separated by commas.

#creating a tuple
a ('= python', 'programming')

#another approach
b = 'python' , 'programming'
print(a)
print(b)

Output:
('python' , 'programming')
('python' , 'programming')
Operations:
1. Indexing: Accessing individual elements in a tuple using index
notation.

my_tuple = (1, 2, 3)

print(my_tuple[0]) # Output: 1

2. Slicing: Extracting a portion of the tuple using slice notation.

my_tuple = (1, 2, 3, 4, 5)

print(my_tuple[1:4]) # Output: (2, 3, 4)

3. Concatenation: Combining two tuples into one using the +


operator.

tuple1 = (1, 2, 3)

tuple2 = (4, 5, 6)

concatenated_tuple = tuple1 + tuple2 # Output: (1, 2, 3, 4, 5, 6)

4. Repetition: Repeating a tuple multiple times using the * operator.

my_tuple = (1, 2)

repeated_tuple = my_tuple * 3 # Output: (1, 2, 1, 2, 1, 2)

Methods:

index(): Returns the index of the first occurrence of a specified value in


the tuple.
my_tuple = (1, 2, 3, 2)

index = my_tuple.index(2)

print(index) # Output: 1

Changing A Tuple

Even though tuples in python are immutable in nature, a nested object in


a tuple can be changed. Or in general, a tuple in python can be
reassigned with a different value.

a = (1,2,3,[4,5])

a[3][0] = 14

print(a)

Deleting A Tuple

Being an immutable data type, a tuple in python does not allow any

changes and it cannot even remove an element from a tuple after the

declaration. But there is a keyword ‘del’ which will delete the tuple

altogether.

a = (1,2,3,4,5)

del a

print(a)
Methods:
1. index(): Returns the index of the first occurrence of a specified value in the

tuple.

my_tuple = (1, 2, 3, 2)

index = my_tuple.index(2)

print(index) # Output: 1

2. count(): Returns the number of occurrences of a specified value in

the tuple.

my_tuple = (1, 2, 3, 2)

count = my_tuple.count(2)

print(count) # Output: 2

Dictionary

It is a collection data type just like a list or a set, but there are certain

features that make python dictionary unique. A dictionary in python is not

ordered and is changeable as well. We can make changes in a


dictionary unlike sets or strings which are immutable in nature.
Dictionary contains key-value pairs like a map that we have in other
programming languages. A dictionary has indexes. Since the value of
the keys, we declare in a dictionary are always unique, we can use them
as indexes to access the elements in a dictionary

Also, a dictionary does not have any duplicate keys. Although the value
elements in the key value pairs can contain duplicate values.

Declaring a Dictionary-

To declare a dictionary in python, we use the curly brackets. The keys


and values are separated with a colon and the pairs are separated with a
comma.

mydictionary { 'key1' : 'value1' , 'key2': 'value2' = , 'key3': 'value3'}

print(mydictionary)

Accessing an element

mydictionary { 1: 'programming' , 2: 'python' , = 3: 'data science'}

mydictionary[1]

#this will get the key value pair with the key 1.

mydictionary.get(1)

#this is another function which will serve the same purpose.

Replacing an element

mydictionary = { 1: 'programming', 2: 'python' , 3: 'data science'}

mydictionary[3] = 'artificial intelligence'


print(mydictionary)

#this will replace the value at key 3 to arti􀁺cial intelligence.

Removing an element

mydictionary = { 1:'programming' , 2 : 'python', 3: 'data science'}

del mydictionary[3]

print(mydictionary)

#this will remove the key value pair from the dictionary with the specified

Operations on a dictionary

clear() - removes all the elements from the dictionary.

a = { 1: 2 , 2: 3 , 3: 5}

a.clear()

print(a)

#you will get an empty dictionary as the output.

copy( ) – returns a copy of the dictionary.

a = {1:2, 2: 3, 3: 4}

b = a.copy()

print(b)
#b will be a copy of the dictionary a.

values( ) – returns all the values in a dictionary.

a = {1: 2, 2: 3, 3:4}

a.values( )

#this will get you the list of all the values in the dictionary.

update( ) – it updates the values of the dictionary with the speci􀁺ed key
value pairs.

a {= 1 : 2, 2: 3, 3: 5}

a.update({4: 6})

#this will update the dictionary with the speci􀁺ed key value pair.

fromkeys( ) – returns a dictionary with the speci􀁺ed keys and values.

a = {1: 'programming' , 2: 'data science'}

b = {1: 2, 2: 3, 3: 'python'}

a.Fromkeys(b)

#this will get the dictionary with the speci􀁺ed keys and values.

items( ) – returns the list for a tuple of each key value pair in the
dictionary.

a = {1: 'programming', 2; 'python'}


a.items()

#this will get the list of tuple for each key value pair.

keys( ) – returns a list containing all the keys in the dictionary.

a = { 1: 'programming' , 2 : 'python' , 3 : 'data science'}

a.keys()

#this will get the list of all the keys from the dictionary.

pop( ) – removes the element with the speci􀁺ed key.

a = { 1: 'programming' , 2: 'data science' , 3: 'python' }

a.pop(3)

#this will remove the value 'python' from the dictionary.

popitem( ) – removes the last inserted key values pair from the
dictionary.

a = { 1: 'programming' , 2: 'python' , 3: 'data science'}

a.popitem()

#this will remove the last inserted key value pair from the dictionary.

setdefault( ) – returns the value of the speci􀁺ed key, if not present insert
the

key with the speci􀁺ed value.


a = { 1: 'programming' , 2: 'python' }

a.setdefault(1, 'programming')

Functions in Python

Python Functions is a block of statements that return the specific task.


The idea is to put some commonly or repeatedly done tasks together
and make a function so that instead of writing the same code again and
again for different inputs, we can do the function calls to reuse code
contained in it over and over again.

Syntax:

def function_name(parameters):

#statements

A function can be called as a section of a program that is written once


and can be executed whenever required in the program, thus making
code reusability.

once defined, a function can be used any number of times at any point in
any of your codes. A function in Python may contain any number of
parameters or none.

Types of functions in python

❖ Python Built-in Functions


❖ Python User-defined Functions
❖ Python Lambda Functions
❖ Python Recursion Functions

Python Built-in Functions - The Python interpreter has a number of


functions that are always available for use. These functions are called
built-in functions.

For example, print() function prints the given object to the standard
output device (screen) or to the text stream file.

In Python 3.6, there are 68 built-in functions.

Python User-defined Functions - Functions that we define ourselves to


do a certain specific task are referred to as user-defined functions.We
can create our own functions based on our requirements.

Advantages of user-defined functions

1. User-defined functions help to decompose a large program into small


segments which makes the program easy to understand, maintain and
debug.

2. If repeated code occurs in a program. The function can be used to


include those codes and execute when needed by calling that function.

3. Programmers working on a large project can divide the workload by


making different functions.
Syntax

def function_name(argument1, argument2, ...) :

Statement_1

Statement_2

....

Example

def add_numbers(x,y):

sum = x + y

return sum

num1 = 5

num2 = 6

print("The sum is", add_numbers(num1, num2))

Output

The sum is 11

Python Lambda Functions


In Python, an anonymous function is a function that is defined without a
name. While normal functions are defined using the def keyword, in
Python anonymous functions are defined using the lambda keyword.

Lambda functions can have any number of arguments but only one
expression. The expression is evaluated and returned. Lambda functions
can be used wherever function objects are required.

Example

double = lambda x: x * 2

print(double(5))

#Output

10

In the above program, lambda x: x * 2 is the Lambda function. Here x is


the argument and x * 2 is the expression that gets evaluated and
returned.

What is recursion in Python?

Recursion is the process of defining something in terms of itself. A


physical world example would be to place two parallel mirrors facing
each other. Any object in between them would be reflected recursively.

Python Recursive Function


We know that in Python, a function can call other functions. It is even
possible for the function to call itself. These type of construct are termed
as recursive functions.

Example:

# An example of a recursive function to

# find the factorial of a number

def calc_factorial(x):

if x == 1 or x==0:

return 1

else:

return (x * calc_factorial(x-1))

num = 4

print("The factorial of", num, "is", calc_factorial(num))

In the above example, calc_factorial() is a recursive function as it calls


itself.

When we call this function with a positive integer, it will recursively call
itself by decreasing the number. Each function call multiples the number
with the factorial of number 1 until the number is equal to one.
Our recursion ends when the number reduces to 1. This is called the
base condition. Every recursive function must have a base condition that
stops the recursion or else the function calls itself infinitely.

scope of a variable.

The location where we can find a variable and also access it if required is
called the scope of a variable. A variable scope specifies the region
where we can access a variable.

It is of two types:-

● Global scope
● Local scope
Global Scope - In Python, a variable declared outside of the function or in
global scope is known as a global variable. This means that a global
variable can be accessed inside or outside of the function.

Example -

# declare global variable

message = 'Hello'

def greet():

print(message)

greet()

print(message)
Output -

Hello

Hello

Local Scope - When we declare variables inside a function, these


variables will have a local scope (within the function). We cannot access
them outside the function. These types of variables are called local
variables.

Example-

def greet():

# local variable

message = 'Hello'

print('Local', message)

greet()

# try to access message variable

# outside greet() function

print(message)

Output -

Local Hello

NameError: name 'message' is not defined


Python Modules

A document with definitions of functions and various statements written in Python is

called a Python module.

The focus is to break down the code into different modules so that there will be no or

minimum dependencies on one another.

We employ modules to divide complicated programs into smaller, more

understandable pieces. Modules also allow for the reuse of code.

Rather than duplicating their definitions into several applications, we may define our

most frequently used functions in a separate module and then import the complete

module.

Let's construct a module. Save the file as example_module.py after entering the

following.

# Here, we are creating a simple Python program to show how to create


a module.

# defining a function in the module to reuse it

def square( number ):

# here, the above function will square the number passed as the input

result = number ** 2

return result # here, we are returning the result of the function

How to Import Modules in Python?

In Python, we may import functions from one module into our


program.For this, we make use of the import Python keyword.
Using the import Python keyword and the dot operator, we may import a
standard module and can access the defined functions within it.

import example_module as em

result = em.square( 4 )

print("By using the module square of number is: ", result )

Here, ‘em’ is an alias word(short name) given to the module for easy
access.

Built-in Modules In Python

Built-in modules are written in C and integrated with python interpreter.

Each built-in module contains resources for certain specific


functionalities like Operating system management, disk input/output etc.

Python Package
Python Packages are a way to organize and structure your Python code

into reusable components. Think of it like a folder that contains related

Python files (modules) that work together to provide certain functionality.

Packages help keep your code organized, make it easier to manage and

maintain, and allow you to share your code with others. They’re like a

toolbox where you can store and organize your tools (functions and

classes) for easy access and reuse in different projects.

A package is a container that contains various functions to perform


specific tasks. For example, the math package includes the sqrt()
function to perform the square root of a number.
While working on big projects, we have to deal with a large amount of
code, and writing everything together in the same file will make our code
look messy. Instead, we can separate our code into multiple files by
keeping the related code together in packages.

Built in python packages


Packages that are pre-built in python. There are different packages to achieve

different tasks.

For web development - flask, django etc

For Machine learning - tensorflow, keras etc

For data analysis - Numpy, pandas, matplotlib etc

User - defined packages

As a programmer , we can store are functions in package so that we can reuse them.

Steps to create a python package-

● Create a Directory: Start by creating a directory (folder) for your

package. This directory will serve as the root of your package

structure.

● Add Modules: Within the package directory, you can add Python

files (modules) containing your code. Each module should

represent a distinct functionality or component of your package.

● Init File: Include an __init__.py file in the package directory. This

file can be empty or can contain an initialization code for your


package. It signals to Python that the directory should be treated

as a package.

● Subpackages: You can create sub-packages within your package

by adding additional directories containing modules, along with

their own __init__.py files.

● Importing: To use modules from your package, import them into

your Python scripts using dot notation. For example, if you have a

module named module.py inside a package named mypackage,

you would import it like this: from mypackage import module.

● Distribution: If you want to distribute your package for others to

use, you can create a setup.py file using Python’s setuptools

library. This file defines metadata about your package and

specifies how it should be installed.

Code Example

1. Create a directory named mypackage.

2. Inside mypackage, create two Python files: module1.py and

module2.py.

3. Create an __init__.py file inside mypackage (it can be empty).

4. Add some code to the modules.

5. Finally, demonstrate how to import and use the modules from the

package.

mypackage/

├── __init__.py

├── module1.py

└── module2.py

Code

We will create module 1 and module 2 , then use them with the package.

# module1.py

def greet(name):

print(f"Hello, {name}!")

# module2.py

def add(a, b):

return a + b

#third file

from mypackage import module1, module2

# Using functions from module1

module1.greet("Alice")

# Using functions from module2

result = module2.add(3, 5)

print("The result of addition is:", result)

That’s how we can create different modules into one package and use them later.

User input in python


User input means that we are able to ask the user to provide an input in
the program. Python stops executing when it comes to the input()
function, and continues when the user has given some input

Example-

a = input(“Enter your name”) # this will allow the user to write a string

#By default input() takes input as string. But we can specify the datatype
in which we want the input value.

Example-

Num = int(input(“Enter a number”)) #this will allow user to enter a


number.

File Handling in python

Python supports file handling and allows users to handle files i.e., to read
and write files, along with many other file handling options, to operate on

files. Python treats files differently as text or binary.

● Steps used during File Handling in Python.

● Opening a file to write.

● Appending and writing to a file.

● Closing a file

File Handling: Opening

you need to open file so that you can write to it. So to open a file in python

we use the following syntax-


object = open( file_name, mode)

The open function returns the instance of the file that you opened to work

on. It takes 2 primarily arguments, file_name and mode. There are four

different modes you can open a file to:

1. “r” = to read from a file.

2. “w” = to write to a file erasing completely previous data.

3. “a” = to append to previously written file.

4. “x” = to create a file.

Additional used modes to specify the type of 􀁺le is:

1. “t” = Text file, Default value.

2. “b” = binary file. For eg. Images.

For example:

fp = open(“my_file.png”, “rb”)

This will open a file named my_file.png in binary format.

Writing in File in Python

To write to a file first, you must open it in write mode and then you can

write to it. However, it is important to note that all previously written data

will be overwritten.
For this example let’s make a file name and write in it using python.

#file name - vgu.txt

fp open(“= vgu.txt”, “wt”)

for _ in range(10):

fp.write(“vgu is a platform for developing skills”)

fp.close()

To write to a file we first opened a file named vgu.txt and saved its

instance in variable fp. Now run a loop 10 times to write “vgu is a

platform for developing skills” in that file 10 times. Now for good

programming practice, you must close all the files that you opened.

One thing to note here is to write texts to a 􀁺le, you must open it in text

mode (“t”). If you are working with binary files use “b” while opening the

file.

Now let us write to a binary file, first thing to remember while writing to a

binary file is that data is to be converted into binary format before writing.

Moreover, binary data is not human-readable hence you cannot read it by

simply opening a file.

fp = open(“binaryFile”, “wb”)
Data = [1,2,3]

fp.write(bytearray(Data))

fp.close()

First, binaryFile is opened to write any data into it. Consider I have an array

of information to write to a file(in this case Data) then first i will convert it

into binary data by using function bytearray() so that data is converted into

binary format. Then, at last, I closed the file.

Appending to a File

Now, most of the times you will be writing to a file without destroying the

earlier contents. To write to a file while preserving previous content is

called appending to a file.

For this example let’s append to the same file that we already created.

Let’s append to vgu.txt

fp = open(“vgu.txt”, “at”)

for _ in range(5):

fp.write(“I am appending something to it!”)


fp.close()

In the above example, we opened a file named vgu.txt using append

mode. This tells python that do not overwrite data but start writing from

the last line. So, what it would do now is that after the ending lines it will

add “I am appending something to it!” 5 times. And then we have closed

that file.

Closing a File

Just use file_reference.close() in python to close an opened file.

For example:

fp = open(“vgu.txt”, “at”)

# Do some work!

fp.close()

why is it important closing a file?

So there are many reasons:

● If a file is opened to perform any operations then it’s locked to be

opened by any other resource until the process itself closes it.

● Operating System keeps a check on the number of files opened by a

program and thus closing files after use allows you stay within that

restriction.
● Effective Resource management

Exception Handling in Python

Exceptions are raised when the program is syntactically correct, but the

code results in an error. This error does not stop the execution of the

program, however, it changes the normal flow of the program.

Exceptions are convenient for handling errors and special conditions in a

program. If you are working with a code that can produce an error, then

you can use exception handling. Also, you can raise an exception in your

own program by using the raise exception statement. Raising an exception

breaks current code execution and returns the exception back until it is

handled.

Try and except statements are used to catch and handle exceptions in

Python. Statements that can raise exceptions are kept inside the try clause

and the statements that handle the exception are written inside except

clause.

How Does Try() Work?

The different steps involved in the working of try are:

● The try clause is executed between the try and except clause.

● If there is no exception, then only the try clause will run and except

clause is finished.
● The try clause will be skipped and except clause will run if any

exception occurs.

● In case of any exception, if the except clause within the code doesn’t

handle it, it is passed on to the outer statements. The execution is

stopped if the exception left unhandled.

● A try statement can have more than one except clause.

Python Exceptions Example

In the first example, there is no exception, so the try clause will run:

def divide(x, y):

try:

result = x // y

print("The answer is :", result)

except ZeroDivisionError:

print("Sorry ! Cannot divide by zero ")

divide(10, 5)

Output:

The answer is : 2
In the second example, there is an exception so only except clause will

run:

def divide(x, y):

try:

result = x // y

print("The answer is :", result)

except ZeroDivisionError:

print("Sorry ! Cannot divide by zero ")

divide(4, 0)

Output: Sorry ! Cannot divide by zero

……………………….

You might also like