PYTHON UNIT-1
PYTHON PROGRAMMING
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, Input / output.
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 Flag.
String, List and Dictionary, Manipulations Building blocks of python
programs,Understanding and using ranges.
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. Recursion: Recursive Functions.
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 – Exception Handling.
UNIT - V Dictionaries and Sets: Dictionary type in Python - Set Data type.
Object Oriented Programming using Python: Encapsulation - Inheritance –
Polymorphism. Python packages: Simple programs using the built-in functions
of packages matplotlib, NumPy, pandas etc.
UNIT – I
What Is Computer Science?
It is about computational problem solving.
Computation is given by the notion of algorithm.
1) Introduction to Python:
Python is a widely used general-purpose, high level programming
language.
It was initially designed by Guido van Rossum in 1991 and developed
by Python Software Foundation.
There are two major Python versions- Python 2 and Python 3.
BP
PYTHON UNIT-1
2) The essence of computational problem Solving:
To solve a problem computationally two things are needed:
A representation that captures all the relevant aspects of the problem, and
an algorithm that solves the problem by use of the representation.
Example : Man, cabbage, goat and wolf problem.
Problem:
A man lives on the east side of a river. He wishes to bring a cabbage, a
goat, and a wolf to a village on the west side of the river to sell.
However, his boat is only big enough to hold himself, and either the
cabbage, goat, or wolf.
In addition, the man cannot leave the goat alone with the cabbage because
the goat will eat the cabbage, and he cannot leave the wolf alone with the
goat because the wolf will eat the goat. How does the man solve his
problem?
Solution:
Trying all possible solutions to a given problem is referred to as a brute
force approach .
The wolf does not eat cabbage, so the crossing can start with the goat.
The man leaves the goat and returns, puts the cabbage in the boat and
takes it across. On the other bank, he leaves the cabbage but takes the
goat.
He leaves the goat on the first bank and takes the wolf across. He leaves
the cabbage with the wolf and rows back alone.
He takes the goat across.
BP
PYTHON UNIT-1
3) Limitations of computational problem solving:
Once an algorithm for solving a given problem is developed or
found, an important question is, “Can a solution to the problem be
found in a reasonable amount of time?”
If not, then the particular algorithm is of limited practical use.
Eg: Travelling salesman problem
Game of chess.
The Traveling Salesman problem:
Any algorithm that correctly solves a given problem must solve the
problem in a reasonable amount of time, otherwise it is of limited
practical use.
Ref book: [Link]
4) Computer 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.
E.g.: Checking the number is prime or not.
History of Algorithm:
The word “algorithm” is derived from the ninth-century Arab
mathematician, Al-Khwarizmi who worked on “written processes to
achieve some goal.”
Computer algorithms are central to computer science. They provide step-
by-step methods of computation that a machine can carry out.
BP
PYTHON UNIT-1
Having high-speed machines (computers) that can consistently follow and
execute a given set of instructions provides a reliable and effective means
of realizing computation.
Algorithms and Computers: A Perfect Match.
Computers can execute instructions very quickly and reliably without
error, algorithms and computers are a perfect match.
Algorithm for finding even number or odd number:
1. Enter the number n
2. If the given number n is divided by 2 it is even
number.
3. Otherwise it is a odd number.
5) 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.
Computer hardware and the intrinsic use of binary representation in
computers.
Digital Computing:
It’s All about Switches. The information in system are stored in digital
format.
In digital computing, all information is represented as a series of digits.
Decimal numbers : 0-9 having base 10.
Represents there are 10 numbers.
BP
PYTHON UNIT-1
In current electronic computing, each digit is represented by a different
voltage level.
All information within a computer system is represented by the use of
only two digits, 0 and 1 , called binary representation .
In this representation, each digit can be one of only two possible values,
similar to a light switch that can be either on or off.
Transistors : switch at very high speed.
Integrated circuits : the building blocks of computer hardware, are comprised
of millions or even billions of transistors
The Binary Number System: For representing numbers, any base (radix) can
be used.
Base 10 representation
Decimal to binary conversion
99 :divide the number by 2.
99
49 -1
24 -1
12 -0
6 -0
3 -0
1 -1
Ans:1100011
BP
PYTHON UNIT-1
Binary to Decimal conversion:
The term bit stands for binary digit.
A byte is a group of bits operated on as a single unit in a computer
system, usually consisting of eight bits.
Fundamental components of Computer Hardware:
Operating System:
An operating system is software that has the job of managing and
interacting with the hardware resources of a computer.
An operating system acts as the“middle man” between the hardware and
executing application programs.
BP
PYTHON UNIT-1
An operating system is software that has the job of managing the
hardware resources of a given computer and providing a particular user
interface.
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.
6) COMPUTER SOFTWARE:
The first computer programs ever written were for a mechanical computer
designed by Charles Babbage in the mid-1800s.
Definition:
Computer software is a set of program instructions, including related data
and documentation, that can be executed by computer.
Types:
System Software
Application software.
Syntax, Semantics, and Program Translation:
Programming languages are languages just as “natural languages”
Syntax and semantics are important concepts that apply to all languages.
The syntax of a language is a set of characters and the acceptable
sequences of those characters.
The semantics of a language is the meaning associated with each
syntactically correct sequence of characters.
BP
PYTHON UNIT-1
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 .
A compiler is a translator program that translates programs directly into
machine code to be executed by the CPU.
An interpreter executes program instructions in place of (“running on top
of”) the CPU.
Program Debugging:
Syntax Errors vs. Semantic Errors:
Program debugging is the process of finding and correcting errors (
“bugs” ) in a computer program.
Syntax errors are caused by invalid syntax.
semantic errors (generally called logic errors ) are errors in program logic
Computers do not understand what a program is meant to do, they only
follow the instructions given .
Procedural vs. Object-Oriented Programming:
Programming languages fall into a number of programming paradigms .
Procedural
Object Oriented
Python supports both procedural and object oriented programming.
BP
PYTHON UNIT-1
7) The Process of Computational Problem Solving:
Involve the act of computer programming Before a program is written, a
design for the program must be developed.
Before a design can be developed, the problem to be solved must be well
understood.
Once written, the program must be thoroughly tested.
i) Problem Analysis
• Understanding the Problem
The fundamental computational issues for solving it can be determined.
The representation is straightforward
Eg. Calendar month problem
Determining the first day of a given month, and displaying the calendar
month in the proper format
The first day of the month can be obtained by direct calculation by use of
the algorithm.
BP
PYTHON UNIT-1
Knowing What Constitutes a Solution
program may be stated as finding
– A solution
– An approximate solution
– A best solution
– All solutions
A best solution here is one with the shortest number of steps.
ii) Program Design
Describing the Data Needed
For the Calendar Month problem, the data include the month and year
(entered by the user), the number of days in each month, and the names of
the days of the week.
A useful structuring of the data is given below
– [ month , year ]
– [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
– [‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’,
‘Friday’, ‘Saturday’]
– 0 – Sunday, 1 – Monday, . . ., 6 – Saturday
Describing the Needed Algorithms:
For the MCGW problem, there are standard search algorithms that can be
used.
Algorithms that work well in general but are not guaranteed to give the
correct result for each specific problem are called heuristic
algorithms .
iii )Program Implementation
Design decisions provide general details of the data representation and
the algorithmic approaches for solving a problem.
The implementation needs to be expressed in a syntactically correct and
appropriate way, using the instructions and features available in Python.
iv) Program Testing
As humans error is common.
BP
PYTHON UNIT-1
8) The Python Programming Language:
About Python
Guido van Rossum is the creator of the Python programming language
first released in the early 1990s.
Python is high level programming language supports for both procedural
and object oriented programming language.
Features of Python:
– Has a simple syntax.
– Programs are clear and easy to read.
– provides powerful programming features.
– It is well supported and freely available at [Link].
-Companies and organizations that use Python include YouTube, Google,
Yahoo, and NASA.
Ref :..\Article\features of [Link](“Akshansh Sharma ,
Firoj Khan ,May 2020”)
The IDLE Python Development Environment:
The development environment provided with Python.
IDLE is an integrated development environment ( IDE ).
An IDE is a bundled set of software tools for program development.
It includes:
– Editor – for creating and modifying programs.
– Translator – for executing programs.
Program 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 .
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.
BP
PYTHON UNIT-1
To utilize the capabilities of a given module in a specific program, an
import statement is used.
A Bit of Python:
A variable, how to perform some simple arithmetic calculations, and how
to do simple input and output.
Variables:
variable is “a name that is assigned to a value”
n = 5 variable n is assigned the value 5
Basic Arithmetic Operators:
The common arithmetic operators in Python are
+ (addition)
-(subtraction)
*(multiplication)
/ (division), and
** (exponentiation).
Basic Input and Output:
In Python, input is used to request and get information from the user.
Example:
name = 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,
What is your name?: Charles
The underline is used here to indicate the user’s input.
Print is used to display information on the screen.
>>> print('Welcome to My First Program!')
Output:
Welcome to My First Program!
BP
PYTHON UNIT-1
Learning How to Use IDLE:
First, to create a Python program file, select.
New File from the File menu in the shell.
A new, untitled program window will appear:
Type the program:
Save the program. Filesave
BP
PYTHON UNIT-1
Run the program. Run Run Module
Or press F5. Execution.
9) LITERALS:
A literal is a sequence of one or more characters that stands for itself.
CLASSIFICATION:
– Numeric Literals
– String Literals
– Control Characters
Numeric Literals:
A numeric literal is a literal containing only the digits 0–9, a sign
character (+ or -) and a possible decimal point. Commas are never used in
numeric literals.
BP
PYTHON UNIT-1
If a numeric literal contains a decimal point, then it denotes a floating-
point value .
Otherwise, it denotes an integer value.
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^-308 to 10^308 with 16 to 17 digits of precision.
Example:
Arithmetic Overflow:
Arithmetic overflow occurs when a calculated result is too large in
magnitude to be represented.
Example:
The multiplication of two values may result in arithmetic overflow , a
condition that occurs when a calculated result is too large in magnitude
(size) to be represented,
>>>1.5e200 * 2.0e210
>>>inf
This results in the special value inf (“infinity”) rather than the
arithmetically correct result 3.0e410, indicating that arithmetic overflow
has occurred.
Limits of Precision in Floating-Point Representation:
Since any floating-point representation contains only a finite number of
digits, what is stored for many floating point values is only an
approximation of the true value.
The loss of precision that can result in a calculated result.
Eg: 1/3 = 0.3333333…
Eg : 3* (1/3) = 0.9999999999
BP
PYTHON UNIT-1
Python displays a rounded result to keep the number of digits displayed
manageable.
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.
>>>12/5
2.4
>>>format(12/5,’2f’)
2.40
>>>format(13402.25, ' , .2f')
13,402.24
String Literals:
A string literal, or string, is a sequence of characters denoted by a pair of
matching single or double (and sometimes triple) quotes in Python.
Eg: 'Hello' 'Smith, John' "Baltimore, Maryland 21210"
string literals may be delimited.
>>> print('Welcome to Python!')
Welcome to Python!
A 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” .
Representation:
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.
Partial UTF-8 (ASCII) Code Table
BP
PYTHON UNIT-1
The ord function gives the UTF-8 (ASCII) encoding of a given character.
The chr function gives the character for a given encoding value.
Control Characters:
Control characters are nonprinting characters used to control the display
of output (among other things).
Control characters do not have a corresponding keyboard character.
Escape Sequence Character:
An escape sequence is a string of one or more characters used to
denote control characters.
– \n newline print(‘ Hello World \n Welcome to this python programming’)
10) VARIABLES AND IDENTIFIERS:
A variable is a name (identifier) that is associated with a value.
A variable can be assigned different values during a program’s
execution —hence, the name “variable.”
Variables are assigned values by use of the
assignment operator , = ,
Num = 10 Num= num+1
BP
PYTHON UNIT-1
The right side of an assignment is evaluated first, then the result is
assigned to the variable on the left .
A variable assigned to another variable.
Variables num and k are both associated with the same literal value 10 in
memory.
>>>id(num)
505494040
>>>id(k)
505494040
The id function produces a unique number identifying a specific value
(object) in memory.
Immutable Value :
An immutable value is a value that cannot be changed.
If no other variable references the memory location of the original value,
the memory location is deallocated.
Finally, in Python the same variable can be associated with values of
different type during program execution, as indicated below.
Var = 12 integer
Var = 12.45 float
var = 'Hello' string
VARIABLE ASSIGNMENT & KEYBOARD INPUT:
Use of input function.
To receive the value of the variable assigned by the user.
All input is returned by the input function as a string type.
Built-in functions int() and float() can be used to convert a string
to a numeric type.
Eg 1:
>>>name = input(‘What is your name?’)
>>>what is your name? Agalya
Eg 2 :
BP
PYTHON UNIT-1
>>>s1=input(‘Enter the Mark1’)
>>>s2 = input(‘Enter the Mark2’)
>>> total = int(s1)+int(s2)
Eg 3:
>>>r=input(‘Enter the radius of the circle’)
>>>area = 3.14 * float(r) * float(r)
Identifiers:
An identifier is a sequence of one or more characters used to name a
given program element.
In Python, an identifier may contain letters and digits, but cannot begin
with a digit.
The special underscore character can also be used.
Spaces are not allowed as part of an identifier.
This is a common error since some operating systems allow spaces within
file names.
In programming languages, however, spaces are used to delimit
(separate) distinct syntactic entities.
Thus, any identifier containing a space character would be considered
two separate identifiers.
Keyword :
A keyword is an identifier that has predefined meaning in a programming
language and therefore cannot be used as a “regular” identifier.
This will result in a syntax error.
Eg : >>> in=10
SyntaxError: invalid syntax
Keywords in Python:
BP
PYTHON UNIT-1
There are other predefined identifiers that can
be used as regular identifiers, but should not
be. This includes float, int, print, exit, and quit.
11) OPERATORS:
Definition:
An operator is a symbol that represents an operation that may be
performed on one or more operands.
A+B=C
A, B, C Operand
+, = Operator
Types:
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
1) Arithmetic Operators:
Python arithmetic operators are used to perform mathematical operations
on numerical values. These operations are Addition, Subtraction,
Multiplication, Division, Modulus, Expoents and Floor Division.
EX:
a = 21
b = 10
print ("a + b : ", a + b)
print ("a - b : ", a - b)
BP
PYTHON UNIT-1
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 : 31
a - b : 11
a * b : 210
a / b : 2.1
a%b: 1
a ** b : 16679880978201
a // b : 2
2) Comparision operator:
Comparison operators compare the values of the two operands and return
a true or false Boolean value in accordance.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= The condition is met if the first operand is smaller than or equal to the second operand.
>= The condition is met if the first operand is greater than or equal to the second operand.
> If the first operand is greater than the second operand, then the condition becomes true.
< If the first operand is less than the second operand, then the condition becomes true.
EX:
a = 32
b=6
print('Two numbers are equal or not:',a==b)
print('Two numbers are not equal or not:',a!=b)
print('a is less than or equal to b:',a<=b)
print('a is greater than or equal to b:',a>=b)
print('a is greater b:',a>b)
print('a is less than b:',a<b)
BP
PYTHON UNIT-1
Output:-
Two numbers are equal or not: False
Two numbers are not equal or not: True
a is less than or equal to b: False
a is greater than or equal to b: True
a is greater b: True
a is less than b: False
3) Assignment Operators
Using the assignment operators, the right expression's value is assigned to the left operand.
Program Code:
a = 32
b=6
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: False
a+=b: 38
a-=b: 26
a*=b: 192
a%=b: 2
a**=b: 1073741824
a//=b: 5
4) Bitwise Operators
The two operands values are processed bit by bit by the bitwise operators.
The examples of Bitwise operators are bitwise OR (|), bitwise AND (&), bitwise XOR (^),
negation (~), Left shift (<<), and Right shift (>>).
BP
PYTHON UNIT-1
Program Code
a=5
b=6
print('a&b:', a&b)
print('a|b:', a|b)
print('a^b:', a^b)
print('~a:', ~a)
print('a<<b:', a<<b)
print('a>>b:', a>>b)
Output:
a|b: 7
a^b: 3
~a: -6
a<>b: 0
5) Logical Operators : The logical operators are and, or, and not.
Program Code:
a=5
print(Is this statement true?:',a > 3 and a < 5)
print('Any one statement is true?:',a > 3 or a < 5)
print('Each statement is true then return False and vice-versa:',(not(a > 3 and a < 5)))
Output:
Is this statement true?: False
Any one statement is true?: True
Each statement is true then return False and vice-versa: True
6) Membership Operators:
The membership of a value inside a Python data structure can be verified using Python
membership operators.
BP
PYTHON UNIT-1
The result is true if the value is in the data structure; otherwise, it returns false.
i)in
ii)not in
Program Code:
x = ["Rose", "Lotus"]
print(' Is value Present?', "Rose" in x)
print(' Is value not Present?', "Riya" not in x)
Output:
Is value Present? True
Is value not Present? True
7) Identity Operators:
Operator Description
Is If the references on both sides point to the same object, it is determined to
be true.
is not If the references on both sides do not point at the same object, it is
determined to be true.
Program Code:
a = ["Rose", "Lotus"]
b = ["Rose", "Lotus"]
c=a
print(a is c)
print(a is not c)
print(a is b)
print(a is not b)
print(a == b)
print(a != b)
BP
PYTHON UNIT-1
Output:
True
False
False
True
True
False
12) Expressions And Data Types:
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.
4 + (3 * 5)
4 and 3*5 are two sub expressions.
3*5 having two sub expressions.
Expressions that evaluate to a numeric type are called arithmetic
expressions .
From the Python Shell, enter the following and observe the results.
>>> (2 + 3) * 4 = 5*4 = 20
>>> 2 + ((3 * 4)-8) = 2+(12-8)= 2+4=6
>>> 2 + (3 * 4) = 2+12= 14
>>> 2 + 3 * (4 – 1) = 2+3*3 = 2+9 = 11
BODMAS rule (Bracket of Division Multiplication Addition &
Subtraction).
Operator Precedence:
Operators appear between their operands, is referred to as infix notation
.(a+b)
There are other ways of representing expressions called prefix(+ab) and
postfix(ab+) notation, in which operators are placed before and after their
operands, respectively.
Operator precedence of Arithmetic operators:
BP
PYTHON UNIT-1
In the table, higher-priority operators are placed above lower-priority
ones
Example : 4+ 3 * 5
Multiplication is performed before addition
4+15 = 19
Operator Associativity:
Operator associativity is the order that operators are applied when having
the same level of precedence, specific to each operator.
Eg: (8-4)-2 4-22
For operators following the associative law
A + (B +C) = (A+B) + C
The order of evaluation doesn’t matter,
(2 + 3) + 4 ➝ 9
2 + (3 + 4) ➝ 9
Division and subtraction, however, do not follow the associative law,
(8-4)-2 = 4-2=2 & 8-(4-2) = 8-2 = 6
2**(3**2) = 2**9 = 512 & (2**3)**2 =8**2=64
All operators except for exponentiation, have left-to-right associativity—
exponentiation has right-to-left associativity.
Eg: 2**3**2 = 2**9 = 512
The exponentiation associativity is from right to left. Hence solve 3**2
first.
2**9 . Then..The answer is 512.
Eg : 6-3 + 2 = 6-5= 1
13) Data Type:
Definition:
A data type is a set of values, and a set of operators that may be applied to
those values.
A set of predefined data types in Python called the built-in types .
Eg: Integers, floats, and strings.
Mixed-Type Expressions:
A mixed-type expression is an expression with operands of different type.
The CPU can only perform operations on values with the same internal
representation scheme, and thus only on operands of the same type.
Operands of mixed-type expressions therefore must be converted to a
common type.
Coercion vs. Type Conversion:
Coercion is the implicit (automatic) conversion of operands to a common
type.
BP
PYTHON UNIT-1
Eg: 2+ 4.5
2.0 + 4.5 =6.5
safe (automatic conversion of int to float)
Type conversion is the explicit conversion of operands to a specific type.
Python provides built-in type conversion functions int() and float(),
Eg: float(2) + 4.5 = 6.5
2 + int(4.5) = 6
Numeric strings can also be converted to a numeric type.
Eg :
num_credits = int(input('How many credits do you have? '))
Temperature Conversion Program
Formula :
Fahrenheit to celcius
C = F – 32 * (5/9)
Celcius to Fahrenheit
F= C * (9/5) + 32
BP
PYTHON UNIT-1
Ref:” Introduction to computer science using python-
Charles diebarch”
14) Python input and output:
Input :
Any information or data sent to the computer from the user through the
keyboard is called input.
Syntax: input(prompt_message)
EX: name =input('What is your first name?')
OUTPUT: What is your first name? John
The python will automatically identify whether the user entered a string,
number, or list; if the input entered from the user is not correct,
then python will throw a syntax error.
Output:
The information produced by the computer to the user is called output.
Syntax: print()
It is used to print the output.
Python provides us with the two inbuilt functions.
i) input()
ii)output()
Python-2 supports the raw_input() function and input() function
Python-3 supports only for input() function .
EX: val = input("Enter a value: ")
print("You entered:",val)
BP
PYTHON UNIT-1
Output:
1. Enter a value: 45
2. You entered: 45
BP