0% found this document useful (0 votes)
29 views53 pages

Part-1 Notes

The document discusses problem solving techniques in Python including algorithms, flowcharts, pseudocode, and programming languages. It defines each technique and provides examples. Key aspects covered include the components of algorithms, control flow, functions, and syntax for different programming constructs.

Uploaded by

Kannan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views53 pages

Part-1 Notes

The document discusses problem solving techniques in Python including algorithms, flowcharts, pseudocode, and programming languages. It defines each technique and provides examples. Key aspects covered include the components of algorithms, control flow, functions, and syntax for different programming constructs.

Uploaded by

Kannan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Module:1: Basics of Python

PROBLEM SOLVING

Problem solving is the systematic approach to define the problem and


creating number of solutions.
The problem solving process starts with the problem specifications and
ends with a Correct program.
PROBLEM SOLVING TECHNIQUES
Problem solving technique is a set of techniques that helps in providing
logic for solving a problem.

Problem Solving Techniques:


Problem solving can be expressed in the form of
1. Algorithms.
2. Flowcharts.
3. Pseudo codes.
4. programs

ALGORITHM

It is defined as a sequence of instructions that describe a method for


solving a problem. In other words it is a step by step procedure for solving
a problem.
Properties of Algorithms
 Should be written in simple English
 Each and every instruction should be precise and unambiguous.
 Instructions in an algorithm should not be repeated infinitely.
 Algorithm should conclude after a finite number of steps.
 Should have an end point
 Derived results should be obtained only after the algorithm terminates.

Qualities of a good algorithm


The following are the primary factors that are often used to judge the
quality of the algorithms.
Time – To execute a program, the computer system takes some amount of
time. The lesser is the time required, the better is the algorithm.
Memory – To execute a program, computer system takes some amount of
memory space. The lesser is the memory required, the better is the
algorithm.
Accuracy – Multiple algorithms may provide suitable or correct solutions
to a given problem, some of these may provide more accurate results than
others, and such algorithms may be suitable.
Example
Write an algorithm to print „Good Morning”
Step 1: Start
Step 2: Print “Good Morning”
Step 3: Stop

BUILDING BLOCKS OF ALGORITHMS (statements, state,


control flow, functions)
Algorithms can be constructed from basic building blocks namely,
sequence, selection and iteration.
Statements:
Statement is a single action in a computer.
In a computer statements might include some of the following actions
 input data-information given to the program
 process data-perform operation on a given input
 output data-processed result

State:
Transition from one process to another process under specified condition
with in a time is called state.
Control flow:
The process of executing the individual statements in a given order is called
control flow.
The control can be executed in three ways
1. sequence
2. selection
3. iteration
Sequence:
All the instructions are executed one after another is called sequence
execution.

Example:

Add two numbers:


Step 1: Start
Step 2: get a,b
Step 3: calculate c=a+b
Step 4: Display c
Step 5: Stop

Selection:
A selection statement causes the program control to be transferred to a
specific part of the program based upon the condition.
If the conditional test is true, one part of the program will be executed,
otherwise it will execute the other part of the program.
Example
Write an algorithm to check whether he is eligible to vote?
Step 1: Start
Step 2: Get age
Step 3: if age >= 18 print “Eligible to vote”
Step 4: else print “Not eligible to vote”
Step 6: Stop

Iteration:
In some programs, certain set of statements are executed again and again
based upon conditional test. i.e. executed more than one time. This type of
execution is called looping or iteration.
Example
Write an algorithm to print all natural numbers up to n
Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 7
Step 5: Print i value and increment i value by 1
Step 6: go to step 4
Step 7: Stop

Functions:

 Function is a sub program which consists of block of code(set of


instructions) that performs a particular task.
 For complex problems, the problem is been divided into smaller and
simpler tasks during algorithm design.
Benefits of Using Functions

 Reduction in line of code


 code reuse
 Better readability
 Information hiding
 Easy to debug and test
 Improved maintainability

Example:
Algorithm for addition of two numbers using function
Main function()
Step 1: Start
Step 2: Call the function add()
Step 3: Stop

sub function add()


Step 1: Function start
Step 2: Get a, b Values
Step 3: add c=a+b
Step 4: Print c
Step 5: Return
NOTATIONS
FLOW CHART
Flow chart is defined as graphical representation of the logic for problem
solving. The purpose of flowchart is making the logic of the program clear
in a visual representation.

Rules for drawing a flowchart

1. The flowchart should be clear, neat and easy to follow.


2. The flowchart must have a logical start and finish.
3. Only one flow line should come out from a process symbol.
4. Only one flow line should enter a decision symbol. However, two or three
flow lines may leave the decision symbol.

5. Only one flow line is used with a terminal symbol.

6. Within standard symbols, write briefly and precisely.


7. Intersection of flow lines should be avoided.

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
analysed 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.
PSEUDO CODE:
 Pseudo code consists of short, readable and formally styled English
languages used for explain an algorithm.
 It does not include details like variable declaration, subroutines.
 It is easier to understand for the programmer or non programmer to
understand the general working of the program, because it is not based on
any programming language.
 It gives us the sketch of the program before actual coding.
 It is not a machine readable
 Pseudo code can’t be compiled and executed.
 There is no standard syntax for pseudo code.

Guidelines for writing pseudo code:

 Write one statement per line
 Capitalize initial keyword
 Indent to hierarchy
 End multiline structure
 Keep statements language independent

Common keywords used in pseudocode

The following gives common keywords used in pseudocodes.


1. //: This keyword used to represent a comment.
2. BEGIN,END: Begin is the first statement and end is the last statement.
3. INPUT, GET, READ: The keyword is used to inputting data.
4. COMPUTE, CALCULATE: used for calculation of the result of the given
expression.
5. ADD, SUBTRACT, INITIALIZE used for addition, subtraction and
initialization.
6. OUTPUT, PRINT, DISPLAY: It is used to display the output of the
program.
7. IF, ELSE, ENDIF: used to make decision.
8. WHILE, ENDWHILE: used for iterative statements.
9. FOR, ENDFOR: Another iterative incremented/decremented tested
automatically.
Syntax for if else:
IF (condition)THEN
statement
...
ELSE
statement
...
ENDIF
Example: Greates of two numbers
BEGIN
READ a,b
IF (a>b) THEN
DISPLAY a is greater
ELSE
DISPLAY b is greater
END IF
END
Syntax for For:
FOR( start-value to end-value) DO
statement
...
ENDFOR

Example: Print n natural numbers


BEGIN
GET n
INITIALIZE i=1
FOR (i<=n) DO
PRINT i
i=i+1
ENDFOR
END
Syntax for While:
WHILE (condition) DO
statement
...
ENDWHILE

Example: Print n natural numbers


BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END

Advantages:

 Pseudo is independent of any language; it can be used by most


programmers.
 It is easy to translate pseudo code into a programming language.
 It can be easily modified as compared to flowchart.
 Converting a pseudo code to programming language is very easy as
comparedwith converting a flowchart to programming language.

Disadvantages:

 It does not provide visual representation of the program’s logic.


 There are no accepted standards for writing pseudo codes.
 It cannot be compiled nor executed.
 For a beginner, It is more difficult to follow the logic or write pseudo
code ascompared to flowchart.
Example:

Addition of two numbers:

BEGIN
GET a,b
ADD c=a+b
PRINT c
END

PROGRAMMING LANGUAGE

A programming language is a set of symbols and rules for instructing a


computer to perform specific tasks. The programmers have to follow all the
specified rules before writing program using programming language. The
user has to communicate with the computer using language which it can
understand.
Types of programming language

1. Machine language
2. Assembly language
3. High level language
Machine language:

The computer can understand only machine language which uses 0’s and
1’s. In machine language the different instructions are formed by taking
different combinations of 0’s and 1’s.

Advantages:
Translation free:
Machine language is the only language which the computer understands.
For executing any program written in any programming language, the
conversion to machine language is necessary. The program written in
machine language can be executed directly on computer. In this case any
conversion process is not required.
High speed
The machine language program is translation free. Since the conversion
time is saved, the execution of machine language program is extremely fast.
Disadvantage:
 It is hard to find errors in a program written in the machine language.
 Writhing program in machine language is a time consuming process.

Machine dependent: According to architecture used, the computer differs


from each other. So machine language differs from computer to computer.
So a program developed for a particular type of computer may not run on
other type of computer.

Assembly language:
To overcome the issues in programming language and make the
programming process easier, an assembly language is developed which is
logically equivalent to machine language but it is easier for people to read,
write and understand.
 Assembly language is symbolic representation of machine language.
Assembly languages are symbolic programming language that uses
symbolic notation to represent machine language instructions. They are
called low level language because they are so closely related to the
machines.
Assembler
Assembler is the program which translates assembly language instruction
in to a machine language.

 Easy to understand and use.


 It is easy to locate and correct errors.

Disadvantage
Machine dependent
The assembly language program which can be executed on the machine
depends on the architecture of that computer.
Hard to learn
It is machine dependent, so the programmer should have the hardware
knowledge to create applications using assembly language.
Less efficient
 Execution time of assembly language program is more than machine
language program.
 Because assembler is needed to convert from assembly language to
machine language.

High level language

High level language contains English words and symbols. The specified
rules are to be followed while writing program in high level language. The
interpreter or compilers are used for converting these programs in to
machine readable form.
Translating high level language to machine language
The programs that translate high level language in to machine language are
called interpreter or compiler.
Compiler:
A compiler is a program which translates the source code written in a high
level language in to object code which is in machine language program.
Compiler reads the whole program written in high level language and
translates it to machine language. If any error is found it display error
message on the screen.
Interpreter
Interpreter translates the high level language program in line by line
manner. The interpreter translates a high level language statement in a
source program to a machine code and executes it immediately before
translating the next statement. When an error is found the execution of the
program is halted and error message is displayed on the screen.

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.

They are divided into following categories:

1. Interpreted programming languages


2. Functional programming languages
3. Compiled programming languages
4. Procedural programming languages
5. Scripting programming language
6. Markup programming language
7. Concurrent programming language
8. Object oriented programming language
Interpreted programming languages:

An interpreted language is a programming language for which most of its


implementation executes instructions directly, without previously
compiling a program into machine language instructions. The interpreter
executes the program directly translating each statement into a sequence of
one or more subroutines already compiled into machine code.
Examples:
Pascal
Python

Functional programming language:

Functional programming language defines every computation as a


mathematical evaluation. They focus on the programming languages are
bound to mathematical calculations
Examples:
Clean
Haskell

Compiled Programming language:

A compiled programming is a programming language whose


implementation are typically compilers and not interpreters.
It will produce a machine code from source code.
Examples:
C
C++
C#
JAVA
Procedural programming language:

Procedural (imperative) programming implies specifying the steps that the


programs should take to reach to an intended state.
A procedure is a group of statements that can be referred through a
procedure call. Procedures help in the reuse of code. Procedural
programming makes the programs structured and easily traceable for
program flow.
Examples:
Hyper talk
MATLAB

Scripting language:

Scripting language are programming languages that control an application.


Scripts can execute independent of any other application. They are mostly
embedded in the application that they control and are used to automate
frequently executed tasks like communicating with external program.
Examples:
Apple script
VB script

Markup languages:

A markup language is an artificial language that uses annotations to text


that define hoe the text is to be displayed.
Examples:
HTML
XML
Concurrent programming language:
Concurrent programming is a computer programming technique that
provides for the execution of operation concurrently, either with in a single
computer or across a number of systems.
Examples:
Joule
Limbo

Object oriented programming language:


Object oriented programming is a programming paradigm based on the
concept of objects which may contain data in the form of procedures often
known as methods.
Examples:
Lava
Moto

[PTO]
ALGORITHMIC PROBLEM SOLVING:
Algorithmic problem solving is solving problem that require the
formulation of an algorithm for the solution.

Understanding the Problem


 It is the process of finding the input of the problem that the algorithm
solves.
 It is very important to specify exactly the set of inputs the algorithm
needs to handle.
 A correct algorithm is not one that works most of the time, but one that
works correctly for all legitimate inputs.

Ascertaining the Capabilities of the Computational Device


 If the instructions are executed one after another, it is called sequential
algorithm.
 If the instructions are executed concurrently, it is called parallel
algorithm.

Choosing between Exact and Approximate Problem Solving


 The next principal decision is to choose between solving the problem
exactly or solving it approximately.
 Based on this, the algorithms are classified as
exact algorithm and approximationalgorithm.

Deciding a data structure:


 Data structure plays a vital role in designing and analysis the algorithms.
 Some of the algorithm design techniques also depend on the structuring
data specifying a problem’s instance
 Algorithm+ Data structure=programs.

Algorithm Design Techniques


 An algorithm design technique (or “strategy” or “paradigm”) is a
general approach to solving problems algorithmically that is applicable to a
variety of problems from different areas of computing.
 Learning these techniques is of utmost importance for the following
reasons.
 First, they provide guidance for designing algorithms for new problems,
 Second, algorithms are the cornerstone of computer science

Methods of Specifying an Algorithm


 Pseudocode is a mixture of a natural language and programming
language-like constructs. Pseudocode is usually more precise than natural
language, and its usage often yields more succinct algorithm descriptions.
 In the earlier days of computing, the dominant vehicle for specifying
algorithms was a flowchart, a method of expressing an algorithm by a
collection of connected geometric shapes containing descriptions of the
algorithm’s steps.
 Programming language can be fed into an electronic computer
directly. Instead, it needs to be converted into a computer program written
in a particular computer language. We can look at such a program as yet
another way ofspecifying the algorithm, although it is preferable to
consider it as the algorithm’s implementation.
Proving an Algorithm’s Correctness
 Once an algorithm has been specified, you have to prove its correctness.
That is, you have to prove that the algorithm yields a required result for
every legitimate input in a finite amount of time.
 A common technique for proving correctness is to use mathematical
induction because an algorithm’s iterations provide a natural sequence of
steps needed for such proofs.
 It might be worth mentioning that although tracing the algorithm’s
performance for a few specific inputs can be a very worthwhile activity, it
cannot prove the algorithm’s correctness conclusively. But in order to show
that an algorithm is incorrect, you need just one instance of its input for
which the algorithm fails.

Analysing an Algorithm
1. Efficiency.
Time efficiency, indicating how fast the algorithm runs,
Space efficiency, indicating how much extra memory it uses.

2. simplicity.
 An algorithm should be precisely defined and investigated with
mathematical expressions.
 Simpler algorithms are easier to understand and easier to program.
 Simple algorithms usually contain fewer bugs.

Coding an Algorithm
 Most algorithms are destined to be ultimately implemented as computer
programs. Programming an algorithm presents both a peril and an
opportunity.
 A working program provides an additional opportunity in allowing an
empirical analysis of the underlying algorithm. Such an analysis is based on
timing the program on several inputs and then analysing the results
obtained.

SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS:


1. iterations
2. Recursions
1. Iterations:
A sequence of statements is executed until a specified condition is true is
called iterations.
1. for loop
2. While loop

Syntax for For:


FOR( start-value to end-value) DO
Statement
...
ENDFOR

Example: Print n natural numbers


BEGIN
GET n
INITIALIZE i=1
FOR (i<=n) DO
PRINT i
i=i+1
ENDFOR
END

Syntax for While:


WHILE (condition) DO
Statement
...
ENDWHILE

Example: Print n natural numbers


BEGIN
GET n
INITIALIZE i=1
WHILE(i<=n) DO
PRINT i
i=i+1
ENDWHILE
END

Recursions:
 A function that calls itself is known as recursion.
 Recursion is a process by which a function calls itself repeatedly until
some specified condition has been satisfied.

Algorithm for factorial of n numbers using recursion:

Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5: Stop
Sub function factorial(n):
Step1: if(n==1) then fact=1 return fact
Step2: else fact=n*factorial(n-1) and return fact

Pseudo code for factorial using recursion:

Main function:
BEGIN
GET n
CALL factorial(n)
PRINT fact
BIN

Sub function factorial(n):


IF(n==1) THEN
fact=1
RETURN fact
ELSE
RETURN fact=n*factorial(n-1)
Briefly describe iteration and recursion. Illustrate with an example.

Example: Iterative algorithm for factorial of a number

Example: Recursive algorithm for factorial of number

More examples:

Write an algorithm to find area of a rectangle


Step 1: Start
Step 2: get l,b values
Step 3: Calculate A=l*b
Step 4: Display A
Step 5: Stop

BEGIN
READ l,b
CALCULATE A=l*b
DISPLAY A
END

Write an algorithm for Calculating area and circumference of circle


Step 1: Start
Step 2: get r value
Step 3: Calculate A=3.14*r*r
Step 4: Calculate C=2.3.14*r
Step 5: Display A,C
Step 6: Stop
BEGIN
READ r
CALCULATE A and C
A=3.14*r*r
C=2*3.14*r
DISPLAY A
END

Write an algorithm for Calculating simple interest

Step 1: Start
Step 2: get P, n, r value
Step3:Calculate
SI=(p*n*r)/100
Step 4: Display S
Step 5: Stop
BEGIN
READ P, n, r
CALCULATE S
SI=(p*n*r)/100
DISPLAY SI
END

Write an algorithm to find minimum of 3 numbers in a list. ALGORITHM


: Find Minimum of 3 numbers in a list
Step 1: Start
Step 2: Read the three numbers A, B, C
Step 3: Compare A and B.
If A is minimum, go to step 4 else go to step 5. Step 4: Compare A and C.
If A is minimum, output “A is minimum” else output “C is minimum”. Go to
step 6.
Step 5: Compare B and C.
If B is minimum, output “B is minimum” else output “C is minimum”.
Step 6: Stop
Write the pseudo code for Towers of Hanoi.

Pseudocode
START
Procedure Hanoi(disk, source, dest, aux)
IF disk = = 0, THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest)
move disk from source to dest
Hanoi(disk - 1, aux, dest, source)
END IF
END Procedure

Write an algorithm and give the pseudo code to guess an integer number in

a range.

Algorithm:
step 1: Start the program
step 2: Read an 'n' number
step 3: Read an Guess number
step 4: if Guess> n; print "Your Guess too high" Step 5: elif Guess <n ; print
"Your Guess
too low" step 6: elif Guess = = n; print "Good job"
Step 7: else print"Nope "
Step :8 Stop the program

Pseudocode:
BEGIN
READ n
READ Guess = 20
IF Guess> n
print"Your Guess too High" elif Guess< n
print "Your Guess too low" elif Guess = = 20
print "Good Job"
ELSE
print"Nope"

8. a) Write an algorithm to insert a card in a list of sorted cards.

ALGORITHM:
Step 1: Start
Step 2: Declare the variables N, List[],I and X
Step 3: READ Number of element in sorted list as N
Step 4: SET i=0
Step 5: IF i<N THEN go to step 6 ELSE go to step 9
Step 6: READ Sorted list element as List[i]
Step 7: i=i+1
Step 8: go to step 5
Step 9: READ Element to be insert as X
Step 10: SET i=N-1
Step 11: IF i>0 AND X<List[i] THEN go to step 12 ELSE go to step 15
Step 13: i=i-1
Step 14: go to step 11
Step 15: List[i+1]=X
Step 16: Stop

b) Write an algorithm to find the minimum number in a list.


Algorithm:
Step 1 : Start
Step 2 : Initialize the value of minimum = 0
Step 3 : Enter the input number (n) of items in a list.
Step 4 : Get all the elements using for loop and store it in a list.
Step 5: Assign the first element in a list as minimum.
Step 6: Compare maximum with the first element in a list,n.
Step 7: Repeat step 8,9 until list becomes empty.
Step 8 : If n is less than the minimum
Step 9 : Assign minimum = n
Step 10 : Display minimum

Pseudocode:
BEGIN
SET numlist=[ ]
GET n
FOR i=1 to n
GET numlist elements
ENDFOR
SET minimum = numlist[0]
FOR i in numlist
IF (n < minimum)
minimum = n
ENDIF
ENDFOR
PRINT minimum
END

What is Python?
Python is a general purpose, dynamic, high-level, and interpreted programming
language. It supports Object Oriented programming approach to develop
applications. It is simple and easy to learn and provides lots of high-level data
structures.

Python is easy to learn yet powerful and versatile scripting language, which makes it
attractive for Application Development.

Python's syntax and dynamic typing with its interpreted nature make it an ideal
language for scripting and rapid application development.
Python supports multiple programming pattern, including object-oriented,
imperative, and functional or procedural programming styles.

Python is not intended to work in a particular area, such as web programming. That
is why it is known as multipurpose programming language because it can be used
with web, enterprise, 3D CAD, etc.

We don't need to use data types to declare variable because it is dynamically


typed so we can write a=10 to assign an integer value in an integer variable.

Python makes the development and debugging fast because there is no compilation
step included in Python development, and edit-test-debug cycle is very fast.

Python History
o Python laid its foundation in the late 1980s.
o The implementation of Python was started in December 1989 by Guido Van
Rossum at CWI in Netherland.
o In February 1991, Guido Van Rossum published the code (labeled version
0.9.0) to alt.sources.
o In 1994, Python 1.0 was released with new features like lambda, map, filter,
and reduce.
o Python 2.0 added new features such as list comprehensions, garbage
collection systems.
o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was
designed to rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language,
which was capable of Exception Handling and interfacing with the Amoeba
Operating System.
o The following programming languages influence Python:
o ABC language.
o Modula-3

Why the Name Python?


There is a fact behind choosing the name Python. Guido van Rossum was reading
the script of a popular BBC comedy series "Monty Python's Flying Circus". It was
late on-air 1970s.

Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So
he decided to select naming Python after the "Monty Python's Flying Circus" for
their newly created programming language.
The comedy series was creative and well random. It talks about everything. Thus it is
slow and unpredictable, which made it very interesting.

Python is also versatile and widely used in every technical field, such as Machine
Learning, Artificial Intelligence, Web Development, Mobile Application, Desktop
Application, Scientific Calculation, etc.

Make it Clear Why We Want to Learn


The goal should be clear before learning the Python. Python is an easy, a vast
language as well. It includes numbers of libraries, modules, in-built functions and
data structures. If the goal is unclear then it will be a boring and monotonous
journey of learning Python. Without any clear goal, you perhaps won't make it done.

So, first figure out the motivation behind learning, which can anything be such as
knowing something new, develop projects using Python, switch to Python, etc. Below
are the general areas where Python is widely used. Pick any of them.

o Data Analysis and Processing


o Artificial Intelligence
o Games
o Hardware/Sensor/Robots
o Desktop Applications

Python Applications
Python is known for its general-purpose nature that makes it applicable in almost
every domain of software development. Python makes its presence in every
emerging field. It is the fastest-growing programming language and can develop any
application.

Here, we are specifying application areas where Python can be applied.


First Python Program
In this Section, we will discuss the basic syntax of Python, we will run a simple
program to print Hello World on the console.

Python provides us the two ways to run a program:

o Using Interactive interpreter prompt


o Using a script file

Interactive interpreter prompt


Python provides us the feature to execute the Python statement one by one at the
interactive prompt. It is preferable in the case where we are concerned about the
output of each line of our Python program.

To open the interactive mode, open the terminal (or command prompt) and type
python (python3 in case if you have Python2 and Python3 both installed on your
system).
Here, we get the message "Hello World !" printed on the console.

Using a script file (Script Mode Programming)


The interpreter prompt is best to run the single-line statements of the code.
However, we cannot write the code every-time on the terminal. It is not suitable to
write multiple lines of code.

Using the script mode, we can write multiple lines code into a file which can be
executed later. For this purpose, we need to open an editor like notepad, create a file
named and save it with .py extension, which stands for "Python".

print ("hello world"); #here, we have used print() function to print the message on th
e console.

Get Started with PyCharm


JetBrains provides the most popular and a widely used cross-platform IDE PyCharm to run
the python programs.

Basic Syntax of Python


Indentation and Comment in Python
Indentation is the most significant concept of the Python programming language.
Improper use of indentation will end up "IndentationError" in our code.

Indentation is nothing but adding whitespaces before the statement when it is


needed. Without indentation Python doesn't know which statement to be executed
to next. Indentation also defines which statements belong to which block. If there is
no indentation or improper indentation, it will display "IndentationError" and
interrupt our code.
Python indentation defines the particular group of statements belongs to the
particular block. The programming languages such as C, C++, java use the curly
braces {} to define code blocks.

In Python, statements that are the same level to the right belong to the same block.
We can use four whitespaces to define indentation. Let's see the following lines of
code.

Example -

1. list1 = [1, 2, 3, 4, 5]
2. for i in list1:
3. print(i)
4. if i==4:
5. break
6. print("End of for loop")

Output:

1
2
3
4
End of for loop

Explanation:

In the above code, for loop has a code blocks and if the statement has its code block
inside for loop. Both indented with four whitespaces. The last print() statement is not
indented; that's means it doesn't belong to for loop.

Comments in Python
Comments are essential for defining the code and help us and other to understand
the code. By looking the comment, we can easily understand the intention of every
line that we have written in code. We can also find the error very easily, fix them, and
use in other applications.

In Python, we can apply comments using the # hash character. The Python
interpreter entirely ignores the lines followed by a hash character. A good
programmer always uses the comments to make code under stable. Let's see the
following example of a comment.

1. name = "Thomas" # Assigning string value to the name variable

We can add comment in each line of the Python code.

1. Fees = 10000 # defining course fees is 10000


2. Fees = 20000 # defining course fees is 20000

Python Identifiers
Python identifiers refer to a name used to identify a variable, function, module, class,
module or other objects. There are few rules to follow while naming the Python
Variable.

o A variable name must start with either an English letter or underscore (_).
o A variable name cannot start with the number.
o Special characters are not allowed in the variable name.
o The variable's name is case sensitive.

VARIABLES:
o
o  A variable allows us to store a value by assigning it to a name,
which can be used later.
o  Named memory locations to store values.
o  Programmers generally choose names for their variables that are
meaningful.
o  It can be of any length. No space is allowed.
o  We don't need to declare a variable before using it. In Python, we
simply assign a value to a variable and it will exist.

o Assigning value to variable:


o
o Value should be given on the right side of assignment operator(=)
and variable on left side.
o >>>counter =45
o print(counter)
o Assigning a single value to several variables simultaneously:
o >>> a=b=c=100
o Assigning multiple values to multiple variables:
o >>> a,b,c=2,4,"ram"
KEYWORDS:
o
o  Keywords are the reserved words in Python.
o  We cannot use a keyword as variable name, function name or any
other identifier.
o  They are used to define the syntax and structure of the Python
language.
o  Keywords are case sensitive.

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,

Sequence:
 A sequence is an ordered collection of items, indexed by positive
integers.
 It is a combination of mutable (value can be changed) and
immutable (values cannot be changed) data types.
 There are three types of sequence data type available in Python, they are
1. Strings
2. Lists
3. Tuples

1. Strings
 A String in Python consists of a series or sequence of characters -
letters, numbers, and special characters.
 Strings are marked by quotes:
 single quotes (' ') Eg, 'This a string in single quotes'
 double quotes (" ") Eg, "'This a string in double quotes'"
 triple quotes(""" """) Eg, This is a paragraph. It is made up of multiple
lines and sentences."""
 Individual character in a string is accessed using a subscript (index).
 Characters can be accessed using indexing and slicing operations
Strings are immutable i.e. the contents of the string cannot be changed after
it is created.

Indexing:

 Positive indexing helps in accessing the string from the beginning


 Negative subscript helps in accessing the string from the end.
 Subscript 0 or –ve n(where n is length of the string) displays the first
element.
Example: A[0] or A[-5] will display “H”
 Subscript 1 or –ve (n-1) displays the second element.
Example: A[1] or A[-4] will display “E”

Operations on string:
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Member ship
2. Lists
 List is an ordered sequence of items. Values in the list are called
elements / items.
 It can be written as a list of comma-separated items (values)
between square brackets[ ].
 Items in the lists can be of different data types.

Operations on list:
Indexing
Slicing
Concatenation
Repetitions
Updation, Insertion, Deletion
3. Tuple:

 A tuple is same as list, except that the set of elements is enclosed in


parentheses instead of square brackets.
 A tuple is an immutable list. i.e. once a tuple has been created, you can't
add elements to a tuple or remove elements from the tuple.
 Benefit of Tuple:
 Tuples are faster than lists.
 If the user wants to protect the data from accidental changes, tuple can
be used.
 Tuples can be used as keys in dictionaries, while lists can't.

Altering the tuple data type leads to error. Following error occurs when
user tries to do.
>>> t[0]="a"
Trace back (most recent call last):
File "<stdin>", line 1, in <module>
Type Error: 'tuple' object does not support item assignment

Dictionaries:

 Lists are ordered sets of objects, whereas dictionaries are unordered


sets.
 Dictionary is created by using curly brackets. i,e. {}
 Dictionaries are accessed via keys and not via their position.
 A dictionary is an associative array (also known as hashes). Any key of
the dictionary is associated (or mapped) to a value.
 The values of a dictionary can be any Python data type. So dictionaries
are

unordered key-value-pairs(The association of a key and a value is called


a key-value pair )
Dictionaries don't support the sequence operation of the sequence data
types like strings, tuples and lists.
If you try to access a key which doesn't exist, you will get an error message:
>>> words = {"house" : "Haus", "cat":"Katze"}
>>> words["car"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'car'

STATEMENTS AND EXPRESSIONS:

Statements:
-Instructions that a Python interpreter can executes are called statements.
-A statement is a unit of code like creating a variable or displaying a value.
>>> n = 17
>>> print(n)
Here, The first line is an assignment statement that gives a value to n.
The second line is a print statement that displays the value of n.

Expressions:
-An expression is a combination of values, variables, and operators.
-A value all by itself is considered an expression, and also a variable.
So the following are all legal expressions:
>>> 42
42
>>> a=2
>>> a+3+2
7
>>> z=("hi"+"friend")
>>> print(z)
Hifriend

INPUT AND OUTPUT

INPUT: Input is data entered by user (end user) in the program.


In python, input () function is available for input.
Syntax for input() is:
variable = input (“data”)
Example:
>>> x=input("enter the name:") enter the name: george
>>>y=int(input("enter the number"))
enter the number 3
#python accepts string as default data type. conversion is required for type.

OUTPUT: Output can be displayed to the user using Print statement .


Syntax:
print (expression/constant/variable)
Example:
print ("Hello") Hello

Operators and Types of Operators - Python


OPERATORS:
 Operators are the constructs which can manipulate the value of
operands.
 Consider the expression 4 + 5 = 9. Here, 4 and 5 are called
operands and + is called operator

Types of Operators:
Python language supports the following types of operators
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

Arithmetic operators:

They are used to perform mathematical operations like addition,


subtraction, multiplication etc. Assume, a=10 and b=5
Examples
a=10
b=5
print("a+b=",a+b)
print("a-b=",a-b)
print("a*b=",a*b)
print("a/b=",a/b)
print("a%b=",a%b)
print("a//b=",a//b)
print("a**b=",a**b)

Output:
a+b= 15
a-b= 5
a*b= 50
a/b= 2.0
a%b= 0
a//b= 2
a**b= 100000

Comparison (Relational) Operators:

 Comparison operators are used to compare values.


 It either returns True or False according to the condition. Assume,
a=10 and b=5
Example
a=10
b=5
print("a>b=>",a>b)
print("a>b=>",a<b)
print("a==b=>",a==b)
print("a!=b=>",a!=b)
print("a>=b=>",a<=b)
print("a>=b=>",a>=b)

Output:
a>b=> True
a>b=> False
a==b=> False
a!=b=> True
a>=b=> False
a>=b=> True
Assignment Operators:

-Assignment operators are used in Python to assign values to variables.

Example
a = 21
b = 10
c=0
c=a+b
print("Line 1 - Value of c is ", c)
c += a
print("Line 2 - Value of c is ", c)
c *= a
print("Line 3 - Value of c is ", c)
c /= a
print("Line 4 - Value of c is ", c)
c= 2 c %= a
print("Line 5 - Value of c is ", c) c **= a
print("Line 6 - Value of c is ", c) c //= a
print("Line 7 - Value of c is ", c)

Output
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864

Logical Operators:
Logical operators are the and, or, not operators.

Example
a = True
b = False
print('a and b is',a and b)
print('a or b is',a or b)
print('not a is',not a)

Output
x and y is False
x or y is True
not x is False

Bitwise Operators:

A bitwise operation operates on one or more bit patterns at the level of


individual Bits

Example:
Let x = 10 (0000 1010 in binary) and
y = 4 (0000 0100 in binary)

Example
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0
c = a & b; # 12 = 0000 1100
print "Line 1 - Value of c is ", c
c = a | b; # 61 = 0011 1101
print "Line 2 - Value of c is ", c
c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c
c = ~a; # -61 = 1100 0011
print "Line 4 - Value of c is ", c
c = a << 2; # 240 = 1111 0000
print "Line 5 - Value of c is ", c
c = a >> 2; # 15 = 0000 1111
print "Line 6 - Value of c is ", c

Output
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

Membership Operators:

 Evaluates to find a value or a variable is in the specified sequence of


string, list, tuple, dictionary or not.
 Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not
in operators are used.
Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False

Identity Operators
They are used to check if two values (or variables) are located on the same
part of the memory.

Example
x=5
y=5
x2 = 'Hello'
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)

Output
False
True
OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of
evaluation depends on the order of operations.

You might also like