PYTHON Notes Unit1&Unit2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

UNIVERSITY COLLEGE OF ENGINEERING NAGERCOIL

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

REGULATION 2021
I YEAR - I SEMESTER
GE3151 - PROBLEM SOLVING AND PYTHON PROGRAMMING
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING COURSE OBJECTIVES:
 To understand the basics of algorithmic problem solving.
 To learn to solve problems using Python conditionals and loops.
 To define Python functions and use function calls to solve problems.
 To use Python data structures – lists, tuples, dictionaries to represent complex data.

 To do input/output with files in Python.

UNIT I COMPUTATIONAL THINKING AND PROBLEM SOLVING


Fundamentals of Computing – Identification of Computational Problems -Algorithms, building blocks
of algorithms (statements, state, control flow, functions), notation (pseudo code, flow chart,
programming language), algorithmic problem solving, simple strategies for developing algorithms
(iteration, recursion). Illustrative problems: find minimum in a list, insert a card in a list of sorted cards,
guess an integer number in a range, Towers of Hanoi.
UNIT II DATA TYPES, EXPRESSIONS, STATEMENTS
Python interpreter and interactive mode, debugging; values and types: int, float, boolean, string, and
list; variables, expressions, statements, tuple assignment, precedence of operators, comments;
Illustrative programs: exchange the values of two variables, circulate the values of n variables, distance
between two points.
UNIT III CONTROL FLOW, FUNCTIONS, STRINGS
Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained conditional
(if-elif-else); Iteration: state, while, for, break, continue, pass; Fruitful functions: return values,
parameters, local and global scope, function composition, recursion; Strings: string slices,
immutability, string functions and methods, string module; Lists as arrays. Illustrative programs:
square root, gcd, exponentiation, sum an array of numbers, linear search, binary search
UNIT IV LISTS, TUPLES, DICTIONARIES
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and methods;
advanced list processing – list comprehension; Illustrative programs: simple sorting, histogram,
Students marks statement, Retail bill preparation.
UNIT V FILES, MODULES, PACKAGES
Files and exception: text files, reading and writing files, format operator; command line
arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative programs: word
count, copy file, Voter‟s age validation, Marks range validation (0-100).
TOTAL : 45 PERIODS
COURSE OUTCOMES:
Upon completion of the course, students will be able to
CO1: Develop algorithmic solutions to simple computational problems.
CO2: Develop and execute simple Python programs.
CO3: Write simple Python programs using conditionals and looping for solving problems.
CO4: Decompose a Python program into functions.
CO5: Represent compound data using Python lists, tuples, dictionaries etc. CO6: Read and write data
from/to files in Python programs.
TEXT BOOKS:
Allen B. Downey, “Think Python: How to Think like a Computer Scientist”, 2nd Edition, O‟Reilly
Publishers, 2016.
Karl Beecher, “Computational Thinking: A Beginner's Guide to Problem Solving and
programming”, 1st Edition, BCS Learning & Development Limited, 2017.

REFERENCES:
Paul Deitel and Harvey Deitel, “Python for Programmers”, Pearson Education, 1st Edition, 2021.
G Venkatesh and Madhavan Mukund, “Computational Thinking: A Primer for Programmers and Data
Scientists”, 1st Edition, Notion Press, 2021.
John V Guttag, "Introduction to Computation and Programming Using Python:
With Applications to Computational Modeling and Understanding Data„„, Third Edition, MIT Press
2021
Eric Matthes, “Python Crash Course, A Hands – on Project Based Introduction to Programming”, 2nd
Edition, No Starch Press, 2019.
https://www.python.org/
Martin C. Brown, “Python: The Complete Reference”, 4th Edition, Mc-Graw Hill, 2018.
UNIT I
ALGORITHMIC PROBLEM SOLVING

Computing
Computing is the process of using computer technology to complete a given goal-oriented
task. Computing encompasses the design and development of software and hardware
systems for a wide range of task namely structuring, processing and managing any kind of
information.
Computational Thinking
Computational thinking is the process of identifying a clear step-by-step solution to a
complex problem. It begins with breaking down a problem into smaller pieces, recognizing
patterns and eliminating extraneous, then creating a step-by-step solution can be replicated.
It includes
Identify the problem to be solved.
Understand the problem.
Develop possible and feasible solutions.
Present the solutions in a way that a computer, a human, or both, can understand.

Steps in Computational Thinking


Decomposition: Break down a complex problem into smaller, more manageable parts.
Decomposition is an important part of computational thinking because it helps make a
problem more manageable. It also helps problem solvers to better define and understand the
problem being solved while enabling them to simplify the problem through pattern
recognition and abstraction.
Pattern recognition: Look for similarities among and within problems. This is the process
of identifying patterns or connections between different parts of the bigger problem. The
purpose of pattern recognition is to further simplify the problem by finding where details
may be similar–or different–as well as building a continued understanding of the more
complex problem.
Abstraction: Abstraction is the process of extracting the most relevant information from
each decomposed problem. This helps to define, or generalize what, exactly needs to be
done to solve the problem as a whole.
Algorithmic thinking: Develop a step-by-step solution to the problem, or the rules to
follow to solve the problem. The final component of computational thinking is algorithmic
thinking. This is the process of defining a step-by-step solution to the problem that can be
replicated for a predictable and reliable outcome.

Identification of Computational Problems


Computational problem
A computational problem is a problem that can be solved step-by-step with a computer.
These problems usually have a well-defined input, constraints, and conditions that the
output must satisfied.
Types of computational problems:
A decision problem is one which gives a boolean output as yes or no based on a condition.
For example: to check whether a given number is prime or not.
To guess whether a person buys a computer or not.
A search problem is a computational problem that finds the best way to attain the
information for a query or decision.
Example: Travelling Salesman Problem
A counting problem is the task of finding the number of elements of some set with a
particular property.
Example : Number of paths in a graph
An optimization problem is finding the "best" possible solution among all solution.
Example: Finding the shortest path
ALGORITHMS
What is algorithm?
An algorithm is a set of step-by-step procedure to accomplish a task or solve a problem.
or
An algorithm is a finite number of clearly described, unambiguous steps that can be
systematically followed to produce a desired result for given input in a finite amount of
time .
Features
An algorithm is a collection of well-defined, unambiguous and effectively
computable instructions, if execute it will return the proper output.
Well-defined- The instructions given in an algorithm should be simple and defined
well.
Unambiguous- The instructions should be clear,there should not be ambiguity .
Effectively computable- The instructions should be written step by step ,which helps
computer to understand the control flow.

BUILDING BLOCKS OF ALGORITHMS


Building blocks are necessary to decide how we want to manipulate units of work.
The basis of every algorithm is steps or blocks of operations.
The building blocks are:

 Statements
 State
 Control flow
 Functions
Statement:
Statement is a unit of code that instructs a computer to perform an action.
Statements may be an input statement or process statement or output statement.
Input statements carry the data to solve the problem.
Process statement perform operation on a given input
Output statement gives the processed result.
Further statements may be categorized into three types: expression statements, declaration
statements, and control flow statements
State:
State is the current condition of a program or part of a program. 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

 sequence
 selection
 iteration
Sequence
Sequence of actions that a program carries out one after another, unconditionally.
Selection
Control flow statements are able to make decisions based on the conditions.
Selection is the program construct that allows a program to choose between different
actions. Choose at most one action from several alternative conditions.

Entry

False Condition True


to make
Decision

Action 1 Action 2

The decision statements are:


 if
 if..else
 switch
IF :
The general form of the if construct can be:
IF (condition) then <process>
IF.. ELSE:
A condition flow can also be stated in the following manner:
IF (condition) then
process 1
ELSE
process 2
if the condition is true then process 1 is executed, else process 2 is executed.
Algorithm to find biggest among given two nos:
Step1: Start
Step 2: Get two numbers as input and store it in to a and b
Step 3: If a is greater than b then
Step 4: Print a is big
Step 5: else
Step 6: Print b is big
Step 7: Stop

Repetition
Repetition means, repeating an action or set of statements until certain condition is attained.
Repetition will reduce the number lines of code in a program. It is helpful in cases where a
set of codes need to be executed multiple times.
Repetition statements may be of two forms
 For

 While
While Statement:

"While" Loop is used to repeat a specific block of code an unknown number of times, until
a condition is met.
The general form is:
while ( condition is true )
execute statements
end
For statement:
“For” loop is used for iterating a specific number of times, often called a “counting”
loop. Two keywords, FOR and ENDFOR are used.
The general form is:
FOR (iteration conditions)
Sequence
END
Example for Repetition : calculate factorial no:
Step1: Start
Step 2: Read the number to compute factorial.
Step 3: Initialize i is equal to 1 and fact is equal to 1
Step 4: Repeat step 4.1 through step 4.2 until „i' is equal
to num

Step 4.1: fact = fact * i

Step 4.2: i = i+1


Step 5: Print fact
Step 6: Stop

Functions:
Functions are "self contained" modules of code that carry out a specific task. The problem
solving mechanism behind functions is to break larger problem into smaller manageable
pieces and solve the problem.
Uses of function
 enable the code reusability
 reducing code redundancy
 enhance code readability
 easy understanding and maintainability of the code
 testing and debugging much easier
Generally a function has function name, function body, return value and l i s t o f
parameter
function_name( parameters )
body of the function
return [value/expression]
Recursion
Recursion is a function calling itself until a specified a specified condition is met.
Example for recursion function(factorial using recursion)
Step 1 : Start
Step 2 : Read the number to compute factorial.

Step 3 : Call factorial(n)


Step 4 : End

Factorial(n)
Step 1 : fact is equal to 1
Step 2: IF n==1 then
return 1
ELSE
f=n*factorial(n-1)
Step 3 : print f
ALGORITHM NOTATIONS (EXPRESSING ALGORITHMS)
Algorithms can be expressed in many kinds of notation, including
Pseudocode
Pseudocode is a way to describe an algorithm or computer program in a readable, natural
language. Pseudocode is a blueprint for translating the logic of a program into a
programming language. It's not compiled or executed on computers, but is meant to be read
and understood by humans.
Guidelines for writing pseudo code
 Write one statement per line

 Indent to hierarchy
 Keep statements language independent
 Common keywords used in pseudo code
The following gives common keywords used in pseudo codes.
BEGIN,END: Represents beginning and end of code.
INPUT, GET, READ: to feed data.
COMPUTE, CALCULATE: to compute the given expression.
ADD, SUBTRACT, INITIALIZE to perform addition, subtraction and initialization.
OUTPUT, PRINT, DISPLAY: to display the output of the program.
IF, ELSE, ENDIF: decision making statements.
WHILE, ENDWHILE & FOR, ENDFOR: iterative statement.
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.
Flowchart
A flowchart is a pictorial or visual representation of the sequence of steps to solve a problem.
Flow chart is defined as graphical representation of the logic for problem solving.
Flowchart symbols
Symbol Name Function
Process Indicates any type of internal
operation inside the Processor or
Memory
Input / Output Used for any Input / Output (I/O)
operation. Indicates that the
computer is to obtain data or
output results
Decision Used to ask a question that can be
answered in a binary format (Yes/
No, True/False)
Connector Allows the flowchart to be drawn
without intersecting lines or
without a reverse flow
Predefined Process Used to invoke a subroutine or an
Interrupt program
Terminal Indicates the starting or ending of the
program, process, or interrupt
program
Flow Lines Shows direction of flow
Rules for drawing a flowchart
 The flowchart must have a logical start and finish.
 Only one flow line should come out from a process symbol.

 Only one flow line should enter a decision symbol. However, two or three flow
lines may leave the decision symbol.

NO
YES

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

 Within standard symbols, write briefly and precisely.


 Intersection of flow lines should be avoided.
Advantages of flowchart:
Communication: - Flowcharts are a visual way to communicate complex logic and the
flow of information, inputs, and logic in a system. This makes it easier for technical users
to communicate with others, such as team members, stakeholders, or clients.
Process Improvement: Helps in the identification of inefficiencies, redundancies, or
bottlenecks.
Effective analysis: - With the help of flowchart, problem can be analyzed in more
effective way.
Process documentation: - Flowcharts can be used to document a process and maintain
proper documentation standards. They can also be used as a reference point in the future.
Efficient Coding: - Flowcharts can provide clear instructions, making the coding process
more efficient.
Debugging: - Flowcharts can help programmers identify errors and trace the flow of logic
to find where the error occurs.
Disadvantages of flow chart:
Time-consuming: It can be time-consuming to create, especially for complex processes.
Complexity: Flowcharts can become difficult to follow for complex processes.
Limited detail: Flowcharts may lack the detail needed to fully understand a process.
Alterations: Redrawing a flowchart to make changes can be time-consuming and
expensive.
Reproduction: Flowchart symbols can't be typed, so you need to use software to create
shapes and plug words into them.
Sample Flowchart
Flowchart to find biggest among two numbers

Start

Read A, B

Yes No
Is A > B

Print B
Print A

End

Flow chart for biggest of three numbers

start

Read
A, B, C

No Is Yes
A>B

Yes Is No No Is Yes
B>C A>C

Print Print Print


‘B is the ‘C is the ‘A is the
largest number largest number largest number

stop
Roots of a quadratic equation ax2+bx+c=0

Start

Declare variables a, b, c, D, x1, x2,


rp and ip

Calculate discriminant
D b - 4ac

True is False
D > 0?

r1 (-b+ D)/2a ip -b/2a


r2 (-b- D)/2a rp -(D)/2a

x1 rp + j ip
x1 rp - j ip

Display r1 and r2

Stop
Flowchart to find factorial of given no
START

Fact 1, Num 0

Read Num

No
IS Num
> 1? Print Fact

Yes Stop

Fact Fact * Num

Num Num-1

Programming Language
Programming:
Programming is the process of taking an algorithm and encoding it into a notation, a
programming language, so that it can be executed by a computer.
Programming language:
A programming language is a computer language that is used by programmers (developers)
to communicate with computers. It is a set of instructions written in any specific language (
C, C++, Java, Python) to perform a specific task.

Computer Languages

Low Level Language Middle Level Language High Level Language


(Machine Language) (Assembly Language)
Low level Language (Machine level Language)
Low-Level language is the only language which can be understood by the computer. Low-
level language is also known as Machine Language. All the instructions of machine
language are written in the form of binary numbers 1's & 0's. A computer can directly
understand the machine language.
Advantages:
Direct access to hardware: Low-level languages allow developers to directly access
hardware resources, which can lead to faster and more efficient programs.
Hardware-specific code: Low-level languages allow developers to create code that is
highly specific to a particular hardware architecture.
System programming: Low-level languages are useful for tasks that require low-level
system programming or working with embedded systems.
More precise and reliable : Low-level languages give developers full control and access
to the memory, registers, and instructions.
More secure: Low-level languages can be more secure because they tend to have fewer
layers between the code and the actual hardware.
Disadvantages:
Complexity: Low-level languages are more complex and difficult to learn, write, read,
debug, and update than high-level languages.
Machine-dependent: Low-level languages are not portable and are dependent on the
machine they are written for.
Risk of human error: Low-level languages have a higher risk of human error.
Bugs and security issues: There is a higher risk of introducing bugs and security issues
because programmers need to manually manage memory allocation and deallocation.

Middle level Language(Intermediate Language)


A middle-level language is a computer language that uses symbols like letters, digits, and
special characters to create instructions. It serves as the bridge between the raw
hardware and programming layer of a computer system.
Assembly language
An assembly language is a type of middle-level language uses alphanumeric codes for a set
of instructions instead of the numeric codes. Binary code instructions in low-level language
are replaced with mnemonics and operands in middle-level language. Assembler is used to
translate middle-level language into low-level language.
High level Language (Human understandable Language)
High-level language is a computer language which can be understood by the human. High-
level language has a set of predefined words known as Keywords and a set of rules known
as Syntax to create instructions. Compiler or interpreter is used to convert high-level
language to low-level language.
Languages like FORTRAN,C, C++, JAVA, Python, etc., are examples of high-level
languages.
Advantages
Ease of learning and use. High-level languages often feature English-like syntax, makes
easier to learn and use.
Enhanced productivity. Programming in high-level languages is faster and more efficient
than low-level/mid-level languages.
Extra portability. Programs written in high-level languages are often portable across
different platforms with little or no modification.
No complex operations. Developer need not focus on complex operations like memory
management. They can focus on solving problems at a higher level.
Disadvantages
Less control over hardware. A high-level programming language gives programmer less
control over the computer's resources.
High resource consumption. Applications written in high-level languages may consume
many system resources regarding memory and processing power.
Dependency on libraries and frameworks.
ALGORITHMIC PROBLEM SOLVING
Algorithmic problem-solving is the process of designing and implementing a solution to a
problem using a series of steps or rules. These steps are often referred to as an algorithm.
The goal of algorithmic problem-solving is to find an efficient and effective solution to a
given problem. Why we need to go for algorithm to solve problem?
Algorithmic problem solving Process
Algorithm development process consists of the following steps.
 Understanding the Problem
 Decide on: computational means, exact vs. approximate solving, algorithm design
technique

 Design an algorithm

 Prove correctness
 Analyze the algorithm
 Code the algorithm
Understanding the Problem
The first step in algorithmic problem-solving is to understand the problem statement. This is
important because a clear understanding of the problem will guide the rest of the process and
helps in the design an effective solution. It also defines the requirement, constrains, inputs
and outputs of the problem. Inputs are the data or information that the algorithm will use to
solve the problem. Outputs are the results or solutions that the algorithm will produce. A
clear understanding of the problem statement will avoid misunderstandings and ensures that
the solution addresses the objective.
Decide on: computational means, exact vs. approximate solving, algorithm design
technique
Computational means addresses how the problem can be solved by means of using a
computer.
The next vital decision is to decide whether we prefer an exact or approximate solution to
the problem.
The third decision is the selection of algorithm design technique.
Design an Algorithm
Design Approaches : There are two approaches for designing an algorithm.
Top-Down Approach
Bottom-up approach
Top-Down Approach: In the top-down approach, a large problem is divided into small
sub-problem.
Bottom-up approach: Complex program is solved using a programming language and
then this is combined into a complete program.
Common Algorithmic Strategies are Greedy Method, Divide and Conquer, Dynamic
Programming, Linear Programming, Reduction, Backtracking, Branch and Bound
Understand the problem

Decide on:
computational means,
exact vs. approximate solving,
algorithm design technique

Design an algorithm

Prove correctness

Analyze the algorithm

Code the algorithm


Proving an Algorithm’s Correctness
Correctness of an algorithm is checking whether the algorithm produces the expected
output for all range of valid inputs and, eventually, terminates. Algorithm verification and
validation ensures the quality and correctness of an algorithm.
Verification: Checks that the algorithm performs as expected and produces accurate
results for a given set of input data and parameters.
Validation: Checks that the algorithm meets the intended specifications and requirements.
Analysing an Algorithm
The next step in algorithmic problem-solving is to analyze the solution. This involves
evaluating the time and space complexity of the algorithm, using Big O notation to describe
its performance.
Time and Space Complexity Analysis:
Time complexity refers to the amount of time it takes for the algorithm to run as a function
of the size of the input.
Space complexity refers to the amount of memory the algorithm uses as a function of the
size of the input.
Analyzing the time and space complexity of an algorithm can help you understand how it
will perform on different inputs and identify any potential performance issues.
Big O Notation:
Big O notation is a mathematical notation used to describe the time and space complexity
of an algorithm.
Coding an Algorithm
The final step in the process of algorithmic problem solving is coding. Coding is the
processes of writing instructions for computers to follow in order to perform
tasksProgramming languages provide the rules for building websites, apps, and other
computer-based technologies.
SIMPLE STRATEGIES FOR DEVELOPING ALGORITHMS
Developing an algorithm is a very important step in problem-solving. There are different
types of strategies that could be used to develop an algorithm to solve a problem.

 Iterations
 Recursions
Iterations:
A set of instructions or structures are repeated in a sequence, a specified number of times
or until a condition is met. Iteration is implemented in programming
using FOR and WHILE statements. It avoids code redundancy.

\
Programmer use a count-controlled iteration if they are aware of the number of times of
execution of the block of code. „For‟ loop is count-controlled iteration statement.
Programmer use Conditional iterations when they don't know how many iterations they
need to achieve their desired results. In such case they use a while loop .
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)

EXAMPLE ALGORITHMS (ILLUSTRATIVE PROBLEMS)


Find minimum in a list
Problem Description : Finding the smallest or minimum number from a given set of
numbers.
Inputs: A list of „n‟ numbers.
Outputs: Smallest number among the numbers in the list.
Algorithm:
Insert a card in a list of sorted cards
Algorithm:
Step1: Start
Step2: Read the new card value to be inserted
Step3: Find the correct position to insert,
Step4: Iterate from the end of the list to the beginning.
Step5: For each pair of adjacent cards, if the card on the right is smaller than the
Step6: Element on the left, the two cards are swapped.
Step7: If position cannot be found, then insert at the end.
Step8: Stop
Guess an integer number in a range
Tower of Hanoi
UNIT –II

DATA, EXPRESSIONS, STATEMENTS


Python interpreter and interactive mode; values and types: int, float, booleans, strings, and
lists; variables, expressions, statements, tuple assignment, precedence of operators,
comments; Illustrative programs: exchange the values of two variables, circulate the
values of n variables, test for leap year.
Python
Python is a general-purpose, high-level, Interpreted, dynamically typed, Interactive and
Object Oriented Programming Language, created by Guido van Rossum in 1991. It was
designed with an emphasis on code readability, and its syntax allows programmers to
express their concepts in fewer lines of code. The other major advantages of python is its
Open Source, platform independent and comes with rich ready-to-use modules and
functions. Python has many applications, including Web development, Game development,
Scientific and numeric computing, Artificial intelligence and machine learning, Business
applications, Audio or video applications and Image processing.
Python features
 Beginners Language
 Extensive Standard Library
 Cross Platform Compatibility

 Interactive Mode
 Portable and Extendable
 Databases and GUI Programming
 Scalable and Dynamic Semantics

 Automatic Garbage Collection


Python interpreter and interactive mode
Python is an interpreter-based language. A Python interpreter is a computer program that
translates Python code into machine code. The Python interpreter executes the Python code
in two modes: interactive mode and script mode.
Python interpreters
Python interpreters are available for many operating systems, allowing Python code to run
on a wide variety of systems.
>>> Prompt bytecode
Bytecode Virtual Program
or
Complier Machine Output
.py Script

.pyc Module
import

Two Parts
Python byte code compiler
The byte code compiler accepts human readable python expressions and statements
as input and produces machine readable python code as output.
A virtual Machine which executes python byte code.
The virtual machine accepts Python byte code as input. And executes the virtual machine
instructions represented by the byte code.
PYTHON MODES
Interactive mode
Interactive mode is a command line terminal without any additional options, a Python
prompt >>> appears and the Python interpreter works on the principle of REPL (Read,
Evaluate, Print, Loop). In interactive mode, interpreter displays the result(s) immediately.
That means, when we type Python expression / statement / command after the prompt
(>>>), the Python immediately responses with the output of it.
For Example:
>>> 5+10
15
>>> x=5
>>>y=6
>>> print x+y
11
Script Mode
For coding of more than few lines, we should always save the code with .py extension, so
that it can be modified and reused. Script mode is a way to run Python code by writing it in
a file and then executing it using the Python interpreter.
VALUES AND DATA TYPES
Identifier
Identifier is the name given to entities like class, functions, variables etc. in Python. It
helps differentiating one entity from another.
Rules for variable or identifier names
 Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to
Z) or digits (0 to 9) or an underscore (_).

 An identifier cannot start with a digit.


 Keywords cannot be used as identifiers.
 Case sensitive.
 Identifier can be of any length.

 Data Type

Data Types
Python Numbers
Number data types are used to store numeric values. Number objects are created when a
value is assigned to a variable.
Python supports four different numerical types
 int (signed integers)
 long (long integers, can also be represented in octal and hexadecimal)
Ex: 56789436L (long), 0o123 (Octal), 0x123 (Hexa)
 float (floating point real values)
Ex: –37.9, 37.3+e15, –32.74e100, 70.2–E15
 complex (complex numbers)
Ex: z = 5+3j
print(z.real)5
print(z.imag) 3
Boolean
A Boolean value is a data type that can hold two values namely true or false. In Python
Boolean data type is represented by the keyword bool.
String
String data type stores of a series or sequence of characters - letters, numbers, and special
characters. Strings are marked by single quotes („ „) , double quotes (“ “) or triple
quotes(“”” “””). Multiline string can be assigned by using three quotes. It is an immutable
data type
Lists
Lists are used to store multiple items in a single variable. List items are ordered, indexed,
mutable (changeable), and allow duplicate values. List is enclosed in square brackets [ ].
Tuple:
A tuple is a built-in data structure that stores a collection of elements in a defined order that
cannot be changed ( immutable). Tuple items are ordered, indexed, immutable
(unchangeable) , and allow duplicate values. Tuples elements are written within parenthesis
( ).
Set
Sets are used to store multiple items in a single variable. A set is a collection which
is unordered, unique (elements cannot be duplicate) and unindexed. Sets are written with
curly braces{}, separated by commas.
Dictionary
A Python dictionary is a collection of items, each item in a dictionary is a key-value pair. A
dictionary can be created by placing key:value pairs inside curly brackets {}, separated by
commas.
Variable
A variable in Python is a named memory location that stores data values. Python doesn't
require a command to declare a variable. A variable is created when you first assign a value
to it.
Variable Names
 Variable name can contain alpha-numeric characters and underscores (A-z, 0-9, and
_)

 Must begin with an alphabet or the underscore character


 It cannot start with a number
 They are case-sensitive
 A variable name cannot be any of the Python keywords.

Keywords
Keyword is a reserved word with a specific meaning and function, and they cannot be used
as variable names.
Expressions And Statements
Expressions
An expression a combination of operands, constant and operators that produces a value
when executed.
Statements
A statement is a single line of code that performs a specific task.
Operators
An operator is a symbol that represents a specific mathematical or logical action or process
performed on operands.
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:
Arithmetic operators are used to perform basic arithmetic operations like addition,
subtraction, multiplication etc.
Arithmetic operators in Python

Operator Meaning Format Example


If x=6
and y=5
+ Add two x+y 6+5=11
operands
– Subtract two x-y 6-5=1
operand
* Multiply two x*y 6*5=30
operands
/ Divide left x/y 6/5=1.2
operand
% Modulus – x%y 6%5=1
returns
remainder
// Floor Division x//y 6//5=1
(rounds down
the result to the
nearest integer
less than or
equal to the
division result.)
** Exponent x**y 65=7776
Comparison (Relational) Operators:
Comparison operators determine the equality or difference between variables or values and
return Boolean output “TRUE or FALSE”
Operator Meaning Format Example
If x=6
and y=5
> greater than x>y True
< less than x<y False
>= greater than or x>=y False
equal to
<= less than or x <=y False
equal to
== equal to x==y False
!= not equal to x!=y True
Logical Operators
Logical operators operates on conditional statements or expression and returns either a True
or a False.. They perform Logical AND, Logical OR, and Logical NOT operations.

Operato Description Example


rs
and Returns True if both statements x < 5 and x < 10
are true

or Returns True if one of the x < 5 or x < 4


statements is true
not Reverses the state. returns False not(x < 5 and x < 10)
if the result is true

Assignment Operators
Assigns the value of the right-hand operand to the left-hand operand. The basic assignment
operator is „=‟.

Operator Meaning Format Example


If x=10
+= Addition x+=8 18
assignment
–= Subtraction x–=8 2
assignment
*= Multiplication x*=8 80
assignment
/= Float division x/=8 1.25
assignment
//= Integer x //=8 1
division
assignment
%= Remainder x %=8 2
assignment
**= Exponent x **=8 108
assignment
Bitwise Operators:
Bitwise operation performs bitwise calculations on integers.

Operator Description Format Example


If x=20 , y= 25
& (Binary AND) Sets each bit to 1 if both x & y 10100 &
bits are 1
11001 =10000
O/P=16 (decimal
equivalent of 10000)
| (Binary OR) Sets each bit to 1 if one of x|y 10100 |
two bits is 1
11001 =11101
O/P=29 (decimal
equivalent of 11101)
^ (Binary XOR) Sets each bit to 1 if only x^y 10100 |
one of two bits is 1
11001 =01101
O/P=13 (decimal
equivalent of 01101)
~ ( Binary Ones One to zero and zeros to ~x -21
Complement) one
<< (Binary Left Shift left by pushing zeros x<<2 10100<<2
Shift) in from the right and let
the leftmost bits fall off =1010000
O/P=80 (decimal
equivalent of
1010000)
>> (Binary Right shift right by pushing x>>2 10100>>2
Shift) copies of the leftmost bit
in from the left, and let =101
the rightmost bits fall off O/P=5 (decimal
equivalent of 101)
Membership Operators:
These operators test whether a value is a member of a sequence. The sequence may be a
list, a string, or a tuple. We have two membership python operators- „in‟ and „not in‟.
Example:
in
books=[„python‟,‟java‟,‟html‟]
„html‟ in books
O/P: True
C++ in books
O/P: False
not in
books=[„python‟,‟java‟,‟html‟]
„html‟ not in books
O/P: False
C++ not in books
O/P: True

Identity Operator
Compare two objects to determine whether they share the same memory and refer to the
same object type. Identity operators are „is‟ and „is not‟.
is:
If two objects have the same identity, it returns True. Otherwise, it returns False. is not:
The 'is not' operator returns True if both the objects do not share the same memory
location and returns true if both are not identical.
Precedence of Operators
Operator precedence determines the order in which operations are performed in an
expression. When more than one operator appears in an expression, the order of
evaluation depends on the rules of precedence.

Operator Description
() Parentheses
** Exponentiation
+x -x ~x Unary plus, unary
minus, and bitwise
NOT
* / // % Multiplication,
division, floor
division, and modulus
+ - Addition and
subtraction
<< >> Bitwise left and right
shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
== != > >= < <= is is- Comparisons,
not in not-in identity, and
membership operators
not Logical NOT
and AND
or OR
Comments
Comments are hints that we add to our code to make it easier to understand. It is intended
only for the human reader. Comments are ignored by the interpreter during the execution of
the program.
There are two types of comments in Python:
 Single line Comments

 Multiline Comments
Single Line Comments: Single-line comment starts with the hashtag symbol (#) and
useful for supplying short explanations.
Multiple Line Comments
Python does not provide the facility for multi-line comments. We can use these string
literals as Python Comments.
„ Python multiline comments‟
""" Python multiline comments"""

You might also like