Cs Study Material Python
Cs Study Material Python
Chapter 1 : Introduction-Fundamentals
1.1.What Is Computer Science?
Computer science is fundamentally about is computational problem solving —that is, solving
problems by the use of computation
The Essence of Computational Problem Solving
In order to solve a problem computationally, two things are needed:
A representation that captures all the relevant aspects of the problem.
An algorithm that solves the problem by use of the representation.
1
PROBLEM SOLVING USING PYTHON UNIT-I
BASE-2 REPRESENTATION :
128 64 32 16 8 4 2 1
2^7 2^6 2^5 2^4 2^3 2^2 2^1 2^0
0 1 1 0 0 0 1 1 = 99
1.4 Computer Software
Computer software is a set of program instructions, including related data and documentation,
that can be executed by computer.
Syntax, Semantics, and Program Translation :
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.
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.
Syntax errors are caused by invalid syntax. Semantic (logic) errors are caused by errors in
program logic.
Procedural vs. Object-Oriented Programming
Python supports both procedural and object-oriented programming.
Procedural programming and object-oriented programming are two major
programming paradigms in use today.
2
PROBLEM SOLVING USING PYTHON UNIT-I
Installing of python
Python is well supported and freely available at https://www.python.org/downloads/
Latest version : 3.8.5
3
PROBLEM SOLVING USING PYTHON UNIT-I
Python IDLE
An Integrated Development Environment (IDLE) is a bundled set of software tools for
program development.
An editor for creating and modifying programs
A translator for executing programs
A program debugger provides a means of taking control of the execution of a program
to aid in finding program errors
The Python Standard Library is a collection of modules, each providing specific functionality
beyond what is included in the core part of Python.
Python character set
Letters: Upper case and lower case letters
Digits: 0,1,2,3,4,5,6,7,8,9
Special Symbols: Underscore (_), (,), [,], {,}, +, -, *, &, ^, %, $, #, !, Single quote(‘),
Double quotes(“), Back slash(\), Colon(:), and Semi Colon (;)
White Spaces: (‘\t\n\x0b\x0c\r’), Space, Tab.
Token
A program in Python contains a sequence of instructions.
Python breaks each statement into a sequence of lexical components known as tokens.
Variables
A variable is “a name that is assigned to a value.”
The assignment operator, = , is used to assign values to variables.
An immutable value is a value that cannot be changed.
Eg: >>>num=10
>>> k=num
>>> print(k)
O/P : 10
In Python the same variable can be associated with values of different type during
program execution.
Eg : var = 12 integer
var = 12.45 float
var = 'Hello' string
4
PROBLEM SOLVING USING PYTHON UNIT-I
5
PROBLEM SOLVING USING PYTHON UNIT-I
>>> inf
Arithmetic underflow problem :
This problem occurs in division.
If denominator is larger than numerator, then it will result in zero.
Eg: 1/10000=0.00001
Loss of precision problem :
This problem occurs in division.
If numerator divided by denominator, then if the result is never ending.
Eg : 10/3 = 3.33333
6
PROBLEM SOLVING USING PYTHON UNIT-I
EXAMPLE :
>>>print('Hello\nJennifer Smith')
O/P:
Hello
Jennifer Smith
>>> print ('what\'s your name?')
O/P : what's your name?
>>> print ('what's your name?')
O/P : SyntaxError: invalid syntax
Implicit Line Joining
Matching parentheses, square brackets, and curly braces can be used to span a logical
program line on more than one physical line.
Explicit Line Joining
Program lines may be explicitly joined by use of the backslash (\).
Identifier
• An identifier is a sequence of one or more characters used to name a given program
element.
7
PROBLEM SOLVING USING PYTHON UNIT-I
The keyword module in python provides two helpful members for dealing with keywords.
8
PROBLEM SOLVING USING PYTHON UNIT-I
kwlist provides a list of all the python keywords for the version which
you are running.
iskeyword() provides a way to determine if a string is also a keyword.
Eg :
NUMBERS
Number data type stores Numerical Values.
This data type is immutable [i.e. values/items cannot be changed].
Pythn supports integers, floating point numbers and complex numbers.
9
PROBLEM SOLVING USING PYTHON UNIT-I
Sequence
A sequence is an ordered collection of items, indexed by positive integers.
It is a combination of mutable (value can be changed) and immutable (values cannot
be changed) datatypes.
There are three types of sequence data type available in Python, they are
1. Strings, 2. Lists, 3. Tuples
Strings
A String in Python consists of a series or sequence of characters.
Single quotes(' ') E.g., 'This a string in single quotes' ,
Double quotes(" ") E.g., "'This a string in double quotes'" ,
Triple quotes(""" """)E.g., """This is a paragraph. It is made up of multiple lines
and sentences."""
Individual character in a string is accessed using a subscript(index).
Strings are Immutable i.e the contents of the string cannot be changed after it is created.
Lists
List is an ordered sequence of items. Values in the list are called elements /items.
It can be written as a list of comma-separated items (values) between square brackets[].
Items in the lists can be of different datatypes.
Eg : lt = [ 10, -20, 15.5, ‘ABC’, “XYZ” ]
Tuples
In tuple the set of elements is enclosed in parentheses ( ).
A tuple is an immutable list.
Once a tuple has been created, you can't add elements to a tuple or remove elements
from the tuple.
Benefit of Tuple:
Tuples are faster than lists.
If the user wants to protect the data from accidental changes, tuple can be used.
Tuples can be used as keys in dictionaries, while lists can't.
Altering the tuple data type leads to error.
Eg : tpl = ( 10, -20, 15.5, ‘ABC’, “XYZ” )
Dictionaries
A dictionary maps keys to values.
10
PROBLEM SOLVING USING PYTHON UNIT-I
Lists are ordered sets of objects, whereas dictionaries are unordered sets.
Dictionary is created by using curly brackets. i,e.{ }
Dictionaries are accessed via keys and not via their position.
The values of a dictionary can be any Python data type. So dictionaries are unordered
key-value pairs(The association of a key and a value is called a key- value pair)
Eg : Creating a dictionary:
>>> food = {"ham":"yes", "egg" : "yes", "rate":450 }
Set :
Python also provides two set types, set and frozenset.
The set type is mutable, while frozenset is immutable.
They are unordered collections of immutable objects.
Boolean :
The boolean data type is either True or False.
In Python, boolean variables are defined by the True and False keywords.
The keywords True and False must have an Upper Case first letter.
OPERATORS IN PYTHON
An operator is a symbol that represents an operation that may be performed on one or
more operands.
Operators that take one operand are called unary operators.
Operators that take two operands are called binary operators.
20 - 5 ➝ 15 ( - as binary operator)
- 10 * 2 ➝ -20 ( - as unary operator)
Types of operators
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operator
Bitwise Operator
Identity Operator
Membership Operator
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication, etc.
11
PROBLEM SOLVING USING PYTHON UNIT-I
x**y (x to the
** Exponent - left operand raised to the power of right
power y)
Relational Operators
• Relational operators are used to compare values. It returns either True or False
according to the condition.
Logical operators
• Logical operators are the and, or, not operators.
12
PROBLEM SOLVING USING PYTHON UNIT-I
Eg:
x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
Assignment Operator
• Assignment operators are used to assign the values to variables.
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
BITWISE OPERATORS
• Bitwise operators are working with individual bits of data.
13
PROBLEM SOLVING USING PYTHON UNIT-I
Example :
Membership operators
Membership operators : in and not in for determining the presence of items in a sequence such
as strings, lists and tuples.
in and not in are the membership operators in Python.
They are used to test whether a value or variable is found in a sequence(string, list,
tuple, set and dictionary)
In dictionary, we can only test for the presence of key not the value.
Example :
What Is an Expression?
An expression is a combination of symbols or single symbol that evaluates to a value.
A subexpression is any expression that is part of a larger expression.
Expressions, most commonly, consist of a combination of operators and operands,
Eg : 4 + (3 * k)
Operator precedence
Precedence : Defines the priority of an operator.
Associativity :
When an expression contains operators with equal precedence then the associativity
property decides which operation is to be performed first.
Associativity implies the direction of execution and is of two types,left to right and right
to left.
15
PROBLEM SOLVING USING PYTHON
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.
Three fundamental forms of control in programming are sequential, selection, and 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.
Indentation in Python
• A header in Python is a specific keyword followed by a colon.
• The set of statements following a header in Python is called a suite(commonly called
a block).
• A header and its associated suite are together referred to as a clause.
Selection Control or Decision Making statement
A selection control statement is a control statement providing selective execution of
instructions.
• if statements
• if-else statements
• Nested if statements
• Multi-way if-elif-else statements
if statement:
• An if statement is a selection control statement based on the value of a given Boolean
expression.
• The if statement executes a statement if a condition is true.
1
PROBLEM SOLVING USING PYTHON
Example :
2
PROBLEM SOLVING USING PYTHON
if-else statements
• The if-else statement takes care of a true as well a false condition.
Example :
Nested if statements
• One if statement inside another if statement then it is called a nested if statement.
Syntax :
if Boolean-expression1:
if Boolean-expression2:
statement1
else:
statement2
else:
statement3
3
PROBLEM SOLVING USING PYTHON
Flow chart
Example :
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
Flow Chart:
4
PROBLEM SOLVING USING PYTHON
Example:
Syntax :
Expression1 if condition else Expression2
Example :
num1=8; num2=9
print(num1) if num1<num2 else print(num2)
Example:
To check whether the given year is leap year or not
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.
Iteration statements
• While Loop
• For Loop
5
PROBLEM SOLVING USING PYTHON
while Statement
A while statement is an iterative control statement that repeatedly executes a set of statements
based on a provided Boolean expression ( condition ).
Syntax :
while condition:
suite (or) statements
•
The reserved keyword while begins with the while statement.
•
The test condition is a Boolean expression.
•
The colon (:) must follow the test condition, i.e. the while statement be terminated
with a colon (:).
• The statement(s) within the while loop will be executed till the condition is true, i.e.
the condition is evaluated and if the condition is true then the body of the loop is
executed.
• When the condition is false, the execution will be completed out of the loop or in
other words, the control goes out of the loop.
FLOW CHART
Example :
x=1
while x < 3:
print(x)
x=x+1
OUTPUT :
6
PROBLEM SOLVING USING PYTHON
Execution
• An infinite loop is an iterative control structure that never terminates (or eventually
terminates with a system error).
Example :
while True:
num = int(input("Enter an integer: "))
print("The double of",num,"is",2 * num)
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.
• A indefinite loop is a program loop in which the number of times the loop will iterate
is not known before the loop is executed.
Input Error Checking
Example :
a=5;b=3
ch=int(input("Enter the choice"))
while ch!=1 and ch!=2:
ch=int(input("Enter either 1 or 2"))
if ch==1:
print(a+b)
else:
print(a-b)
7
PROBLEM SOLVING USING PYTHON
range() function
range(5) [0,1,2,3,4]
range(1,5) [1,2,3,4]
range(1,10,2) [1,3,5,7,9]
range(5,0,-1) [5, 4, 3, 2, 1]
range(0,1) [0]
range(1,1) Empty
range(0) Empty
for loop
• A for statement is an iterative control statement that iterates once for each element in
a specified sequence of elements.
• Used to construct definite loops.
8
PROBLEM SOLVING USING PYTHON
Syntax :
for var in sequence:
statement(s)
………………………………
……………………………
………………………………
• for and in are essential keywords to iterate the sequence of values.
• var takes on each consecutive value in the sequence
• statements in the body of the loop are executed once for each value
Flow chart
•The for loop repeats a group of statements for a specified number of times.
for var in range(m,n):
print var
• function range(m, n) returns the sequence of integers starting from m, m+1, m+2,
m+3…………… n-1.
Example :
for i in range(1,6):
print(i)
Lists
A list is a linear data structure, thus its elements have a linear ordering.
Example :
• lst = [1,2,3,4,5]
• lst = [‘a,’b’,’c’,’d’]
• lst= [1,’ABC’,98.5,’HELLO’]
➢ Operations commonly performed on lists include retrieve, update, insert, remove, and
append.
➢ A list traversal is a means of accessing, one-by-one, the elements of a list.
9
PROBLEM SOLVING USING PYTHON
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
zerobased indexing.
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
lst = [10,20,30,40,50]
lst[0]=10
lst[1]=20
lst[2]=30
lst[3]=40
lst[4]=50
lst[-1]=50
lst[-2]=40
lst[-3]=30
lst[-4]=20
lst[-5]=10
Syntax : lst.append(element)
Eg : lst.append(60)
Eg : lst[2]=25
Eg : del lst[3]
10
PROBLEM SOLVING USING PYTHON
lst[1:3]=[20,30]
lst[1:4]=[20,30,40]
lst[:4]=[10,20,30,40]
lst[2:]=[30,40,50]
Built-in-function
listname.count(element)
listname.index(element)
listname.index(element,start)
listname.append(element)
listname.extend(list)
listname.pop(index)
listname.insert(index,element)
listname.remove(element)
listname.reverse()
Listname.sort()
>>> lst1=[1,2,3,4]
>>> lst2=lst1
>>> print(lst2)
[1, 2, 3, 4]
List Comprehension
List comprehensions in Python provide a concise means of generating a more varied set of
sequences than those that can be generated by the range function.
11
PROBLEM SOLVING USING PYTHON
Syntax :
Eg:
print(lst)
Example:
lst1=[1,2,3,4]
lst2=[2,5,6,7]
print(pair)
Looping in List
lst = [10,20,30,40,50]
for i in lst:
print(i)
O/P :
10
20
30
40
50
12
PROBLEM SOLVING USING PYTHON
Nested Lists
Tuples
tup=()
tup1=(“apple”,”banana”,1997,2020)
tup2=(1,2,3,4,5)
Basic Operations
a=(10,20,20,40,50,60,10,80) b=(1,2,3,4,5,6)
Length : len(a) : 8
Concatentation : a+b : (10, 20, 20, 40, 50, 60, 10, 80, 1, 2, 3, 4, 5, 6)
13
PROBLEM SOLVING USING PYTHON
Repetition : a*2 : (10, 20, 20, 40, 50, 60, 10, 80, 10, 20, 20, 40, 50, 60, 10, 80)
Membership : 20 in a : True
Index : a.index(40) : 3
Count : a.count(20) : 2
Conversion to Tuple
lst=[]
for i in range(5):
#ele=int(input())
lst.append(i)
print(lst)
tup=tuple(lst)
print(tup)
Sample program for tuple : Counting No.of ODD & EVEN numbers in tuple
input_tuple=()
final_tuple=()
oddc=0
evenc=0
for i in range(1,11):
input_tuple=(i)
final_tuple=final_tuple+(input_tuple,)
print(final_tuple)
for x in final_tuple:
temp=int(x)
if temp%2==0:
evenc=evenc+1
14
PROBLEM SOLVING USING PYTHON
else:
oddc=oddc+1
15
FUN
NCTIONS – UNIT III NOTES
Program Routines:
A program routine is a named group of instructions that accomplishes some task. A routine
may be invoked (called) as many times as needed in a given program. A function is Python’s
version of a program routine.
What is a Function routine?
• A routine is a named group of instructions performing some task.
• A routine can be invoked ( called ) as many times as needed in a given program
• A function is Python’s version of a program routine.
Advantages of Function:
• Helpful debugging your code.
• Reusability of code.
• Easier to understand.
• Easier to maintain.
Function definition:
• Every function should start with ‘def’ keyword.
• Every function should have name( not equal to any keyword)
• Parameters / Arguments (optional) included in b/w parenthesis.(formal)
• Every function namee with/without arguments should end with(:)
• return empty / value
• Multi value return can be done ( tuples )
• Every function must be defined before it is called
called.
Syntax:
def function_name(arg1, arg2, …. arg n) :
program statement 1
program statement 2
--------
--------
return
Function call:
• Function name Equal to the function definition
• Arguments / Parameters(actual)
Actual arguments & Formal parameters
parameters:
• Actual arguments, or simply “arguments,” are the values passed to functions to be
operated on.
• Formal parameters, or simply “parameters,” are the “placeholder” names for the
arguments passed.
Value-returning functions:
• A value-returning
returning function in Python is a program routine called for its return value,
and is therefore similar to a mathematical function.
Non-value-returning
returning functions
functions:
• A non-value-returning
returning function is a function called for its side effects, and not for a
returned function value.
The locall and global scope of a variable
variable:
• Variables and parameters that are initialised within a function including parameters,
are said to exist in that function’s local scope. Variables that exist in local scope are
called local variables.
• Variables that are assigned outside functions are said to exist in global scope.
Therefore, variables that exist in global scope are called global variables.
1
FUN
NCTIONS – UNIT III NOTES
LOCAL VARIABLE :
• A local variable is a variable that is only accessible from within the function it resides.
Such variables are said to have local scope.
GLOBAL VARIABLE :
• A global variable is a variable defined outside of any function definition. Such
variables are said to have global scope. The use of global variables is considered bad
programming practice.
tice.
2
FUNCTIONS – UNIT III NOTES
• floor() :- Returns the greatest integral value smaller than the number. If number is
already integer, same number is returned.
• fabs() :- Returns the absolute value of the number.
• gcd() :- Used to compute the greatest common divisor of 2 numbers mentioned in its
arguments
Recursive function:
• A function is said to be recursive if a statement within the body of the function
calls itself.
• Eg:
def factorial(n):
if n==0:
return 1
return n*factorial(n-1)
print(factorial(5))
Advantages:
• Recursive functions make the code look clean and elegant.
• A complex task can be broken down into simpler sub-problems using recursion.
• Sequence generation is easier with recursion than using some nested iteration.
Dis-Advantages:
• The logic behind recursion is hard to follow through.
• Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
• Recursive functions are hard to debug.
Types of Arguments:
• Positional Arguments
• Keyword Arguments
• Default Arguments
• Variable length Arguments
Positional Arguments:
• Number of arguments should be same in both function call and function definition.
• A positional argument is an argument that is assigned to a particular parameter based
on its position in the argument list.
• Order or Position should be followed.
Eg:
def display(a,b): #function definition
print(a,b)
display(10,20) #function call
Keyword Arguments:
• A keyword argument is an argument that is specified by parameter name.
• Order or Position should not be followed.
• Initialisation will be done based on the keyword. (name of identifier)
Eg:
def display(a,b):
print(a,b)
display(b=10,a=20)
Default Arguments:
• An argument that can be optionally provided in a given function call. When not
provided, the corresponding parameter provides a default value.
• Number of arguments need not be same in both function call and function definition.
• Some of arguments will be consider as default arguments.
3
FUNCTIONS – UNIT III NOTES
Eg:
def display(a,b,c=30):
print(a,b,c)
display(10,20)
Variable Length Arguments:
• Arbitrary number of arguments.
• By placing * as prefix to the argument of function definition.
Eg:
def display(*courses):
for i in courses:
print(i)
display("BCA","MCA","CS","IT")
4
OOP’S CONCEPTS