lOMoARcPSD|28387430
CORE - I PYTHON PROGRAMMING
I YEAR / I SEM
UNIT – I
Introduction: The essence of computational problem solving – Limits of computational problem
solving-Computer algorithms-Computer Hardware-Computer Software-The process of
computational problem solving-Python programming language - Literals - Variables and
Identifiers - Operators - Expressions and Data types.
UNIT - II
Control Structures: Boolean Expressions - Selection Control - If Statement- Indentation in
Python- Multi-Way Selection -- Iterative Control- While Statement- Infinite loops- Definite vs.
Indefinite Loops- Boolean Flags and Indefinite Loops. Lists: List Structures - Lists in Python -
Iterating over lists in Python.
UNIT - III
Functions: Program Routines- Defining Functions- More on Functions: Calling Value-Returning
Functions- Calling Non-Value-Returning Functions- Parameter Passing - Keyword Arguments in
Python - Default Arguments in Python-Variable Scope.
UNIT - IV
Objects and their use: Software Objects - Turtle Graphics – Turtle attributes-Modular Design:
Modules - Top-Down Design - Python Modules - Text Files: Opening, reading and writing text
files - String Processing - Exception Handling.
UNIT - V
Dictionaries and Sets: Dictionary type in Python - Set Data type. Object Oriented Programming
using Python: Encapsulation - Inheritance – Polymorphism. Recursion: Recursive Functions.
TEXT BOOK:
1. Charles Dierbach, “Introduction to Computer Science using Python - A computational
Problem solving Focus”, Wiley India Edition, 2015.
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
REFERENCE BOOKS:
1. Mark Lutz, “Learning Python Powerful Object Oriented Programming”, O’reilly Media 2018,
5th Edition.
2. Timothy A. Budd, “Exploring Python”, Tata MCGraw Hill Education Private Limited 2011,
1st Edition.
3. Allen Downey, Jeffrey Elkner, Chris Meyers, “How to think like a computer scientist: learning
with Python”, 2012.
4. Sheetal Taneja & Naveen kumar, “Python Programming a Modular approach – A Modular
approach with Graphics, Database, Mobile and Web applications”, Pearson, 2017.
5. Ch Satyanarayana M Radhika Mani, B N Jagadesh, “Python programming”, Universities Press
2018.
WEB REFERENCES
[Link]
[Link]
[Link]
[Link]
NPTEL & MOOC courses titled Python programming
[Link]
[Link]
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
UNIT - I
[Link]. Topic Page No.
1. Define computational problem solving.
2. Define computation.
3. Define algorithm.
4. Define essence of computational problem solving.
5. Explain limits of computational problem solving.
6. Explain algorithm.
7. Define hardware.
8. Explain digital computing.
9. Explain computer components.
10. Explain operating system.
11. Define software.
12. Define syntax.
13. Define semantics.
14. Define compiler.
15. Define interpreter.
16. Differentiate syntax and semantic errors
17. Define program debugging.
18. Explain computational problem solving
19. Explain about python.
20. Define basic I/O operations
21. Explain literals.
22. Explain variables.
23. Explain identifiers
24. Explain operators.
25. Explain expressions.
26. Explain data types.
5
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
I – CHAPTER: INTRODUCTION FUNDAMENTAL
1.1 Computer Science
Computer science is fundamentally about is computational problem solving —that is,
solving problems by the use of computation.
There are various areas of study in computer science including software engineering (the
design and implementation of large software systems), database management, computer
networks, computer graphics, computer simulation, data mining, information security,
programming language design, systems programming, computer architecture, human–
computer interaction, robotics, and artificial intelligence, among others.
Computation
One characterization of computation is given by the notion of an algorithm.
Algorithm
An algorithm to be a series of steps that can be systematically followed for producing the
answer to a certain type of problem.
The Essence of Computational Problem Solving
To solve a problem computationally, two things are needed:
Representation
Algorithm
A representation that captures all the relevant aspects of the problem, and an algorithm that
solves the problem by use of the representation.
Limits of Computational Problem Solving
1.2Computer Algorithms
Algorithms
An algorithm is a finite number of clearly described, unambiguous “doable” steps that
can be systematically followed to produce a desired result for given input in a finite amount of
time.
Algorithms and Computers: A Perfect Match
Most require the use of computers either because they would require too much time for a
person to apply, or involve so much detail as to make human error likely. Because computers can
execute instructions very quickly and reliably without error, algorithms and computers are a
perfect match.
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
EX:
1.3 Computer Hardware
Computer hardware comprises the physical part of a computer system. It includes the all-
important components of the central processing unit (CPU) and main memory. It also includes
peripheral components such as a keyboard, monitor, mouse, and printer.
1.3.1 Digital Computing: It’s All about Switches
It is essential that computer hardware be reliable and error free. The key to developing
reliable systems is to keep the design as simple as possible.
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
In digital computing, all information is represented as a series of digits. We are used to
representing numbers using base 10 with digits 0–9.
All information within a computer system is represented using only two digits, 0 and 1,
called binary representation.
Computer hardware, therefore, is based on the use of simple electronic “on/off” switches
called transistors that switch at very high speed.
Integrated circuits (“chips”), the building blocks of computer hardware, are comprised
of millions or even billions of transistors.
1.3.2 The Binary Number System
For representing numbers, any base (radix) can be used. For example, in base 2, there are
two possible digits (0, 1), in which each column value is a power of 2.
The term bit stands for bi nary digit. Therefore, every bit has the value 0 or 1. A byte is a
group of bits operated on as a single unit in a computer system, usually consisting of eight bits.
1.3.3 Fundamental Hardware Components
Central Processing Unit (CPU) is the “brain” of a computer system, containing digital
logic circuitry able to interpret and execute instructions.
Main memory is where currently executing programs reside, which the CPU can directly
and very quickly access. Main memory is volatile; that is, the contents are lost when the
power is turned off.
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
Secondary memory is nonvolatile, and therefore provides long-term storage of programs
and data. This kind of storage, for example, can be magnetic (hard drive), optical (CD or
DVD), or nonvolatile fl ash memory (such as in a USB drive).
Input/output devices include anything that allows for input (such as the mouse and
keyboard) or output (such as a monitor or printer).
Buses transfer data between components within a computer system, such as between the
CPU and main memory.
Fundamental Hardware Components
1.3.4 Operating Systems—Bridging Software and Hardware
An operating system is software that has the job of managing and interacting with the
hardware resources of a computer. Because an operating system is intrinsic to the
operation a computer, it is referred to as system software.
An operating system acts as the “middle man” between the hardware and executing
application programs.
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
1.3.5 Limits of Integrated Circuits Technology: Moore’s Law
Moore’s Law states that the number of transistors that can be placed on a single silicon
chip doubles roughly every two years.
1.4 Computer Software
Computer software is a set of program instructions, including related data and documentation
that can be executed by computer. They can be classified in two,
System Software
Application Software
System software is intrinsic to a computer system; application software fulfils users’ needs,
such as a photo-editing program.
1.4.1 Syntax, Semantics, and Program Translation
Syntax
The syntax of a language is a set of characters and the acceptable arrangements
sequences) of those characters.
Semantics
The semantics of a language is the meaning associated with each syntactically correct
sequence of characters.
Program Translation
A central processing unit (CPU) is designed to interpret and execute a specific set of
instructions represented in binary form (i.e., 1s and 0s) called machine code. Only
programs in machine code can be executed by a CPU.
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
10
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
Writing programs at this “low level” is tedious and error-prone. Therefore, most
programs are written in a “high-level” programming language such as Python. Since the
instructions of such programs are not in machine code that a CPU can execute, a
translator program must be used. There are two fundamental types of translators.
Compiler
Interpreter
A compiler translates programs directly into machine code to be executed by the CPU.
Compiler
An interpreter, which executes program instructions in place of (“running on top of”)
the CPU. An interpreter can immediately execute instructions as they are entered. This is referred
to as interactive mode.
Interpreter
Program Debugging: Syntax Errors vs. Semantic Errors
Program debugging is the process of finding and correcting errors (“bugs”) in a
computer program. Programming errors are inevitable during program development.
Syntax errors are caused by invalid syntax (for example, entering prnt instead of print).
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
11
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
Semantic errors (generally called logic errors) are errors in program logic. Such errors
cannot be automatically detected, since translators cannot understand the intent of a given
computation. For example, if a program computed the average of three numbers as
follows,
(num1 1 num2 1 num3) / 2.0
1.4.3 Procedural vs. Object-Oriented Programming
Programming languages fall into a number of programming paradigms. The two major
programming paradigms in use today are procedural (imperative) programming and object-
oriented programming. Each provides a different way of thinking about computation. While most
programming languages only support one paradigm, Python supports both procedural and object-
oriented programming.
1.5 COMPUTATIONAL PROBLEM SOLVING
It is a process, with programming being only one of the steps. Before a program is written,
a design for the program must be developed. And before a design can be developed, the problem
to be solved must be well understood. Once written, the program must be thoroughly tested.
Process of Computational Problem Solving
1.5.1 Problem Analysis
Understanding the Problem
Once a problem is clearly understood, the fundamental computational issues for solving it
can be determined. For each of the problems discussed earlier, the representation is
straightforward.
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
12
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
For example the Man, Cabbage, Goat, Wolf (MCGW) problem, a brute-force algorithmic
approach of trying all possible solutions works very well, since there are a small number of
actions that can be taken at each step, and only a relatively small number of steps for reaching a
solution.
Knowing What Constitutes a Solution
Besides clearly understanding a computational problem, one must know what constitutes
a solution. For some problems, there is only one solution. For others, there may be a number (or
infinite number) of solutions. Thus, a program may be stated as finding,
A solution
An approximate solution
A best solution
All solutions
For example the MCGW problem, there are an infinite number of solutions since the man
could pointlessly row back and forth across the river an arbitrary number of times.
1.5.2 Program Design
Describing the Data Needed
For the Man, Cabbage, Goat, Wolf problem, a list can be used to represent the correct
location (east and west) of the man, cabbage, goat, and wolf as discussed earlier, reproduced
below,
Man Cabbage Goat Wolf
[W, E, W, E]
Describing the Needed Algorithms
When solving a computational problem, either suitable existing algorithms may be found
or new algorithms must be developed. For the MCGW problem, there are standard search
algorithms that can be used.
1.5.3 Program Implementation
Since we are programming in Python, the implementation needs to be expressed in a
syntactically correct and appropriate way, using the instructions and features available in Python.
1.5.4 Program Testing
Software testing is a crucial part of software development. Testing is done incrementally
as a program is being developed, when the program is complete, and when the program needs to
be updated.
1.6 The Python Programming Language
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
13
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
1.6.1 About Python
Guido van Rossum is the creator of the Python programming language, first released in
the early 1990s. Its name comes from a 1970s British comedy sketch television show called
Monty Python’s Flying Circus. The development environment IDLE provided with Python
comes from the name of a member of the comic group.
Python has a simple syntax. Python programs are clear and easy to read. At the same time,
Python provides powerful programming features, and is widely used. Companies and
organizations that use Python include YouTube, Google, Yahoo, and NASA. Python is well
supported and freely available at [Link].
1.6.2 The IDLE Python Development Environment
IDLE is an integrated development environment (IDE). An IDE is a bundled set of
software tools for program development. This typically includes an editor for creating and
modifying programs, a translator for executing programs, and a program debugger. A
debugger provides a means of taking control of the execution of a program to aid in finding
program errors. Python is most commonly translated by use of an interpreter. The window that
provides this interaction is referred to as the Python shell. Interacting with the shell is much like
using a calculator.
1.6.3 The Python Standard Library
The Python Standard Library is a collection of built-in modules, each providing
specific functionality beyond what is included in the “core” part of Python.
1.6.4 A Bit of Python
Variables
One of the most fundamental concepts in programming is that of a variable. (Variables
are discussed in detail in Chapters 2.) A simple description of a variable is “a name that is
assigned to a value,”
EX:
n = 5 (variable n is assigned the value 5)
Some Basic Arithmetic Operators
The common arithmetic operators in Python are
+(addition)
-(subtraction)
*(multiplication)
/ (division)
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
14
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
** (exponentiation)
EX:
10 + 20, 25 – 15, 5 * 10, 20 / 10, 2 ** 4 (2 to the 4th power)
Basic Input and Output
Input
The programs that we will write request and get information from the user.
EX:
nam=input ('What is your name?: ')
Characters within quotes are called strings. This particular use of a string, for requesting input
from the user, is called a prompt. The input function displays the string on the screen to prompt
the user for input.
EX:
What is your name? : Krishna
Output
The print function is used to display information on the screen in Python. This may be
used to display a message.
EX:
>>> print ('Welcome to My First Program!')
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
II - CHAPTER: DATA AND EXPRESSIONS
2.1 Literals
2.1.1 What Is a Literal?
A literal is a sequence of one or more characters that stands for itself.
2.1.2 Numeric Literals
A numeric literal is a literal containing only the digits 0–9, a sign character (1 or 2) and
a possible decimal point. If a numeric literal contains a decimal point, then it denotes a floating-
point value, or “float” (e.g., 10.24); otherwise, it denotes an integer value (e.g., 10). Commas
are never used in numeric literals.
EX:
5+9
Limits of Range in Floating-Point Representation
There is no limit to the size of an integer that can be represented in Python. Floating-
point values, however, have both a limited range and a limited precision. Python uses a double-
precision standard format (IEEE 754) providing a range of 10 2 308 to 10 308 with 16 to 17
digits of precision. To denote such a range of values, floating-points can be represented in
scientific notation.
EX:
9.0045602e + 5 (9.0045602 * 10 5 , 8 digits of precision)
1.006249505236801e8 (1.006249505236801 * 10 8 , 16 digits of precision)
4.239e216 (4.239 *10 - 16 , 4 digits of precision)
Arithmetic overflow
A condition that occurs when a calculated result is too large in magnitude (size) to be
represented.
EX:
>>> 1.5e200 * 2.0e210
Arithmetic underflow
A condition that occurs when a calculated result is too small in magnitude to be
represented.
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
EX:
>>> 1.0e2300 / 1.0e100
Built-in format Function
The built-in format function can be used to produce a numeric string of a given floating-
point value rounded to a specific number of decimal places.
EX:
>>>12/5 2.4 >>>format (12/5, '.2f') 2.40
>>>5/7 0.7142857142857143 >>>format (5/7, '.2f') 0.71
2.1.3 String Literals
String literals , or “ strings ,” represent a sequence of characters, In Python, string
literals may be delimited (surrounded) by a matching pair of either single (') or double (") quotes.
Strings must be contained all on one line.
EX:
>>> print('Welcome to Python!')
String may contain zero or more characters, including letters, digits, special characters,
and blanks. A string consisting of only a pair of matching quotes (with nothing in between) is
called the empty string, which is different from a string containing only blank characters.
EX:
>>>print(‘’) “Empty string”
>>>print(‘ ‘)”Blank string”
The Representation of Character Values
Unicode is capable of representing over 4 billion different characters, enough to
represent the characters of all languages, past and present. Python’s (default) character encoding
uses UTF-8, an eight-bit encoding that is part of the Unicode standard.
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
2.1.4 Control Characters
Control characters are special characters that are not displayed on the screen. Rather,
they control the display of output (among other things). They are represented by a combination
of characters called an escape print sequence. '\n', represents the newline control character, used
to begin a new screen line.
EX:
('Hello\n Jennifer Smith')
2.1.5 String Formatting
The format function can be used to control how strings are displayed.
Syntax:
format (value, format_specifier)
Where value is the value to be displayed and format_specifier can contain a combination
of formatting options.
EX:
format('Hello', ' < 20') ➝ 'Hello ' Left justified
format('Hello', ' > 20') ➝' Hello' Right justified
format('Hello', '^20') ➝‘ Hello ‘ Centre justified
format(' ', '30') ➝' ' Blank space
format('.', '. < 30') ➝’………………… .’ Printing character
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
aximum length of 79 characters.
2.1.6 Imp
licit Implicit Line Joining
and There are certain delimiting characters that allow a logical program line to
Exp span more than on physical line. This includes matching parentheses, square brackets,
licit curly braces, and triple quotes.
Lin
e EX:
Join
ing print('Name:', student_name, 'Address:',
student_address, 'Number of Credits:',
S total_credits, 'GPA:', current_gpa)
o
m Explicit Line Joining
eti
m Program lines may be explicitly joined by use of the backslash (\) character.
es
a
pr
og EX:
ra
m
lin
e
m
ay
be
to
o
lo
ng
to
fit
in
th
e
Py
th
on
-
re
co
m
m
en
de
d
m
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
msecs_month) 1 \ (day_birth * numsecs_day)
nu
mse
cs_
190
0_d 2.2 Variables and Identifiers
ob
5 2.2.1 What Is a Variable?
((ye A variable is a name (identifier) that is associated with a value. A variable can be
ar_ assigned different values during a program’s execution. Variables are assigned values by
birt use of the assignment operator, “=”.
h2
190 EX:
0) * num =10, num =num+1
avg
_nu An immutable value is a value that cannot be changed.
mse
cs_
yea EX:
r) 1
\ N
( u
( m
m =
o 1
n 0
t K
h =
_ n
b u
i m
r
t
h
1
)
a
v
g
_
n
u
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
2.2.2 Var hat is your first name?') What is your
iabl first name? Krishna
e
Assi If the user hit return without entering any value, name would be assigned to the empty
gn string (''). All input is returned by the input function as a string type. Python provides
men built-in type conversion Functions.
t
and EX:
Key >>>int(input(‘Enter no’))
boa
rd
Inp 2.2.3 What Is an Identifier?
ut
Th An identifier is a sequence of one or more characters used to provide a name for a
e given program element. Python is case sensitive. Identifiers may contain letters and digits,
val but cannot begin with a digit. The underscore character, _, is also allowed to aid in the
ue readability of long identifier names. It should not be used as the first character, however,
ca as identifiers beginning with an underscore have special meaning in Python. Spaces are
n not allowed as part of an identifier.
co
meEX:
fro StdName, add2, e_id
m
the2.2.4 Keywords and Other Predefined Identifiers in Python
us
er A keyword is an identifier that has predefined meaning in a programming
by language.
us Therefore, keywords cannot be used as “regular”
e identifiers.
of
theEX:
inp
ut
fu
nct
ion
. 2.3 Operators
EX: 2.3.1 What Is an Operator?
>
>> An operator is a symbol that represents an operation that may be performed on
na one or more operands. An operand is a value that a given operator is applied. A unary
meoperator operates on only one operand. A binary operator operates on two operands, as
=i with the addition operator.
np
ut('
W
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
2.3.2 Arithmetic Operators
Python provides the arithmetic operators are
The division operator, /, produces “true division” regardless of its operand types. The
truncating division operator, //, produces either an integer or fl oat truncated result based on
20
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
the type of operands applied to. The modulus operator (%) gives the remainder of the division
of its operands.
2.4 Expressions and Data Types
2.4.1 What Is an Expression?
An expression is a combination of symbols (or single symbol) that evaluates to a value. A sub
expression is any expression that is part of a larger expression.
EX:
4 + (3 * k)
2.4.2 Operator Precedence
Operator precedence is the relative order that operators are applied in the evaluation of
expressions, defined by a given operator precedence table.
EX:
10 + 20 < 20 + 30 ➝ 30 < 50 ➝ True
10 < 20 and 30 < 20 or 30 < 40 ➝ True and False or True
➝ False or True ➝ True
2.4.3 Operator Associativity
Operator associativity is the order that operators are applied when having the same level
of precedence, specific to each operator.
EX:
(2+3) + 4 ➝ 9
2.4.4 What Is a Data Type?
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
21
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
A data type is a set of values, and a set of operators that may be applied to those values.
Integers, fl oats, and strings are part of a set of predefined data types in Python called the built-in
types. In static typing, a variable is declared as a certain type before it is used, and can only be
assigned values of that type. Python, however, uses dynamic typing. In dynamic typing, the data
type of a variable depends only on the type of value that the variable is currently holding.
2.4.5 Mixed-Type Expressions
A mixed-type expression is an expression containing operands of different type.
Operands of mixed-type expressions therefore must be converted to a common type. Values can
be converted in one of two ways—by implicit (automatic) conversion, called coercion, or by
explicit type conversion.
Coercion vs. Type Conversion
Coercion is automatically performed on mixed-type expressions only if the operands can
be safely converted, that is, if no loss of information will result.
Type conversion is the explicit conversion of operands to a specific type.
Type conversion can be applied even if loss of information results.
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
22
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
23
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
UNIT - II
[Link] Topic Page No.
1. What is a control structure?
2. Explain boolean expressions
3. Explain selection control?
4. Explain iterative control?
5. Define lists in python.
6. Define list operations.
7. Define list traversal.
8. Explain lists in python.
9. Explain iterating over lists (sequences) in python
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
III - CHAPTER: CONTROL STRUCTURES
3.1 What Is a Control Structure?
Control is the order that instructions are executed in a program. A control statement is a
statement that determines the control flow of a set of instructions. A control structure is a set of
instructions and the control statements controlling their execution. There are three fundamental
forms of control that programming languages provide,
Sequential control
Selection control
Iterative control
Sequential control is an implicit form of control in which instructions are executed in
the order that they are written.
Selection control is provided by a control statement that selectively executes instructions
Iterative control is provided by an iterative control statement that repeatedly executes
instructions.
3.2 Boolean Expressions (Conditions)
The Boolean data type contains two Boolean values, denoted as True and False in
Python. A Boolean expression is an expression that evaluates to a Boolean value.
3.2.1 Relational Operators
The relational operators in Python perform the usual comparison [Link]
expressions are a type of Boolean expression, since they evaluate to a Boolean result.
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
3.2.2 Membership Operators
Python provides a convenient pair of membership operators. These operators can be
used to easily determine if a particular value occurs within a specified list of values.
3.2.3 Boolean Operators
George Boole, in the mid-1800s, developed what we now call Boolean algebra. Boolean
algebra contains a set of Boolean (logical) operators, denoted by and, or, and not in Python.
these logical operators can be used to construct arbitrarily complex Boolean expressions.
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
EX:
>>>(n>10) and (n<15)
>>>(n==1)or(n==0)
>>>not(n=0)
3.2.4 Operator Precedence and Boolean Expressions
EX:
(10 < 20 and 30 < 20) or (30 < 40)
3.2.5 Short-Circuit (Lazy) Evaluation
In short-circuit (lazy) evaluation, the second operand of Boolean operators and
or is not evaluated if the value of the Boolean expression can be determined from the first
operand alone.
EX:
if n ! 5 0:
if 1/n < tolerance
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
3.2.6 Logically Equivalent Boolean Expressions
In numerical algebra, there are arithmetically equivalent expressions of different form.
3.3 Selection Control
A selection control statement is a control statement providing selective execution of
instructions. A selection control structure is a given set of instructions and the selection control
statement(s) controlling their execution.
3.3.1 If Statement
An if statement is a selection control statement based on the value of a given Boolean
expression. A statement that contains other statements, such as the if statement, is called a
compound statement.
EX:
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
3.3.2 Indentation in Python
In Python, however, indentation is used to associate and group statements. A header in
Python is a specific keyword followed by a colon. Headers that are part of the same compound
statement must be indented the same amount—otherwise, a syntax error will result.
The set of statements following a header in Python is called a suite (commonly called a
block). The statements of a given suite must all be indented the same amount. A header and its
associated suite are together referred to as a clause. A compound statement in Python may
consist of one or more clauses.
EX:
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
3.3.3 Multi-Way Selection
Nested if Statements
If statements can be nested in Python, resulting in multi-way selection.
29
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
EX:
credits 5 45
if credits .5 90:
print('Senior')
else:
if credits .5 60:
print('Junior')
else:
if credits .5 30:
print('Sophomore')
else:
if credits .5 1:
print('Freshman')
else:
print('* No Earned Credits *')
The elif Header in Python
Python has another header called elif (“else-if”) that provides multi-way selection in a
single if statement. A final else clause may be used for “catch-all” situations.
EX:
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
30
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
3.4 Iterative Control
An iterative control statement is a control statement providing the repeated execution of
a set of instructions. An iterative control structure is a set of instructions and the iterative control
Statement controlling their execution.
3.4.1 While Statement
A while statement is an iterative control statement that repeatedly executes a set of
statements based on a provided Boolean expression (condition). As long as the condition of a
while statement is true, the statements within the loop are (re)executed. Once the condition
becomes false, the iteration terminates and control continues with the first statement after the
while loop.
3.4.2 Input Error Checking
The while statement is well suited for input error checking in a program.
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
31
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
3.4.3 Infinite loops
An infinite loop is an iterative control structure that never terminates (or eventually
terminates with a system error). Infinite loops are generally the result of programming errors.
Such infinite loops can cause a program to “hang,” that is, to be unresponsive to the user. In such
cases, the program must be terminated by use of some special keyboard input (such as ctrl-C) to
interrupt the execution.
EX:
3.4.4 Definite vs. Indefinite Loops
A definite loop is a program loop in which the number of times the loop will iterate can
be determined before the loop is executed. Although it is not known what the value of n will be
until the input statement is executed, its value is known by the time the while loop is reached.
Thus, it will execute “n times.”
EX:
sum = 0
current = 1
n = input('Enter value: ')
while current <= n:
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
32
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
sum =sum +current
current = current + 1
An indefinite loop is a program loop in which the number of times that the loop will
iterate cannot be determined before the loop is executed.
EX:
which = input("Enter selection: ")
while which ! = 'F' and which ! = 'C':
which 5=input("Please enter 'F' or 'C': ")
Boolean Flags and Indefinite Loops
A single Boolean variable used as the condition of a given control statement is called a
Boolean flag.
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
33
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
IV - CHAPTER:LIST
4.1 List Structures
4.1.1 What Is a List?
A list is a linear data structure, meaning that its elements have a linear ordering. That is,
there is a first element, a second element, and so on. In which each item in the list is identified by
its index in which each item in the list is identified by its index value.
EX:
4.1.2 Common List Operations
Operations commonly performed on lists include retrieve, update, insert, delete (remove)
and append.
EX:
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
34
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
4.1.3 List Traversal
A list traversal is a means of accessing, one-by-one, the elements of a list.
EX:
4.2 Lists (Sequences) in Python
4.2.1 Python List Type
A list in Python is a mutable, linear data structure of variable length, allowing mixed-type
elements. Mutable means that the contents of the list may be altered. Lists in Python use zero
based indexing. Thus, all lists have index values 0 ... n-1, where n is the number of elements in
the list. Lists are denoted by a comma-separated list of elements within square brackets.
An empty list is denoted by an empty pair of square brackets, [].Elements of a list
are accessed by using an index value within square brackets.
EX:
lst 5 [1, 2, 3]
lst[0] ➝ 1 access of fi rst element
lst[1] ➝ 2 access of second element
lst[2] ➝ 3 access of third element
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
35
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
4.2.2 Tuples
A tuple is an immutable linear data structure. Thus, in contrast to lists, once a tuple is
defined, it cannot be altered. Otherwise, tuples and lists are essentially the same. To distinguish
tuples from lists, tuples are denoted by parentheses instead of square brackets.
EX:
student 5 ('John Smith', 48, 'Computer Science', 3.42)
Another difference between tuples and lists is that tuples of one element must include a
comma following the element. Otherwise, the parenthesized element will not be made into a
tuple.
An empty tuple is represented by a set of empty parentheses, (). (We shall later see the
usefulness of the empty tuple.) The elements of tuples are accessed the same as lists, with square
brackets, Thus, delete, update, insert, and append operations are not defined on tuples.
4.2.3 Sequences
A sequence in Python is a linearly ordered set of elements accessed by an index number.
Lists, tuples, and strings are all sequences. Strings, like tuples, are immutable ; therefore, they
cannot be altered.
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
36
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
4.2.4 Nested Lists
Lists and tuples can be nested within each other to construct arbitrarily complex data
structures.
EX:
class_grades 5=[ [85, 91, 89], [78, 81, 86], [62, 75, 77], ...]
class_grades[0][0] ➝ [85, 91, 89][0] ➝ 85
4.3 Iterating Over Lists (Sequences) in Python
4.3.1 For Loops
A for statement is an iterative control statement that iterates once for each element in a
specified sequence of elements. Thus, for loops are used to construct definite loops.
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
37
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
Variable k is referred to as a loop variable.
EX:
for ch in 'Hello':
print(ch)c
4.3.2 The Built-in range Function
Python provides a built-in range function that can be used for generating a sequence of
integers that a for loop can iterate over. The values in the generated sequence include the starting
value, up to but not including the ending value.
EX:
sum =0
for k in range(1, 11):
sum = sum + k
This for loop adds up the integer values 1–10. By default, the range function generates a
sequence of consecutive integers. A “step” value can be provided, however. Range (0, 11, 2)
produces the sequence [0, 2, 4, 6, 8, 10], with a step value of 2. A sequence can also be generated
“backwards” when given a negative step value. For example, range (10, 0, 2 1) produces the
sequence [10,9, 8, 7, 6, 5, 4, 3, 2, 1].
4.3.3 Iterating Over List Elements vs. List Index Values
An index variable is a variable whose changing value is used to access elements of an
indexed data structure. However, there are times when the loop variable must iterate over the
index values of a list instead.
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
38
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI
lOMoARcPSD|28387430
4.3.4 While Loops and Lists (Sequences)
For situations in which a sequence is to be traversed while a given condition is
true, a while loop is the appropriate control structure to use.
EX:
DURGADEVI D MCA [Link]
ASSISTANT PROFESSOR
DEPT., OF COMPUTER APPLICATIONS
PSVASC
CHENNAI