Python UNIT 1
Python UNIT 1
UNIT I
A program is a set of instructions that tells the computer how to solve a particular problem. Various
program design tools like algorithms, pseudocdes and flowcharts are used to design the blueprint of the
solution (or the program to be written). Computer programming goes a step further in problem solving
process. Programming means writing computer programs. While programming, the programmers take
an algorithm and code the instructions in a particular programming language so that it can be executed
by a computer. These days, there are many programming languages available in the market. The
programmer can choose any language depending on his expertise and the problem domain.
ALGORITHMS
In computing, we focus on the type of problems categorically known as algorithmic problems, where
their solutions are expressible in the form of algorithms. The term ‘algorithm’ was derived from the
name of Mohammed al-Khwarizmi, a Persian mathematician in the nineth century (Al-Khwarizmi →
Algorism (in Latin) → Algorithm). The typical meaning of an algorithm is a formally defined procedure for
performing some calculation. If a procedure is formally defined, then it must be implemented using
some formal language, and such languages are known as programming languages. The algorithm gives
the logic of the program, that is, a step-by-step description of how to arrive at a solution.
In general terms, an algorithm provides a blueprint to writing a program to solve a particular problem. It
is considered to be an effective procedure for solving a problem in a finite number of steps. That is, a
well-defined algorithm always provides an answer, and is guaranteed to terminate
Algorithms are mainly used to achieve software reuse. Once we have an idea or a blueprint of a solution,
we can implement it in any language, such as C, C++, Java, and so on. In order to qualify as an algorithm,
a sequence of instructions must possess the following characteristics:
• Effectiveness: The algorithm should designed in such a way that it should be the most effective among
many different ways to solve a problem.
• Output: After the algorithm gets terminated, the desired result must be obtained.
In the course of processing, data is read from an input device, stored in computer’s memory for further
processing, and then the result of the processing is written to an output device. The data is stored in the
computer’s memory in the form of variables or constants.
The state of an algorithm is defined as its condition regarding current values or contents of the stored
data.
An algorithm is a list of precise steps and the order of steps determines the functioning of the algorithm.
The flow of control (or the control flow) of an algorithm can be specified as top-down or bottom-up
approach. Thus, the flow of control specifies the order in which individual instructions of an algorithm
are executed.
A subroutine (or procedure or function or routine) is a sequence of instructions that performs a specific
task. These instructions are packaged as a single unit and can be used (or invoked or called) wherever
that particular task needs to be performed. After performing its defined task, the sub-routine branches
back (or returns) to the next instruction after the one that invoked it.
A subroutine may be designed to accept one or more data values (also known as parameters) from the
calling code. It may also return a value to its caller.
A subroutine can also be written in such a way that it calls itself repeatedly. The subroutine symbol is
used to write steps for procedures. These procedures can be called from anywhere in the code. This
means that once the flowchart for a process is drawn, it can be referenced and used from anywhere in
the code.
1.4 ALGORITHMIC PROBLEM SOLVING STEPS
As mentioned earlier, algorithms are solutions to problems. They are not solutions themselves. They just
list specific instructions that need to be performed for getting the solution. In computer science,
emphasis is laid on writing a good and effective algorithm and this emphasis makes computer science
distinct from other disciplines. For example, computer science is distinct from theoretical mathematics
because those practitioners are typically satisfied with just proving the existence of a solution to a
problem but in computer science, the problem is not solved until the algorithm is used to implement the
solution. We will now discuss about the sequence of steps one must typically follow for designing an
effective algorithm.
3. Exact/approximate solution
The problem given should be clearly and completely understood. It is compared with earlier problems
that have already been solved to check if it is similar to them and a known algorithm exists. If the
algorithm is available, it is used, otherwise a new one has to be developed.
After understanding the problem, the capabilities of the computing device should be known. For this,
the type of the architecture, speed and memory availability of the device are noted.
Exact/approximate solution
The next step is to develop the algorithm. The algorithm must compute correct output for all possible
and legitimate inputs. This solution can be an exact solution or an approximate solution. For example,
you can only have an approximate solution in case of finding square root of number or finding the
solutions of non-linear equations.
A data type is a well-defined collection of data with a welldefined set of operations on it. A data
structure is basically a group of data elements that are put together under one name, and which defines
a particular way of storing and organizing data in a computer so that it can be used efficiently. The
elementary data structures are as follow
2 Sets: Treats data as elements of a set. Allows application of operations such as intersection, union,
and equivalence.
Developing an algorithm is an art which may never be fully automated. By mastering the design
techniques, it will become easier for you to develop new and useful algorithms. Examples of algorithm
design techniques include dynamic programming.
An algorithm is just a sequence of steps or instructions that can be used to implement a solution. After
writing the algorithm, it is specified either using a natural language or with the help of pseudocode and
flowcharts.
Writing an algorithm is not just enough. You need to prove that it computes solutions for all the possible
valid inputs. This process is often referred to as algorithm validation. Algorithm validation ensures that
the algorithm will work correctly irrespective of the programming language in which it will be
implemented.
When an algorithm is executed, it uses the computer’s resources like the Central Processing Unit (CPU)
to perform its operation and to hold the program and data respectively. An algorithm is analysed to
measure its performance in terms of CPU time and memory space required to execute that algorithm.
This is a challenging task and is often used to compare different algorithms for a particular problem. The
result of the comparison helps us to choose the best solution from all possible solutions. Analysis of the
algorithm also helps us to determine whether the algorithm will be able to meet any efficiency
constraint that exits or not.
An algorithm is a step–by–step procedure for solving a task or problem. However, these steps must be
ordered, unambiguous and finite in number. Basically, an algorithm is nothing but English-like
representation of logic which is used to solve the problem. For accomplishing a particular task, different
algorithms can be written. The different algorithms differ in their requirements of CPU time and memory
space. The programmer selects the best suited algorithm for the given task to be solved.
Various strategies and notations used for developing and designing algorithms are discussed in the
following sections.
An algorithm has a finite number of steps and some steps may involve decision making and repetition.
Broadly speaking, an algorithm may employ three control structures, namely, sequence, decision, and
repetition.
Sequence
Sequence means that each step of the algorithm is executed in the specified order. An algorithm to add
two numbers is given as follows. This algorithm performs the steps in a purely sequential order.
End
Decision
Decision statements are used when the outcome of the process depends on some condition. For
example, if x = y, then print "EQUAL". Hence, the general form of the if construct can be given as
follows:
A condition in this context is any statement that may evaluate either to a true value or a false value. In
the preceding example, the variable x can either be equal or not equal to y. However, it cannot be both
true and false. If the condition is true then the process is executed.
IF condition
then process1
ELSE process2
This form is commonly known as the if-else construct. Here, if the condition is true then process1 is
executed, else process2 is executed. An algorithm to check the equality of two numbers is shown below
1.2.1 FLOW CHART
When designing a flowchart, each step in the process is depicted by a different symbol and is associated
with a short description. The symbols in the flowchart (refer Figure 1.1) are linked together with arrows
to show the flow of logic in the process. The symbols used in a flowchart include the following:
1 Start and end symbols are also known as the terminal symbols and are represented as circles, ovals, or
rounded rectangles. Terminal symbols are always the first and the last symbols in a flowchart.
2 Arrows depict the flow of control of the program. They illustrate the exact sequence in which the
instructions are executed.
3 Generic processing step, also called as an activity, is represented using a rectangle. Activities include
instructions such as add a to b or save the result. Therefore, a processing symbol represents arithmetic
and data movement instructions. When more than one process has to be executed simultaneously, they
can be placed in the same processing box. However, their execution will be carried out in the order of
their appearance.
• Input/Output symbols are represented using a parallelogram and are used to get inputs from the users
or display the results to them.
• A conditional or decision symbol is represented using a diamond. It is basically used to depict a Yes/No
question or a True/False test. The two symbols coming out of it, one from the bottom point and the
other from the right point, corresponds to Yes or True, and No or False, respectively. The arrows should
always be labelled. A decision symbol in a flowchart can have more than two arrows, which indicates
that a complex decision is being taken.
• Labelled connectors are represented by an identifying label inside a circle and are used in complex or
multi-sheet diagrams to substitute for arrows. For each label, the ‘outflow’ connector must have one or
more ‘inflow’ connectors. A pair of identically labelled connectors is used to indicate a continued flow
when the use of lines becomes confusing.
• A pre-defined process symbol is a marker for another process step or series of process flow steps that
are formally defined elsewhere. This shape commonly depicts sub-processes (or subroutines in
programming flowcharts).
Significance of Flowcharts
A flowchart is a diagrammatic representation that illustrates the sequence of steps that must be
performed to solve a problem. It is usually drawn in the early stages of formulating computer solutions.
It facilitates communication between programmers and users. Once a flowchart is drawn, programmers
can make users understand the solution easily and clearly.
Flowcharts are very important in the programming of a problem as they help the programmers to
understand the logic of complicated and lengthy problems. Once a flowchart is drawn, it becomes easy
for the programmers to write the program in any high-level language. Hence, the flowchart has become
a necessity for better documentation of complex programs
Advantages of flowchart:
1.Communication: - Flowcharts are better way of communicating the logic of
a system to all concerned.
2. Effective analysis: - With the help of flowchart, problem can be analyzed in
more effective way.
3.Proper documentation: - Program flowcharts serve as a good
program documentation, which is needed for various purposes.
4.Efficient Coding: - The flowcharts act as a guide or blueprint during the
systems analysis and program development phase.
5. Proper Debugging: - The flowchart helps in debugging process.
6.Efficient Program Maintenance: - The maintenance of operating program
becomes easy with the help of flowchart. It helps the programmer to put
efforts more efficiently on that part.
Disadvantages of flow chart:
1. Complex logic: - Sometimes, the program logic is quite complicated. In that
case, flowchart becomes complex and clumsy.
2. Alterations and Modifications: - If alterations are required the flowchart
may require re-drawing completely.
3. Reproduction: - As the flowchart symbols cannot be typed, reproduction
of flowchart becomes a problem.
4.Cost: For large application the time and cost of flowchart drawing
becomes costly.
1.5.3 Pseudocodes
Pseudocode is a compact and informal high-level description of an algorithm that uses the structural
conventions of a programming language. It facilitates designers to focus on the logic of the algorithm
without getting bogged down by the details of language syntax. An ideal pseudocode must be complete,
describing the entire logic of the algorithm, so that it can be translated straightaway into a programming
language.
It is basically meant for human reading rather than machine reading, so it omits the details that are not
essential for humans. Such details include variable declarations, system-specific code, and subroutines.
Pseudocodes are an outline of a program that can easily be converted into programming statements.
They consist of short English phrases that explain specific tasks within a program’s algorithm. They
should not include keywords in any specific computer language.
The sole purpose of pseudocodes is to enhance human understandability of the solution. They are
commonly used in textbooks and scientific publications for documenting algorithms, and for sketching
out the program structure before the actual coding is done. This helps even non-programmers to
understand the logic of the designed solution. There are no standards defined for writing a pseudocode,
because a pseudocode is not an executable program. Flowcharts can be considered as graphical
alternatives to pseudocodes, but require more space on paper.
1.3 PROGRAMMING LANGUAGE
• Portability.
UNIT 1
functions that are combined and interpreted by the compiler to create a new value, as
opposed to a “statement” which is just a standalone unit of execution and doesn't return
anything.
Data types are the classification or categorization of data items. It represents the
kind of value that tells what operations can be performed on a particular data.
Since everything is an object in Python programming, data types are actually
classes and variables are instance (object) of these classes.
Following are the standard or built-in data type of Python:
Numeric
Sequence Type
Boolean
Set
Dictionary
Numeric
In Python, numeric data type represent the data which has numeric value. Numeric
value can be integer, floating number or even complex numbers. These values are
defined as int, float and complex class in Python.
Integers – This value is represented by int class. It contains positive or
negative whole numbers (without fraction or decimal). In Python there is no limit
to how long an integer value can be.
Float – This value is represented by float class. It is a real number with
floating point representation. It is specified by a decimal point. Optionally, the
character e or E followed by a positive or negative integer may be appended to
specify scientific notation.
Complex Numbers – Complex number is represented by complex class. It
is specified as (real part) + (imaginary part)j. For example – 2+3j
Note – type() function is used to determine the type of data type.
a =5
b = 5.0
c = 2 + 4j
Output:
Type of a: <class 'int'>
Python Expressions:
Expressions are representations of value. They are different from statement in the fact that statements do
something while expressions are representation of value. For example any string is also an expressions
since it represents the value of the string as well.
Python has some advanced constructs through which you can represent values and hence these
constructs are also called expressions.
Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
Python is a Beginner's Language: Python is a great language for the beginnerlevel programmers and
supports the development of a wide range of applications.
Python Features:
Easy-to-learn: Python is clearly defined and easily readable. The structure of the program is very
simple. It uses few keywords.
Easy-to-maintain: Python's source code is fairly easy-to-maintain. Portable: Python can run on a wide
variety of hardware platforms and has the same interface on all platforms.
Interpreted: Python is processed at runtime by the interpreter. So, there is no need to compile a
program before executing it. You can simply run the program.
Extensible: Programmers can embed python within their C,C++,Java script ,ActiveX, etc.
Free and Open Source: Anyone can freely distribute it, read the source code, and edit it.
High Level Language: When writing programs, programmers concentrate on solutions of the current
problem, no need to worry about the low level details.
Scalable: Python provides a better structure and support for large programs than shell scripting.
Applications:
Bit Torrent file sharing
i–Robot
NASA
2.1Numbers:
2.2 Sequence:
Sequence Type
In Python, sequence is the ordered collection of similar or different data types.
Sequences allows to store multiple values in an organized and efficient fashion.
There are several sequence types in Python –
String
List
Tuple
2.2.1 Strings:
1) String
In Python, Strings are arrays of bytes representing Unicode characters. A string is
a collection of one or more characters put in a single quote, double-quote or triple
quote. In python there is no character data type, a character is a string of length
one. It is represented by str class.
Creating String
Strings in Python can be created using single quotes or double quotes or even
triple quotes.
# Creation of String
# Creating a String
print(String1)
# Creating a String
print(String1)
print(type(String1))
# Creating a String
# with triple Quotes
print(String1)
print(type(String1))
String1 = '''Geeks
For
Life'''
print(String1)
Output:
String with the use of Single Quotes:
Welcome to the Geeks World
# characters of String
String1 = "GeeksForGeeks"
print(String1)
print(String1[0])
print(String1[-1])
Output:
Initial String:
GeeksForGeeks
2) List
Lists are just like the arrays, declared in other languages which is a ordered
collection of data. It is very flexible as the items in a list do not need to be of the
same type.
Creating List
Lists in Python can be created by just placing the sequence inside the square
brackets[].
# Creation of List
# Creating a List
List = []
print(List)
List = ['GeeksForGeeks']
print(List[0])
print(List[2])
print(List)
Output:
Intial blank List:
[]
Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]
Accessing elements of List
In order to access the list items refer to the index number. Use the index operator [
] to access an item in a list. In Python, negative sequence indexes represent
positions from the end of the array. Instead of having to compute the offset as
in List[len(List)-3], it is enough to just write List[-3]. Negative indexing means
beginning from the end, -1 refers to the last item, -2 refers to the second-last item,
etc.
print(List[0])
print(List[2])
# negative indexing
print(List[-1])
print(List[-3])
Output:
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
2.2.4Tuple:
3) Tuple
Just like list, tuple is also an ordered collection of Python objects. The only
difference between type and list is that tuples are immutable i.e. tuples cannot be
modified after it is created. It is represented by tuple class.
Creating Tuple
In Python, tuples are created by placing a sequence of values separated by
‘comma’ with or without the use of parentheses for grouping of the data sequence.
Tuples can contain any number of elements and of any datatype (like strings,
integers, list, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky. Having
one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to
make it a tuple.
# creation of Set
Tuple1 = ()
print (Tuple1)
print(Tuple1)
print(tuple(list1))
Tuple1 = tuple('Geeks')
print(Tuple1)
# Creating a Tuple
Output:
Initial empty Tuple:
()
tuple1 = tuple([1, 2, 3, 4, 5])
print(tuple1[0])
# negative indexing
print(tuple1[-1])
print(tuple1[-3])
Output:
Frist element of tuple
1
Python has two basic modes: script and interactive. The normal mode is the mode where the scripted and
finished .py files are run in the Python interpreter. Interactive mode is a command line shell which gives
immediate feedback for each statement, while running previously fed statements in active memory
Advantages
Readability
High level language is closer to natural language so they are easier to learn
and understand
Machine independent
High level language program have the advantage of being portable between
machines.
Easy debugging
Easy to find and correct error in high level language
Disadvantages
Less efficient
The translation process increases the execution time of the program.
Programs in high level language require more memory and take more
execution time to execute.
1.1.5 Values and Data Types
Value:
Value can be any letter ,number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong
to different datatypes.)
Data type:
Every value in Python has a data type.
It is a set of values, and the allowable operations on those values.
Python has four standard data types:
Numbers:
Number data type stores Numerical Values.
This data type is immutable [i.e. values/items cannot be changed].
Python supports integers, floating point numbers and complex
numbers. They are defined as,