Full Python
Full Python
FLOWCHART
ALGORITHM
ØThe word algorithm relates to the name of mathematician Al-
Khowarizmi, which means a procedure or a technique.
ØAn algorithm is a sequence of steps to solve a particular
problem or algorithm is an ordered set of unambiguous steps
that produces a result and terminates in a finite time.
ØAlgorithm has the following characteristics
ØInput: An algorithm may or may not require input
ØOutput: Each algorithm is expected to produce at least one result
ØDefiniteness: Each instruction must be clear and unambiguous.
ØFiniteness: If the instructions of an algorithm are executed, the
algorithm should terminate after finite number of steps
ADVANTAGES OF ALGORITHM
Step 2 Define the variables: Algorithm's variables allow you to use it for more
than one place.
We can define two variables for rectangle height and rectangle width as HEIGHT and WIDTH (or H
& W). We should use meaningful variable name e.g. instead of using H & W use HEIGHT and
WIDTH as variable name.
HOW TO WRITE ALGORITHMS
Step 3 Outline the algorithm's operations: Use input variable for computation
purpose,
e.g. to find area of rectangle multiply the HEIGHT and WIDTH variable and store the value in new
variable (say) AREA.
An algorithm's operations can take the form of multiple steps and even branch, depending on the
value of the input variables.
qThe first design of flowchart goes back to 1945 which was designed by John Von
Neumann.
qUnlike an algorithm, Flowchart uses different symbols to design a solution to a
problem.
qIt is another commonly used programming tool.
qBy looking at a Flowchart one can understand the operations and sequence of
operations performed in a system.
qFlowchart is often considered as a blueprint of a design used for solving a
specific problem.
ADVANTAGES OF FLOWCHART
vFlowchart is diagrammatic /Graphical representation of sequence of steps to
solve a problem
vFlowchart is an excellent way of communicating the logic of a program.
vEasy and efficient to analyze problem using flowchart.
vDuring program development cycle, the flowchart plays the role of a blueprint,
which makes program development process easier.
vAfter successful development of a program, it needs continuous timely
maintenance during the course of its operation.
vThe flowchart makes program or system maintenance easier.
vIt is easy to convert the flowchart into any programming language code.
STANDARD SYMBOLS
vThe language used to write algorithm is simple and similar to day-to-day life
language.
vThe variable names are used to store the values. The value store in variable can
change in the solution steps.
vIn addition some special symbols are used as below:
vAssignment Symbol ( <- or =) is used to assign value to the variable.
e.g. to assign value 5 to the variable HEIGHT, statement is
HEIGHT <- 5
or
HEIGHT = 5
vThe statement C = A + B means that add the value stored in variable A and
variable B then assign/store the value in variable C.
vThe statement R = R + 1 means that add I to the value stored in variable R and
then assign/store the new value in variable R, in other words increase the value
of variable R by 1
ALGORITHM & FLOWCHART TO
FIND THE SUM OF TWO NUMBERS
ALGORITHM & FLOWCHART TO CONVERT
TEMPERATURE FROM CELSIUS TO FAHRENHEIT
ALGORITHM & FLOWCHART TO CONVERT
TEMPERATURE FROM FAHRENHEIT TO CELSIUS
14-11-2022 Dr Aravapalli Rama Satish 1
Python Introduction -
Operators & Branching
Module - 2
Python - History
Execution
Execution
in
in
Interactive
Script mode
mode
C:\> python –m py_compile x.py To store the byte code in separate file in
Way - II the directory “__pycache__” as “x.cpython-34.pyc”
C:\> python x.cpython-34.pyc
We cannot use a
keyword as a
variable name,
function name or
any other
identifier.
• frozenset:
• Similar to set but once it is created it can’t be modified.
• Can be create by using frozenset().
• The None data type represents an object that does not contain
any value
• In a python program, maximum of only one ‘None’ object is provided.
• One of the uses of ‘None’ is that it is used inside a function as a
default value of the arguments.
• When calling a function, if no value is passed, then the default value will be
taken as ‘None’. If some value is passed to the function, then that value is used
by the function.
• In Boolean expression,‘None’ data type represents False.
• D = (1+2)*3**2//2+3 **
Exponent - left operand raised to the x**y (x to the
power of right power y)
to the condition. !=
Not equal to - True if operands are
not equal
x != y
ceil(x) Returns the smallest integer greater than or equal to x. pow(x, y) Returns x raised to the power y
copysign(x, y) Returns x with the sign of y sqrt(x) Returns the square root of x
fabs(x) Returns the absolute value of x acos(x) Returns the arc cosine of x
floor(x) Returns the largest integer less than or equal to x atan(x) Returns the arc tangent of x
frexp(x) Returns the mantissa and exponent of x as the pair (m, e) cos(x) Returns the cosine of x
fsum(iterable) Returns an accurate floating point sum of values in the iterable hypot(x, y) Returns the Euclidean norm, sqrt(x*x + y*y)
isfinite(x) Returns True if x is neither an infinity nor a NaN (Not a Number) sin(x) Returns the sine of x
isinf(x) Returns True if x is a positive or negative infinity tan(x) Returns the tangent of x
isnan(x) Returns True if x is a NaN degrees(x) Converts angle x from radians to degrees
modf(x) Returns the fractional and integer parts of x acosh(x) Returns the inverse hyperbolic cosine of x
trunc(x) Returns the truncated integer value of x asinh(x) Returns the inverse hyperbolic sine of x
log(x[, b]) Returns the logarithm of x to the base b (defaults to e) sinh(x) Returns the hyperbolic cosine of x
log1p(x) Returns the natural logarithm of 1+x tanh(x) Returns the hyperbolic tangent of x
pi Mathematical constant, the ratio of circumference of a circle to it's diameter (3.14159...)
https://docs.python.org/3/library/math.html
e mathematical constant e (2.71828...)
14-11-2022 Dr Aravapalli Rama Satish 74
Math module
• break:
• It is used inside a for loop or while loop to come out of them.
• When break is executed, the python interpreter jumps out of the loop
to process the next statement in the program.
• continue:
• It is used in a loop to go back to the beginning of the loop.
• When continue is executed, the next repetition will start and all the
subsequent statements in the current iteration will be skipped from
the execution.
2
4
a
Matched?
No match
• A period matches any single ac 1 match
character (except newline ..
'\n’). acd 1 match
To build and test regular expressions, you can use RegEx tester tools such as regex101. This tool not
only helps you in creating regular expressions, but it also helps you learn it.
%[flags][width][.precision]type
https://docs.python.org/2/library/stdtypes.html#string-
formatting
04-01-2023 Dr Aravapalli Rama Satish 3
print( )
• Any object which is not a string can be formatted using the %s operator
as well.
• The string which returns from the "repr" method of that object is
formatted as the string.
• For example:
https://docs.python.org/3/library/stdtypes.html#str.
format
https://docs.python.org/3/library/string.html#form
atstrings
• Searching a String:
• To find out whether a
given key string is
available in the list of
strings or not and
provide the location of
the string in the list.
• List comprehension offers a shorter syntax when you want to create a new list
based on the values of an existing list.
• Python also supports computed lists called ‘List Comprehensions’ having the
following syntax:
newlist = [expression for item in iterable if condition == True]
Where expression is evaluated once for every item in the sequence.
# Assign matrix
twoDMatrix = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]
# Generate transpose
trans = [[i[j] for i in twoDMatrix] for j in range(len(twoDMatrix[0]))]
print(trans)
04-01-2023 Dr Aravapalli Rama Satish 46
List Comprehensions
# Initializing string # Explicit function to calculate sum of digits
string = 'Geeks4Geeks' def digitSum(n):
# Toggle case of each character dsum = 0
List = list(map(lambda i: chr(ord(i) ^ 32), string))
# Display list for ele in str(n):
print(List) dsum += int(ele)
return dsum
# Reverse each string in tuple # Initializing list
List = [string[::-1] for string in ('Geeks', 'for', List = [367, 111, 562, 945, 6726, 873]
'Geeks')] # Using the function on odd elements of the list
# Display list newList = [digitSum(i) for i in List if i & 1]
print(List)
# Displaying new list
print(newList)
04-01-2023 Dr Aravapalli Rama Satish 47
List - Enumeration
• enumerate( ) is used.
• It is used when we want to print both index as well as an item in the list.
• It returns an enumerate object which contains the index and the value of all the
items of the list as a tuple.
• To print index, you also can use range( ).
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]
[(1, 'f'), (2, 'g'), (3, 'h')]
• Just like in other Python container objects, the contents of an array can be accessed
and modified by indexing or slicing the array.
• Unlike the typical container objects, different arrays can share the same data, so
changes made on one array might be visible in another.
• Array attributes reflect information intrinsic to the array itself.
• If you need to get, or even set, properties of an array without creating a new array,
you can often access an array through its attributes.
04-01-2023 Dr Aravapalli Rama Satish 82
NumPy – Creation of basic array
• To create a NumPy array, you can use the function np.array().
• All you need to do to create a simple array is pass a list to it. If you choose to, you can
also specify the type of data in your list.
• The function empty creates an array whose initial content is random and
depends on the state of the memory. The reason to use empty over zeros (or
something similar) is speed - just make sure to fill every element afterwards!
• You can create an array with a range of elements. And even an array that
contains a range of evenly spaced intervals. To do this, you will specify the
first number, last number, and the step size.
04-01-2023 Dr Aravapalli Rama Satish 84
NumPy – Creation of basic array
• You can also use np.linspace() to create an array with values that are spaced
linearly in a specified interval.
• While the default data type is floating point (np.float64), you can explicitly specify
which data type you want using the dtype keyword.
You can also make use of the logical operators & and |
in order to return Boolean values that specify whether
or not the values in an array fulfill a certain condition.
This can be useful with arrays that contain names or
other categorical values.
04-01-2023 Dr Aravapalli Rama Satish 97
NumPy – Indexing and Slicing
• You can also use np.nonzero() to select elements or indices from an
array.
• You can use np.nonzero() to print the indices of elements that are, for example,
less than 5
• You can also stack two existing arrays, both vertically and horizontally.
• vstack or hstack.
• You can split an array into several smaller arrays using hsplit.
• You can specify either the number of equally shaped arrays to return or the columns
after which the division should occur.
You can also use ones(), zeros(), and random() to create a 2D array
if you give them a tuple describing the dimensions of the matrix:
# For 2D mixed with 1D, the result is the usual., np.matmul() is the conventional matrix product.
a = np.array([[1, 0], [0, 1]])
b = np.array([1, 2])
# The output matrices below are both 1D after the removal of the appended/prepended 1 dimension
print(np.matmul(a, b)) # Prints [1 2]
print(np.matmul(b, a)) # Prints [1 2]
a = np.ones([9, 5, 7, 4])
c = np.ones([9, 5, 4, 3])
print(np.dot(a, c).shape) # Prints (9, 5, 7, 9, 5, 3)
print(np.matmul(a, c).shape) # Prints (9, 5, 7, 3) / n is 7, k is 4, m is 3 per the stacked-matrices rule
1. add_number(2, 3): Both values are passed during the function call.
Hence, these values are used instead of the default values.
2. add_number(2): Only one value is passed during the function call.
So, according to the positional argument 2 is assigned to argument a,
and the default value is used for parameter b.
3. add_number(): No value is passed during the function call. Hence,
default value is used for both parameters a and b.
We can use * or ** when we are calling a function to unpack a sequence or a dictionary into a
series of individual parameters:
file = open(“File1.txt”,“a”)
file.write(“\n python is very simple yet powerful language”)
file.close()
26-01-2023 Dr Aravapalli Rama Satish 8
Reading of Files
• read() is used to read a string from an already opened file.
• syntax: fo.read(count)
• count is an optional parameter which if passed to the read() specifies the
number of bytes to be read from the opened file.
• It starts reading from the beginning of the file.
• If count is missing or has negative value, then it reads entire file contents.
• read() returns new line as ‘\n’
• If you try to open a file for reading that does not exist, then you will get an
error.
file = open(“File1.txt”, “r”)
print(file.read(10))
file.close()
26-01-2023 Dr Aravapalli Rama Satish 9
Reading of Files
• readline() is used to read a single line from the file.
• It returns an empty string when the end of the file is reached.
• The blank line is represented by ‘\n’ and the readline() returns a string
containing only a single new line character.
• After reading a line the control automatically goes to the next line.
• readlines() is used to read all lines in the file.
file = open(“File1.txt”, “r”)
print(“First Line:”, file.readline())
print(“Second Line:”, file.readline())
file.close()
(or)
file = open(“File1.txt”, “r”)
print(file.readlines())
file.close()
def charcount(filename):
return len(open(filename).read())
def wordcount(fn):
return len(open(filename).read().split())
def linecount(fn):
return len(open(fn).readlines())
uppercount()
fh=open("python.txt","r")
fw=open("python_new.txt","w")
rec=fh.read()
for a in rec:
if (a.isdigit() != True):
fw.write(a)
fh.close()
fw.close()
26-01-2023 Dr Aravapalli Rama Satish 19
Examples
• Write a program to count the words “to” and “the” present in
a text file “python.txt”
fname = "python.txt"
num_words = 0
f= open(fname, 'r')
words = f.read().split()
for a in words:
if (a.lower() == "to" or a.lower() == "the" ):
num_words = num_words + 1
print("Number of words:", num_words)
f.close()
fh=open("python.txt","r")
count=0
lines=fh.readlines()
for a in lines:
count=count+1
print(count,a)
fh.close()
fh=open("python.txt","r")
count=0
lines=fh.readlines()
for a in lines:
if (a.count("to") > 0) :
print(a)
fh.close()
import csv
with open('innovators.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)