Python Notes 1
Python Notes 1
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.
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.
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.
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.
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
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”.
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.
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
Examples of identifiers:
variable_name
function_name
Class
module_name
_private_variable
Operators in Python
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.
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
Methods
List
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
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]
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]
Tuple
#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
my_tuple = (1, 2, 3, 4, 5)
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
my_tuple = (1, 2)
Methods:
index = my_tuple.index(2)
print(index) # Output: 1
Changing A Tuple
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
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
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-
print(mydictionary)
Accessing an element
mydictionary[1]
#this will get the key value pair with the key 1.
mydictionary.get(1)
Replacing an element
Removing an element
del mydictionary[3]
print(mydictionary)
#this will remove the key value pair from the dictionary with the specified
Operations on a dictionary
a = { 1: 2 , 2: 3 , 3: 5}
a.clear()
print(a)
a = {1:2, 2: 3, 3: 4}
b = a.copy()
print(b)
#b will be a copy of the dictionary a.
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 specied key
value pairs.
a {= 1 : 2, 2: 3, 3: 5}
a.update({4: 6})
#this will update the dictionary with the specied key value pair.
b = {1: 2, 2: 3, 3: 'python'}
a.Fromkeys(b)
#this will get the dictionary with the specied keys and values.
items( ) – returns the list for a tuple of each key value pair in the
dictionary.
#this will get the list of tuple for each key value pair.
a.keys()
#this will get the list of all the keys from the dictionary.
a.pop(3)
popitem( ) – removes the last inserted key values pair from the
dictionary.
a.popitem()
#this will remove the last inserted key value pair from the dictionary.
setdefault( ) – returns the value of the specied key, if not present insert
the
a.setdefault(1, 'programming')
Functions in Python
Syntax:
def function_name(parameters):
#statements
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.
For example, print() function prints the given object to the standard
output device (screen) or to the text stream file.
Statement_1
Statement_2
....
Example
def add_numbers(x,y):
sum = x + y
return sum
num1 = 5
num2 = 6
Output
The sum is 11
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
Example:
def calc_factorial(x):
if x == 1 or x==0:
return 1
else:
return (x * calc_factorial(x-1))
num = 4
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 -
message = 'Hello'
def greet():
print(message)
greet()
print(message)
Output -
Hello
Hello
Example-
def greet():
# local variable
message = 'Hello'
print('Local', message)
greet()
print(message)
Output -
Local Hello
The focus is to break down the code into different modules so that there will be no or
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, the above function will square the number passed as the input
result = number ** 2
import example_module as em
result = em.square( 4 )
Here, ‘em’ is an alias word(short name) given to the module for easy
access.
Python Package
Python Packages are a way to organize and structure your Python code
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
different tasks.
As a programmer , we can store are functions in package so that we can reuse them.
structure.
● Add Modules: Within the package directory, you can add Python
as a package.
your Python scripts using dot notation. For example, if you have a
Code Example
module2.py.
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
return a + b
#third file
module1.greet("Alice")
result = module2.add(3, 5)
That’s how we can create different modules into one package and use them later.
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-
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
● Closing a file
you need to open file so that you can write to it. So to open a file in python
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
For example:
fp = open(“my_file.png”, “rb”)
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.
for _ in range(10):
fp.close()
To write to a file we first opened a file named vgu.txt and saved its
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.
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
Appending to a File
Now, most of the times you will be writing to a file without destroying the
For this example let’s append to the same file that we already created.
fp = open(“vgu.txt”, “at”)
for _ in range(5):
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
that file.
Closing a File
For example:
fp = open(“vgu.txt”, “at”)
# Do some work!
fp.close()
opened by any other resource until the process itself closes it.
program and thus closing files after use allows you stay within that
restriction.
● Effective Resource management
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. 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
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.
● 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
In the first example, there is no exception, so the try clause will run:
try:
result = x // y
except ZeroDivisionError:
divide(10, 5)
Output:
The answer is : 2
In the second example, there is an exception so only except clause will
run:
try:
result = x // y
except ZeroDivisionError:
divide(4, 0)
……………………….