0% found this document useful (0 votes)
3 views

MC4103 - PYTHON PROGRAMMING NOTES FOR ALL UNITS

The document provides an overview of Python programming basics, including key concepts such as variables, data types, control structures, and functions. It explains the use of keywords, mutable and immutable types, operator precedence, and various loop constructs, along with examples. Additionally, it covers parameter passing, recursion, and the significance of Boolean values in Python.

Uploaded by

abhisatheesan119
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

MC4103 - PYTHON PROGRAMMING NOTES FOR ALL UNITS

The document provides an overview of Python programming basics, including key concepts such as variables, data types, control structures, and functions. It explains the use of keywords, mutable and immutable types, operator precedence, and various loop constructs, along with examples. Additionally, it covers parameter passing, recursion, and the significance of Boolean values in Python.

Uploaded by

abhisatheesan119
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

UNIT 1 BASICS OF PYTHON

Introduction to Python Programming – Python Interpreter and Interactive Mode–


Variables and Identifiers – Arithmetic Operators – Values and Types –
Statements. Operators – Boolean Values
– Operator Precedence – Expression – Conditionals: If-Else Constructs –
Loop Structures/Iterative Statements – While Loop – For Loop – Break
Statement-Continue statement – Function Call and Returning Values – Parameter
Passing – Local and Global Scope – Recursive Functions
PART A (2MARKS)
1. What do you mean by python programming?
Python is an interpreted, object-oriented, high-level programming language with
dynamic semantics developed by Guido van Rossum. It was originally released in 1991.
it is known for its simplicity, flexibility, and ease of use. Python has gained popularity
over the years due to its wide range of features and capabilities.
2. What are keywords? Give example?
Python Keywords are some predefined and reserved words in Python that have
special meanings. Keywords are used to define the syntax of the coding. The keyword
cannot be used as an identifier, function, or variable name. All the keywords in Python
are written in lowercase except True and False. There are 35 keywords in Python
Eg:
'False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'de f',
'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is
3. What are mutable and immutable types in python?
MUTABLE
Anything is said to be mutable when anything can be modified or changed. The term
"mutable" in Python refers to an object's capacity to modify its values. These are
frequently the things that hold a data collection.
Eg: lists, dictionaries, and sets
IMMUTABLE
Immutable refers to a state in which no change can occur over time. A Python object is
referred to as immutable if we cannot change its value over time. The value of these
Python objects is fixed once they are made.
Eg: Strings and tuples

4. List any four built in data types in python?


 Numeric data types: int, float, complex
 String data types: str
 Sequence types: list, tuple, range
 Binary types: bytes, bytearray, memoryview
 Mapping data type: dict
 Boolean type: bool
 Set data types: set, frozenset

5. Outline the logic to swap the content of two identifiers without using the third
variable.
x=5
y=7
print ("Before swapping: ")
print("Value of x : ", x, " and y : ", y
x, y = y, x
print ("After swapping: ")
print("Value of x : ", x, " and y : ", y)
6. What are the rules for naming the variable?
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-
z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three different
variables)
 A variable name cannot be any of the Python keywords.

7. What is python break, continue and pass statement?


BREAK STATEMENT
The break statement in Python is used to terminate the loop or statement in which it is
present. After that, the control will pass to the statements that are present after the
break statement, if available. If the break statement is present in the nested loop, then
it terminates only those loops which contain the break statement.
CONTINUE STATEMENT
Continue is also a loop control statement just like the break statement. continue
statement is opposite to that of the break statement, instead of terminating the loop, it
forces to execute the next iteration of the loop. As the name suggests the continue
statement forces the loop to continue or execute the next iteration. When the continue
statement is executed in the loop, the code inside the loop following the continue
statement will be skipped and the next iteration of the loop will begin.
PASS STATEMENT
As the name suggests pass statement simply does nothing. The pass statement in
Python is used when a statement is required syntactically but you do not want any
command or code to execute. It is like a null operation, as nothing will happen if it is
executed. Pass statements can also be used for writing empty loops. Pass is also used
for empty control statements, functions, and classes.
8. Write the syntax for while loop and for loop?
While loop
The while code is used to run a block code until a certain condition is met
Syntax
While condition:
{body of the loop}
For loop
In Python, a for loop is used to iterate over sequences such as lists, tuples, string, etc.
Syntax
For val in sequence:
Statement(s)
9. What is identifier? mention the rules for identifier with example
Identifier is a user-defined name given to a variable, function, class, module, etc. The
identifier is a combination of character digits and an underscore. They are case-sensitive
i.e., 'num' and 'Num' and 'NUM' are three different identifiers in python.
10.What are local variable and global variable?
LOCAL VARIABLE
Local variables in python are those variables that are declared inside the function.
Alternatively, they are said to defined within a local scope. A user can only access a
local variable inside the function but never outside it.
GLOBAL VARIABLE
Variables that are created outside of a function (as in all of the examples above) are
known as global variables.
Global variables can be used by everyone, both inside of functions and outside.

11.What is recursion in python programming?


 Recursion is a common mathematical and programming concept. It means that a
function calls itself. This has the benefit of meaning that you can loop through
data to reach a result.
 Python also accepts function recursion, which means a defined function can call
itself.
12.What is Boolean value in python?
 Booleans represent one of two values: True or False. In programming you often
need to know if an expression is True or False.
 You can evaluate any expression in Python, and get one of two
answers, True or False.
 When you compare two values, the expression is evaluated and Python returns
the Boolean answer
13.What is expression in python?
An expression is a combination of values, variables, operators, and calls to functions.
Expressions need to be evaluated.
A combination of operands and operators is called an expression. The expression in
Python produces some value or result after being interpreted by the Python interpreter.
An expression in Python is a combination of operators and operands.
14.Define floor division with example?
In Python, we can perform floor division (also sometimes known as integer
division) using the // operator. This operator will divide the first argument by the second
and round the result down to the nearest whole number, making it equivalent to the
math. floor() function.
15.Define operator precedence?
An expression in python consists of variables, operators, values, etc. When the Python
interpreter encounters any expression containing several operations, all operators get
evaluated according to an ordered hierarchy, called operator precedence.
Operator precedence in python follows the PEMDAS rule for arithmetic expressions.
The precedence of operators is listed below in a high to low manner.
Firstly, parantheses will be evaluated, then exponentiation and so on.
P – Parentheses
E – Exponentiation
M – Multiplication
D – Division
A – Addition
S – Subtraction
16.What is type () in python?
python type() is a built-in function that is used to return the type of data stored in the
objects or variables in the program. For example, if a variable contains a value of 45.5 then
the type of that variable is float. Another example can be, if variable ‘subj’ stores the value
‘Python’, then the type of ‘subj’ is a string. It is also used for creating dynamic classes
along with their attribute values using the dictionary data type.

17.Draw the flow chart for if- else statement?

18.What are the three types of parameter passing?


There are several methods of parameter passing in programming languages, such
as "pass by value", "pass by reference", and "pass by name

19.Which character is used for commenting in python?


 Comments in Python are the lines in the code that are ignored by the interpreter
during the execution of the program. Comments enhance the readability of the
code and help the programmers to understand the code very carefully.
 In Python, we use the hash symbol # to write a single-line comment.

20.Define unary operator in python with example?


A unary operation is an operation with only one operand. As unary operations
have only one operand, they are evaluated before other operations containing them.
Common unary operators include Positive ( + ) and Negative ( - ).

PART B AND C
1. Explain the looping statement in python with example?
Python For loop
For loops are used for sequential traversal. For example: traversing a list or string or
array etc. In Python, there is “for in” loop which is similar to for each loop in other
languages. Let us learn how to use for in loop for sequential traversals.
Syntax:
for iterator_var in sequence:
statements(s)
Eg:
n=4
for i in range(0, n):
print(i)
WHILE LOOP
a while loop is used to execute a block of statements repeatedly until a given
condition is satisfied. And when the condition becomes false, the line immediately
after the loop in the program is executed.
Syntax:
while expression:
statement(s)
All the statements indented by the same number of character spaces after a programming
construct are considered to be part of a single block of code. Python uses indentation as
its method of grouping statements.
Eg:
# Python program to illustrate while loop
count = 0
while (count < 3):
count = count + 1
print("Hello")

BREAK STATEMENT
Break statement in Python is used to bring the control out of the loop when some
external condition is triggered. break statement is put inside the loop body (generally after
if condition). It terminates the current loop, i.e., the loop in which it appears, and resumes
execution at the next statement immediately after the end of that loop. If the break
statement is inside a nested loop, the break will terminate the innermost loop.

Python Continue Statement


Python Continue statement is a loop control statement that forces to execute the next
iteration of the loop while skipping the rest of the code inside the loop for the current
iteration only, i.e. when the continue statement is executed in the loop, the code inside the
loop following the continue statement will be skipped for the current iteration and the next
iteration of the loop will begin.

Syntax
while True:
...
if x == 10:
continue
print(x)

Eg:
for var in "sree":
if var == "e":
continue
print(var)
2. Summarize the precedence of mathematical operator in python?
An expression in python consists of variables, operators, values, etc. When the Python
interpreter encounters any expression containing several operations, all operators get
evaluated according to an ordered hierarchy, called operator precedence.
Precedence Operators Description Associativity
1 () Parentheses Left to right
2 x[index], x[index:in Subscription, Left to right
dex] slicing
3 await x Await expression N/A
4 ** Exponentiation Right to left
5 +x, -x, ~x Positive, Right to left
negative, bitwise
NOT
6 *, @, /, //, % Multiplication, Left to right
matrix, division,
floor division,
remainder
7 +, – Addition and Left to right
subtraction
8 <<, >> Shifts Left to right
9 & Bitwise AND Left to right
10 ^ Bitwise XOR Left to right
11 | Bitwise OR Left to right
12 in, not in, is, is Comparisons, Left to Right
not, <, <=, >, >=, !=, membership
== tests, identity
tests
13 not x Boolean NOT Right to left
14 and Boolean AND Left to right
15 or Boolean OR Left to right
16 if-else Conditional Right to left
expression
17 lambda Lambda N/A
expression
18 := Assignment Right to left
expression
(walrus operator)

Eg:
10 + 20 * 30 is calculated as 10 + (20 * 30)
and not as (10 + 20) * 30

3. Explain the python data types with example?


Data types are the classification or categorization of data items. It represents the kind of
value that tells what operations can be performed on a particular data. Since everything
is an object in Python programming, data types are actually classes and variables are
instances (object) of these classes. The following are the standard or built-in data types
in Python:
Numeric
Sequence Type
Boolean
Set
Dictionary

To define the values of various data types and check their data types we use the type()
function.
1. NUMERIC
The numeric data type in Python represents the data that has a numeric value. A numeric value
can be an integer, a floating number, or even a complex number. These values are defined
as Python int, Python float, and Python complex classes in Python.
2.Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fractions or decimals). In Python, there is no limit to how long an integer
value can be.
3.Float – This value is represented by the float class. It is a real
number with a floating-point representation. It is specified by a decimal point. Optionally,
the character e or E followed by a
positive or negative integer may be appended to specify scientific notation.
4. Complex Numbers – Complex number is represented by a complex class. It is specified
as (real part) + (imaginary part)j. For example – 2+3j
5. SEQUENCE
The sequence Data Type in Python is the ordered collection of similar or different data types.
Sequences allow storing of multiple values in an organized and efficient fashion. There are
several sequence types in Python
6. String Data Type
Strings in Python are arrays of bytes representing Unicode characters. A string is a collection
of one or more characters put in a single quote, double-quote, or triple-quote. In python there
is no character data type, a character is a string of length one. It is represented by str class.
Creating String
Strings in Python can be created using single quotes or double quotes or even triple quotes.
Accessing elements of String
In Python, individual characters of a String can be accessed by using the method of
Indexing. Negative Indexing allows negative address references to access characters from the
back of the String, e.g. -1 refers to the last character, -2 refers to the second last character, and
so on.
7. List Data Type
Lists are just like arrays, declared in other languages which is an ordered collection of data. It
is very flexible as the items in a list do not need to be of the same type.
Creating List
Lists in Python can be created by just placing the sequence inside the square brackets[].
Access List Items
In order to access the list items refer to the index number. Use the index operator [ ] to access
an item in a list. In Python, negative sequence indexes represent positions from the end of the
array. Instead of having to compute the offset as in List[len(List)-3], it is enough to just write
List[-3]. Negative indexing means beginning from the end, -1 refers to the last item, -2 refers
to the second-last item, etc.
8. Tuple Data Type
Just like a list, a tuple is also an ordered collection of Python objects. The only difference
between a tuple and a list is that tuples are immutable i.e. It is represented by a tuple
class.

Creating a Tuple
In Python, tuples are created by placing a sequence of values separated by a ‘comma’ with or
without the use of parentheses for grouping the data sequence. Tuples can contain any number
of elements and of any datatype (like strings, integers, lists, etc.).
Access Tuple Items
In order to access the tuple items refer to the index number. Use the index operator [ ] to
access an item in a tuple. The index must be an integer. Nested tuples are accessed using
nested indexing.
Data type with one of the two built-in values, True or False. Boolean objects that are equal to
True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can
be evaluated in a Boolean context as well and determined to be true or false. It is denoted by
the class bool.
9. Set
In Python, a Set is an unordered collection of data types that is iterable, mutable and has no
duplicate elements. The order of elements in a set is undefined though it may consist of
various elements.
Create a Set in Python
Sets can be created by using the built-in set() function with an iterable object or a sequence by
placing the sequence inside curly braces, separated by a ‘comma’. The type of elements in a
set need not be the same, various mixed-up data type values can also be passed to the set.
Access Set Items
Set items cannot be accessed by referring to an index, since sets are unordered the items has
no index. But you can loop through the set items using a for loop, or ask if a specified value is
present in a set, by using the in the keyword.
10.Dictionary
A dictionary in Python is an unordered collection of data values, used to store data values like
a map, unlike other Data Types that hold only a single value as an element, a Dictionary holds
a key: value pair. Key-value is provided in the dictionary to make it more optimized. Each
key-value pair in a Dictionary is separated by a colon : , whereas each key is separated by a
‘comma’.
Create a Dictionary
In Python, a Dictionary can be created by placing a sequence of elements within curly {}
braces, separated by ‘comma’. Values in a dictionary can be of any datatype and can be
duplicated, whereas keys can’t be repeated and must be immutable. The dictionary can also be
created by the built-in function dict(). An empty dictionary can be created by just placing it in
curly braces{}. Note – Dictionary keys are case sensitive, the same name but different cases
of Key will be treated distinctly.
Accessing Key-value in Dictionary
In order to access the items of a dictionary refer to its key name. Key can be used inside
square brackets. There is also a method called get() that will also help in accessing the element
from a dictionary.

4. Illustrate the arithmetic operators in python with suitable example?


Python Arithmetic operators are used to perform basic mathematical operations like addition,
subtraction, multiplication, and division.
In Python 3.x the result of division is a floating-point while in Python 2.x division of 2
integers was an integer. To obtain an integer result in Python 3.x floored (// integer) is used.

Operator Description Syntax

+ Addition: adds two operands x+y

– Subtraction: subtracts two operands x–y

* Multiplication: multiplies two operands x*y

/ Division (float): divides the first operand by the second x/y

// Division (floor): divides the first operand by the second x // y

Modulus: returns the remainder when the first operand is


% x%y
divided by the second

** Power: Returns first raised to power second x ** y


Example of Arithmetic Operators in Python
Division Operators
Division Operators allow you to divide two numbers and return a quotient, i.e., the first
number or number at the left is divided by the second number or number at the right and
returns the quotient.
There are two types of division operators:
Float division
Floor division
Float division
The quotient returned by this operator is always a float number, no matter if two numbers are
integers.
Integer division( Floor division)
The quotient returned by this operator is dependent on the argument being passed. If any of
the numbers is float, it returns output in float. It is also known as Floor division because, if
any number is negative, then the output will be floored.
EXAMPLE
a = 21
b = 10
c=0

c=a+b
print "Line 1 - Value of c is ", c

c=a-b
print "Line 2 - Value of c is ", c

c=a*b
print "Line 3 - Value of c is ", c

c=a/b
print "Line 4 - Value of c is ", c

c=a%b
print "Line 5 - Value of c is ", c

a=2
b=3
c = a**b
print "Line 6 - Value of c is ", c

a = 10
b=5
c = a//b
print "Line 7 - Value of c is ", c

5. Write the following program


(i) To find whether a given number is Armstrong number or not?
num = int(input("Enter a number: "))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

OUTPUT

Enter a number: 663


663 is not an Armstrong
number

(i) To calculate the distance between two points

x1 = 2
y1 = 3
# point b
x2 = 5
y2 = 7
# distance b/w a and b
distance = ((x1 - x2)**2 + (y1 - y2)**2)**0.5
# display the result
print("Distance between points ({}, {}) and ({}, {}) is
{}".format(x1,y1,x2,y2,distance))

OUTPUT

Distance between points (2, 3) and (5,


7) is 5.0
6. Explain the various types of statements in python with suitable example
STATEMENTS
Any instruction written in the source code and executed by the Python interpreter is called a
statement. The Python language has many different types of statements like assignment
statements, conditional statements, looping statements, etc., that help a programmer get the
desired output. For example, p = 9; is an assignment statement.

PYTHON STATEMENT
A conditional statement is a logical expression where operators compare, evaluate, or check if
the input meets the conditions and returns ‘True’. If yes, the interpreter executes a specific set
of instructions. On the other hand, looping statements repeatedly execute a set of instructions
as long as the defined conditions are met or satisfied.
Types of statements in Python
The different types of Python statements are listed below:
Multi-Line Statements
Python Conditional and Loop Statements
Python If-else
Python for loop
Python while loop
Python try-except
Python with statement
Python Expression statements
Python pass statement
Python del statement
Python return statement
Python import statement
Python continue and break statement
Multiline Statements
Usually, we use the new line character (/n) to end a Python statement. However, if you want
to expand your code over multiple lines, like when you want to do long calculations and can’t
fit your statements into one line, you can use the continuation character (/).

Eg:
s = 10 + 15+ 30 + \
49 + 5 + 57 + \
3 - 54 - 2

Another way to create multiline statements is to use parentheses (), braces {}, square brackets
[], or even a semi-colon (;). While the continuation character marks an obvious line
continuation, the other multiline methods imply continuation indirectly.

Python if statement
The if statement is the most simple decision-making statement. It is used to decide whether a
certain statement or block of statements will be executed or not.
Syntax:
if condition:
# Statements to execute if
# condition is true
Here, the condition after evaluation will be either true or false. if the statement accepts
boolean values – if the value is true then it will execute the block of statements below it
otherwise not.
As we know, python uses indentation to identify a block. So the block under an if statement
will be identified as shown in the below example:
if condition:
statement1
statement2

# Here if the condition is true, if block


# will consider only statement1 to be inside
# its block.

Python If-Else Statement


The if statement alone tells us that if a condition is true it will execute a block of statements
and if the condition is false it won’t. But if we want to do something else if the condition is
false, we can use the else statement with if statement to execute a block of code when the if
condition is false.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

Nested-If Statement in Python


A nested if is an if statement that is the target of another if statement. Nested if statements
mean an if statement inside another if statement. Yes, Python allows us to nest if statements
within if statements. i.e., we can place an if statement inside another if statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Python if-elif-else
Here, a user can decide among multiple options. The if statements are executed from the top
down. As soon as one of the conditions controlling the if is true, the statement associated with
that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then
the final else statement will be executed.
Syntax:
if (condition):
statement
elif (condition):
statement
else:
statement

Python For loop


For loops are used for sequential traversal. For example: traversing a list or string or array etc.
In Python, there is “for in” loop which is similar to for each loop in other languages. Let us
learn how to use for in loop for sequential traversals.
Syntax:
for iterator_var in sequence:
statements(s)
Eg:
n=4
for i in range(0, n):
print(i)
WHILE LOOP
a while loop is used to execute a block of statements repeatedly until a given condition is
satisfied. And when the condition becomes false, the line immediately after the loop in the
program is executed.
Syntax:
while expression:
statement(s)
All the statements indented by the same number of character spaces after a programming
construct are considered to be part of a single block of code. Python uses indentation as its
method of grouping statements.
Eg:
# Python program to illustrate while loop
count = 0
while (count < 3):
count = count + 1
print("Hello")

BREAK STATEMENT
break statement in Python is used to bring the control out of the loop when some external
condition is triggered. break statement is put inside the loop body (generally after if
condition). It terminates the current loop, i.e., the loop in which it appears, and resumes
execution at the next statement immediately after the end of that loop. If the break statement is
inside a nested loop, the break will terminate the innermost loop.

Python Continue Statement


Python Continue statement is a loop control statement that forces to execute the next
iteration of the loop while skipping the rest of the code inside the loop for the current iteration
only, i.e. when the continue statement is executed in the loop, the code inside the loop
following the continue statement will be skipped for the current iteration and the next iteration
of the loop will begin.

SYNTAX
while True:
...
if x == 10:
continue
print(x)

Eg:
for var in "sree":
if var == "e":
continue
print(var)
7. Explain the various types of operators in python with suitable example?
PYTHON OPERATORS
In Python programming, Operators in general are used to perform operations on values and
variables. These are standard symbols used for the purpose of logical and arithmetic
operations.
OPERATORS: These are the special symbols. Eg- + , * , /, etc.
OPERAND: It is the value on which the operator is applied.
Types of Operators in Python
Arithmetic Operators
Comparison Operators
Logical Operators
Bitwise Operators
Assignment Operators
Identity Operators and Membership Operators

1. Arithmetic Operators in Python


Python Arithmetic operators are used to perform basic mathematical operations like addition,
subtraction, multiplication, and division.
In Python 3.x the result of division is a floating-point while in Python 2.x division of 2
integers was an integer. To obtain an integer result in Python 3.x floored (// integer) is used.
Operator Description Syntax
Operator Description Syntax

+ Addition: adds two operands x+y

– Subtraction: subtracts two operands x–y

* Multiplication: multiplies two operands x*y

/ Division (float): divides the first operand by the second x/y

// Division (floor): divides the first operand by the second x // y

Modulus: returns the remainder when the first operand is


% x%y
divided by the second

** Power: Returns first raised to power second x ** y

Example of Arithmetic Operators in Python


Division Operators
Division Operators allow you to divide two numbers and return a quotient, i.e., the first
number or number at the left is divided by the second number or number at the right and
returns the quotient.
There are two types of division operators:
Float division
Floor division
Float division
The quotient returned by this operator is always a float number, no matter if two numbers are
integers.
Integer division( Floor division)
The quotient returned by this operator is dependent on the argument being passed. If any of
the numbers is float, it returns output in float. It is also known as Floor division because, if
any number is negative, then the output will be floored.
2. Comparison Operators in Python
In Python Comparison of Relational operators compares the values. It either
returns True or False according to the condition.

Operator Description Syntax

> Greater than: True if the left operand is greater than the right x>y
Operator Description Syntax

< Less than: True if the left operand is less than the right x<y

x ==
== Equal to: True if both operands are equal
y

!= Not equal to – True if operands are not equal x != y

Greater than or equal to True if the left operand is greater than or equal to x >=
>=
the right y

Less than or equal to True if the left operand is less than or equal to the x <=
<=
right y
= is an assignment operator and == comparison operator.

3. Logical Operators in Python


Python Logical operators perform Logical AND, Logical OR, and Logical NOT operations.
It is used to combine conditional statements.

Operator Description Syntax

And Logical AND: True if both the operands are true x and y

Or Logical OR: True if either of the operands is true x or y

Not Logical NOT: True if the operand is false not x

3. Bitwise Operators in Python


Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to
operate on binary numbers.

Operator Description Syntax

& Bitwise AND x&y

| Bitwise OR x|y
Operator Description Syntax

~ Bitwise NOT ~x

^ Bitwise XOR x^y

>> Bitwise right shift x>>

<< Bitwise left shift x<<

4. Assignment Operators in Python


Python Assignment operators are used to assign values to the variables.
Operator Description Syntax

Assign the value of the right side of the expression to the


= x=y+z
left side operand

Add AND: Add right-side operand with left-side operand


+= a+=b a=a+b
and then assign to left operand

Subtract AND: Subtract right operand from left operand


-= a-=b a=a-b
and then assign to left operand

Multiply AND: Multiply right operand with left operand


*= a*=b a=a*b
and then assign to left operand

Divide AND: Divide left operand with right operand and


/= a/=b a=a/b
then assign to left operand

Modulus AND: Takes modulus using left and right


%= a%=b a=a%b
operands and assign the result to left operand

Divide(floor) AND: Divide left operand with right operand


//= a//=b a=a//b
and then assign the value(floor) to left operand

Exponent AND: Calculate exponent(raise power) value


**= a**=b a=a**b
using operands and assign value to left operand
Operator Description Syntax

Performs Bitwise AND on operands and assign value to left


&= a&=b a=a&b
operand

Performs Bitwise OR on operands and assign value to left


|= a|=b a=a|b
operand

Performs Bitwise xOR on operands and assign value to left


^= a^=b a=a^b
operand

Performs Bitwise right shift on operands and assign value


>>= a>>=b a=a>>b
to left operand

Performs Bitwise left shift on operands and assign value to a <<= b a= a <<
<<=
left operand b

5. Identity Operators in Python


In Python, is and is not are the identity operators both are used to check if two values are
located on the same part of the memory. Two variables that are equal do not imply that they
are identical.
is True if the operands are identical
is not True if the operands are not identical

6. Membership Operators in Python


In Python, in and not in are the membership operators that are used to test whether a value or
variable is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence

7. Ternary Operator in Python


in Python, Ternary operators also known as conditional expressions are operators that
evaluate something based on a condition being true or false. It was added to Python in version
2.5.
It simply allows testing a condition in a single line replacing the multiline if-else making the
code compact.

Syntax : [on_true] if [expression] else [on_false]


UNIT II DATA TYPES IN PYTHON
Lists, Tuples, Sets, Strings, Dictionary, Modules: Module Loading and Execution
– Packages – Making Your Own Module – The Python Standard Libraries.
PART A (2 MARKS)

1. Give the difference between list and tuple?


TUPLE
Sno LIST

1 Lists are mutable Tuples are immutable

The implication of iterations is The implication of iterations


2
Time-consuming is comparatively Faster

The list is better for performing A Tuple data type is


3 operations, such as insertion and appropriate for accessing the
deletion. elements

2. What is slicing in list mention its syntax with example?


slicing is the extraction of a part of a string, list, or tuple. It enables users to access the
specific range of elements by mentioning their indices.
Syntax: Object [start:stop:step]
“Start” specifies the starting index of a slice.
“Stop” specifies the ending element of a slice
3. What is tuple in python data collection?
Tuples are used to store multiple items in a single variable.
 Tuple is one of 4 built-in data types in Python used to store collections of data,
the other 3 are List, Set, and Dictionary, all with different qualities and usage.
 A tuple is a collection which is ordered and unchangeable.
 Tuples are written with round brackets.
4. What is meant by set in python?
Set is a data type in python used to store several items in a single variable. It is one of
the four built-in data types (List, Dictionary, Tuple, and Set) having qualities and usage
different from the other three. It is a collection that is written with curly brackets and is
both unindexed and unordered.

5. Explain dictionary in python?


Dictionaries are used to store data values in key: value pairs. A dictionary is a collection
which is ordered, changeable and do not allow duplicates. Dictionaries are written with
curly brackets, and have keys and values:
6. What is len function and explain how it is used on strings with an example?
The len() function returns the number of items in an object. When the object is a string,
the len() function returns the number of characters in the string.

7. How to split string and what function is used to perform that operation?
The split() function in Python is a built-in string method that is used to split a string into
a list of substrings based on a specified delimiter. The function takes the delimiter as an
argument and returns a list of substrings obtained by splitting the original string
wherever the delimiter is found.

8. Write a program to reverse the given number?


num = 1234
reversed_num = 0
while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
print("Reversed Number: " + str(reversed_num))

PART B AND C
1. Explain the following with example
(I) creating the list
Lists in Python can be created by just placing the sequence inside the square brackets[].

# Python program to demonstrate


# Creation of List

# Creating a List
List = []
print("Blank List: ")
print(List)

# Creating a List of numbers


List = [10, 20, 14]
print("\nList of numbers: ")
print(List)

# Creating a List of strings and accessing


# using index
List = ["Geeks", "For", "Geeks"]
print("\nList Items: ")
print(List[0])
print(List[2])
(ii)Accessing the elements of list
In order to access the list items refer to the index number. Use the index operator [ ] to
access an item in a list. The index must be an integer. Nested lists are accessed using nested
indexing.
# Python program to demonstrate
# accessing of element from list

# Creating a List with


# the use of multiple values
List = ["Geeks", "For", "Geeks"]

# accessing a element from the


# list using index number
print("Accessing a element from the list")
print(List[0])
print(List[2])

(iii) Adding elements to list


Elements can be added to the List by using the built-in append() function. Only one element
at a time can be added to the list by using the append() method, for the addition of multiple
elements with the append() method, loops are used. Tuples can also be added to the list with
the use of the append method because tuples are immutable. Unlike Sets, Lists can also be
added to the existing list with the use of the append() method.

Eg:
List = []
print("Initial blank List: ")
print(List)

# Addition of Elements
# in the List
List.append(1)
List.append(2)
List.append(4)
print("\nList after Addition of Three elements: ")
print(List)

# Adding elements to the List


# using Iterator
for i in range(1, 4):
List.append(i)
print("\nList after Addition of elements from 1-3: ")
print(List)

# Adding Tuples to the List


List.append((5, 6))
print("\nList after Addition of a Tuple: ")
print(List)

# Addition of List to a List


List2 = ['For', 'Geeks']
List.append(List2)
print("\nList after Addition of a List: ")
print(List)

(iv) Delete elements from list


Elements can be removed from the List by using the built-in remove() function but an Error
arises if the element doesn’t exist in the list. Remove() method only removes one element at
a time, to remove a range of elements, the iterator is used. The remove() method removes the
specified item.
Eg:
# Python program to demonstrate
# Removal of elements in a List

# Creating a List
List = [1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12]
print("Initial List: ")
print(List)

# Removing elements from List


# using Remove() method
List.remove(5)
List.remove(6)
print("\nList after Removal of two elements: ")
print(List)

2. Define dictionary in python. Outline the operation in dictionary with an example.


Soln:
Dictionary in Python is a collection of keys values, used to store data values like a map,
which, unlike other data types which hold only a single value as an element.
Creating a Dictionary
In Python, a dictionary can be created by placing a sequence of elements within
curly {} braces, separated by ‘comma’. Dictionary holds pairs of values, one being the Key
and the other corresponding pair element being its Key:value. Values in a dictionary can be
of any data type and can be duplicated, whereas keys can’t be repeated and must
be immutable.
Adding elements to a Dictionary
Addition of elements can be done in multiple ways. One value at a time can be added to a
Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’. Updating an
existing value in a Dictionary can be done by using the built-in update() method. Nested key
values can also be added to an existing Dictionary.
Accessing elements of a Dictionary
In order to access the items of a dictionary refer to its key name. Key can be used inside
square brackets.
Dictionary methods
Method Description

dic.clear() Remove all the elements from the dictionary

dict.copy() Returns a copy of the dictionary

dict.get(key, default = “None”) Returns the value of specified key

dict.items() Returns a list containing a tuple for each key value pair

dict.keys() Returns a list containing dictionary’s keys

dict.update(dict2) Updates dictionary with specified key-value pairs

dict.values() Returns a list of all the values of dictionary

pop() Remove the element with specified key

popItem() Removes the last inserted key-value pair

dict.setdefault(key,default= set the key to the default value if the key is not specified
“None”) in the dictionary

dict.has_key(key) returns true if the dictionary contains the specified key.

dict.get(key, default = “None”) used to get the value specified for the passed key.
Eg:
# demo for all dictionary methods
dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}

# copy() method
dict2 = dict1.copy()
print(dict2)

# clear() method
dict1.clear()
print(dict1)

# get() method
print(dict2.get(1))

# items() method
print(dict2.items())

# keys() method
print(dict2.keys())

# pop() method
dict2.pop(4)
print(dict2)

# popitem() method
dict2.popitem()
print(dict2)

# update() method
dict2.update({3: "Scala"})
print(dict2)

# values() method
print(dict2.values())

3. write a python program implementing application using list and tuples?

LIST PROGRAM
list = [“apple”, ”ball”,” cat”,” dog”]
print(list)
print(list[0])
list2 = [1,3,5,7,8,4]
print(sum(list2))
print(min(list2))
print(max(list2))
print(list2[0])
print(list2[-1])

OUTPUT

[‘apple’,’ball’,’cat’,’dog’]
Apple
28
1
8
1
4

TUPLE PROGRAM
Tuple1 tuple(input(“enter the tuple elemets…”)
Print(tuple1)
Count = 0
For I in tuple1:
Print(“tuple1[%d] = %s”(count, i)
Count = count+1

OUTPUT

Enter the tuple elements… 98765


(‘9’,’8’,’7’,’6’,’5’)
Tuple1[0] = 9
Tuple1[1] = 8
Tuple1[2] = 7
Tuple1[3] = 6
Tuple1[4] = 5

4. what is sets? Explain python sets in detail discussing the operation and methods
with suitable example?
Soln:
 Sets are used to store multiple items in a single variable.
 Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage.
 A set is a collection which is unordered, unchangeable*, and unindexed.
 Sets are written with curly brackets.
Unordered
 Unordered means that the items in a set do not have a defined order.
 Set items can appear in a different order every time you use them, and cannot be
referred to by index or key.
Eg:
thisset = {"apple", "banana", "cherry"}
print(thisset)

Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set has been
created.
Once a set is created, you cannot change its items, but you can remove items and add new
items

Duplicates Not Allowed


Sets cannot have two items with the same value.
Eg:
thisset={"apple", "banana", "cherry", "apple"}
print(thisset)
Output
{‘banana’, ‘cherry’, ‘apple’}

Get the Length of a Set


To determine how many items a set has, use the len() function.
Eg:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
Output
3
Example
Days=set([“Monday”,”Tuesday”,”Wednesday”,”Thursday”,”Friday”,
”Saturday”, “Sunday”])
Print(days)
Print(type(days))
Print(“looping through the set elements…”)
For i in Days:
Print(i)
5. Explain briefly about strings and its function with example?

Python string is the collection of the characters surrounded by single quotes, double quotes, or
triple quotes. The computer does not understand the characters; internally, it stores
manipulated character as the combination of the 0's and 1's.
Each character is encoded in the ASCII or Unicode character. So we can say that Python
strings are also called the collection of Unicode characters.
In Python, strings can be created by enclosing the character or the sequence of characters in
the quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the
string.

Creating String in Python

We can create a string by enclosing the characters in single-quotes or double- quotes. Python
also provides triple-quotes to represent the string, but it is generally used for multiline string
or docstrings.

#Using single quotes


str1 = 'Hello Python'
print(str1)
#Using double quotes
str2 = "Hello Python"
print(str2)

#Using triple quotes


str3 = '''''Triple quotes are generally used for
represent the multiline or
docstring'''
print(str3)

Accessing characters in Python String


In Python, individual characters of a String can be accessed by using the method of
Indexing. Indexing allows negative address references to access characters from the back of
the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so
on.
While accessing an index out of the range will cause an IndexError. Only Integers are
allowed to be passed as an index, float or other types that will cause a TypeError.

String Slicing
In Python, the String Slicing method is used to access a range of characters in the String.
Slicing in a String is done by using a Slicing operator, i.e., a colon (:). One thing to keep in
mind while using this method is that the string returned after slicing includes the character at
the start index but not the character at the last index.
Example:
In this example, we will use the string-slicing method to extract a substring of the original
string. The [3:12] indicates that the string slicing will start from the 3rd index of the string to
the 12th index, (12th character not including). We can also use negative indexing in string
slicing.
Reversing a Python String
By accessing characters from a string, we can also reverse strings in Python. We can
Reverse a string by using String slicing method.
Example:
In this example, we will reverse a string by accessing the index. We did not specify the first
two parts of the slice indicating that we are considering the whole string, from the start index
to the last index.
Deleting/Updating from a String
In Python, the Updation or deletion of characters from a String is not allowed. This will
cause an error because item assignment or item deletion from a String is not supported.
Although deletion of the entire String is possible with the use of a built-in del keyword. This
is because Strings are immutable, hence elements of a String cannot be changed once
assigned. Only new strings can be reassigned to the same name.
Updating a character
A character of a string can be updated in Python by first converting the string into a Python
List and then updating the element in the list. As lists are mutable in nature, we can update
the character and then convert the list back into the String.
Another method is using the string slicing method. Slice the string before the character you
want to update, then add the new character and finally add the other part of the string again
by string slicing.
Updating Entire String
As Python strings are immutable in nature, we cannot update the existing string. We can only
assign a completely new value to the variable with the same name.
Deleting a character
Python strings are immutable, that means we cannot delete a character from it. When we try to
delete thecharacter using the del keyword, it will generate an error.
Deleting Entire String
Deletion of the entire string is possible with the use of del keyword. Further, if we try to print
the string, this will produce an error because the String is deleted and is unavailable to be
printed.
Escape Sequencing in Python
While printing Strings with single and double quotes in it causes SyntaxError because String
already contains Single and Double Quotes and hence cannot be printed with the use of either
of these. Hence, to print such a String either Triple Quotes are used or Escape sequences are
used to print Strings.
Escape sequences start with a backslash and can be interpreted differently. If single quotes are
used to represent a string, then all the single quotes present in the string must be escaped and
the same is done for Double Quotes.
Formatting of Strings
Strings in Python can be formatted with the use of format() method which is a very versatile
and powerful tool for formatting Strings. Format method in String contains curly braces {} as
placeholders which can hold arguments according to position or keyword to specify the order.
Python String constants
Built-In Function Description

string.ascii_letters Concatenation of the ascii_lowercase and ascii_uppercase constants.

string.ascii_lowercase Concatenation of lowercase letters

string.ascii_uppercase Concatenation of uppercase letters

string.digits Digit in strings

string.hexdigits Hexadigit in strings

string.letters concatenation of the strings lowercase and uppercase

string.lowercase A string must contain lowercase letters.

string.octdigits Octadigit in a string

string.punctuation ASCII characters having punctuation characters.

string.printable String of characters which are printable

Returns True if a string ends with the given suffix otherwise returns
String.endswith()
False

Returns True if a string starts with the given prefix otherwise returns
String.startswith()
False

Returns “True” if all characters in the string are digits, Otherwise, It


String.isdigit()
returns “False”.

Returns “True” if all characters in the string are alphabets,


String.isalpha()
Otherwise, It returns “False”.
Built-In Function Description

string.isdecimal() Returns true if all characters in a string are decimal.

one of the string formatting methods in Python3, which allows


str.format()
multiple substitutions and value formatting.

String.index Returns the position of the first occurrence of substring in a string

string.uppercase A string must contain uppercase letters.

string.whitespace A string containing all characters that are considered whitespace.

Method converts all uppercase characters to lowercase and vice


string.swapcase()
versa of the given string, and returns it

returns a copy of the string where all occurrences of a substring is


replace()
replaced with another substring.
Deprecated string functions
Built-In Function Description

string.Isdecimal Returns true if all characters in a string are decimal

String.Isalnum Returns true if all the characters in a given string are alphanumeric.

string.Istitle Returns True if the string is a title cased string

String.partition splits the string at the first occurrence of the separator and returns a tuple.

String.Isidentifier Check whether a string is a valid identifier or not.

String.len Returns the length of the string.

Returns the highest index of the substring inside the string if substring is
String.rindex
found.

String.Max Returns the highest alphabetical character in a string.


Built-In Function Description

String.min Returns the minimum alphabetical character in a string.

String.splitlines Returns a list of lines in the string.

string.capitalize Return a word with its first character capitalized.

string.expandtabs Expand tabs in a string replacing them by one or more spaces

string.find Return the lowest indexing a sub string.

string.rfind find the highest index.

Return the number of (non-overlapping) occurrences of substring sub in


string.count
string

string.lower Return a copy of s, but with upper case, letters converted to lower case.

Return a list of the words of the string, If the optional second argument
string.split
sep is absent or None

string.rsplit() Return a list of the words of the string s, scanning s from the end.

rpartition() Method splits the given string into three parts

Return a list of the words of the string when only used with two
string.splitfields
arguments.

string.join Concatenate a list or tuple of words with intervening occurrences of sep.

It returns a copy of the string with both leading and trailing white spaces
string.strip()
removed

string.lstrip Return a copy of the string with leading white spaces removed.

string.rstrip Return a copy of the string with trailing white spaces removed.
Built-In Function Description

string.swapcase Converts lower case letters to upper case and vice versa.

string.translate Translate the characters using table

string.upper lower case letters converted to upper case.

string.ljust left-justify in a field of given width.

string.rjust Right-justify in a field of given width.

string.center() Center-justify in a field of given width.

Pad a numeric string on the left with zero digits until the given width is
string-zfill
reached.

Return a copy of string s with all occurrences of substring old replaced


string.replace
by new.

Returns the string in lowercase which can be used for caseless


string.casefold()
comparisons.

Encodes the string into any encoding supported by Python. The default
string.encode
encoding is utf-8.

string.maketrans Returns a translation table usable for str.translate()


Advantages of String in Python:
 Strings are used at a larger scale i.e. for a wide areas of operations such as storing and
manipulating text data, representing names, addresses, and other types of data that can be
represented as text.
 Python has a rich set of string methods that allow you to manipulate and work with strings
in a variety of ways. These methods make it easy to perform common tasks such as
converting strings to uppercase or lowercase, replacing substrings, and splitting strings into
lists.
 Strings are immutable, meaning that once you have created a string, you cannot change it.
This can be beneficial in certain situations because it means that you can be confident that
the value of a string will not change unexpectedly.
 Python has built-in support for strings, which means that you do not need to import any
additional libraries or modules to work with strings. This makes it easy to get started with
strings and reduces the complexity of your code.
 Python has a concise syntax for creating and manipulating strings, which makes it easy to
write and read code that works with strings.
Drawbacks of String in Python:
 When we are dealing with large text data, strings can be inefficient. For instance, if you
need to perform a large number of operations on a string, such as replacing substrings or
splitting the string into multiple substrings, it can be slow and consume a lot resources.
 Strings can be difficult to work with when you need to represent complex data structures,
such as lists or dictionaries. In these cases, it may be more efficient to use a different data
type, such as a list or a dictionary, to represent the data.

6. What do you meant by python IDE? Explain in detail?

The term "IDE" refers for "Integrated Development Environment," which is a coding tool
that aids in automating the editing, compiling, testing, and other steps of an SDLC while
making it simple for developers to execute, write, and debug code.
It is specifically made for software development and includes a number of tools that are
used in the creation and testing of the software.
 PyCharm
 Spyder
 PyDev
 Atom
 Wing
 Jupyter Notebook
 Thonny

Pycharm
The Jet Brains created PyCharm, a cross-platform Integrated Development Environment
(IDE) created specifically for Python. It is the most popular IDE and is accessible in both
a premium and a free open-source version. By handling everyday duties, a lot of time is
saved.
It is a full-featured Python IDE with a wealth of features including auto code completion,
easy project navigation, quick error checking and correction, support for remote
development, database accessibility, etc.
Features
o Smart code navigation
o Errors Highlighting
o Powerful debugger

spyder
Spyder is a well-known open-source IDE that is best suited for data research and has a
high level of recognition in the industry. Scientific Python Development Environment is
Spyder's full name. It supports all popular operating systems,including Windows, MacOS
X, and Linux.

A number of features are offered by it, including a localised code editor, a document
viewer, a variable explorer, an integrated console, etc. It also supports a number of
scientific modules, including SciPy and NumPy.

Features
o Proper syntax highlighting and auto code completion
o Performs well in multi-language editor and auto code completion mode

pydev
As an external plugin for Eclipse, PyDev is one of the most popular Python IDEs. The
Python programmers who have a background in Java naturally gravitate towards this
Python interpreter because it is so well-liked by users.

In 2003-2004, Aleksandar Totic, who is well known for his work on the Mosaic
browser, contributed to the Pydev project.

Django integration, code auto-completion, smart and block indents, among other
features, are features of Pydev.
Features
o Strong Parameters like refactoring, debugging, code analysis, and
codecoverage function.
o It supports virtual environments, Mypy, and black formatter.
o Also supports PyLint integration, remote debugger, Unit test integration, etc.

Atom
GitHub, a company that was first founded as an open-source, cross-platform project, is
the company that creates Atom. It is built on the Electron framework, which enables
cross-platform desktop applications utilising Chromium and Node.js and is dubbed the
"Hackable Text Editor for the 21st Century."

Features
o Visualize the results on Atom without open any other window.
o A plugin named "Markdown Preview Plus" provides built-in
support forediting and visualizing Markdown files.
WING
It's described as a cross-platform IDE with a tonne of useful features and respectable
development support. It is free to use in its personal edition. The 30- day trial period for
the pro version is provided for the benefit of the developers.
Features
Customizable and can have extensions as well
JUPYTER NOTEBOOK
Jupyter is one of the most used Python notebook editors that is used across the Data
Science industry. You can create and edit notebook documents using this web application,
which is based on the server-client architecture. It utilises Python's interpretive nature to
its fullest potential.

Features
o Supports markdowns
o Easy creation and editing of codes
o Ideal for beginners in data science

THONNY
Thonny is a Python IDE (Integrated Development Environment) that is open- source,
free, and geared towards beginners. Since its initial release in 2016, it has grown to be a
well-liked option for novice Python coders.

Thonny's user-friendly interface is one of its most distinguishing qualities. It makes it


simple for beginners to learn Python and debug their programmes because it
incorporates a code editor, debugger, and REPL (Read-Eval-Print-Loop) in a single
window. To assist users with writing proper code, Thonny also has tools like code
completion, syntax highlighting, and error highlighting.

Thonny IDE that works well for teaching and learning programming is Thonny.
Software that highlights syntax problems and aids code completion was created at the
University of Tartu.

Features
o Simple debugger
o Supports highlighting errors and auto code completion
6. Explain about packages in python with example?
The files are organize in different folders and subfolders based on some criteria, so that
they can be managed easily and efficiently. For example, we keepall our games in a
Games folder and we can even subcategorize according to the genre of the game or
something like this. The same analogy is followed by the packages in Python.
What is a Python Package?
Python modules may contain several classes, functions, variables, etc.
whereas Python packages contain several modules. In simpler terms, Package
in Python isa folder that contains various modules as files.
Creating Package
create a package in Python named mypckg that will contain two modules mod1 and mod2.
To create this module follow the below steps:
Create a folder named mypckg.
Inside this folder create an empty Python file i.e. init .py
Then create two modules mod1 and mod2 in this folder.
init__.py helps the Python interpreter recognize the folder as a package. It alsospecifies the
resources to be imported from the modules. If the init__.py is empty this means that all the
functions of the modules will be imported. We can also specify the functions from each
module to be made available.
For example,
from .mod1 import gfg
from .mod2 import sum
Import Modules from a Package
We can import these Python modules using the from…import statement
and thedot(.) operator.
Syntax:
import package_name.module_name
Example
from mypckg
import mod1from mypckg
import mod2mod1.gfg()
res = mod2.sum(1, 2)print(res)

FILE HANDLING AND EXCEPTION


UNIT HANDLING
III
Files: Introduction – File Path – Opening and Closing Files – Reading and
Writing Files –File Position –Exception: Errors and Exceptions, Exception
Handling, Multiple Exceptions
PART A
1. How to open a file in python?
Opening a file creates a file object. In this example, the variable frefers tothe new file
object. >>> f = open("test.dat","w")
>>> print f <open file ‗test.dat„, mode ‗w„ at fe820> The open function takes two
arguments. The first is the name of the file, and the second is themode. Mode "w"
means that we are opening the file for writing.
2. Explain how the write method works on a file?
>>> f.write("Now is the time")
>>> f.write("to close the file")
Closing the file tells the system that we are done writing and makes thefile
availablefor reading:
>>> f.close()
3. Which method is used to read the contents of a file which is already created?
The read method reads data from the file. With no arguments,reads the entire
contents of the file:
>>> text = f.read()
>>> print text
Now is the time to close the file
4. What is text file? Give an example for text file?
A text file is a file that contains printable characters and white space,organized
into lines separated by newline characters.
To demonstrate, we„ll create a text file with three lines of text separated by newlines:
>>> f = open("test.data","w")
>>> f.write("line one\nline two\nline three\n")
>>> f.close()
5. What is an exception? Explain with few examples
Whenever runtime error occurs, it creates an exception. The program stops
executionand prints an error message.
EXAMPLE:
Dividing by Zero creates an exception:
Print 55/0
ZeroDivisionError: integer division or modulo
6. How do you delete a file in python?
The remove() method is used to delete a file by supplying the name of the file to be
deleted as argument.
Syntax: os.remove(filename)
7. What is the function of raise statement?
The raise statement in python is used to forcefully invoke an exception.Syntax for
raising an exception is:
raise<exception name>
8. Write a python script to display current data and time?
import datetime
now = datetime.datetime.now()
print(“current date and time:”)
print(now.strftime(“%y-%m-%d%h:%m:%s”)
9. Explain the advantages of python files?
 When the data stored in a file, it is stored permanently. This means that
even through the computer is switched off, the data cannot be removed from
the memory since the file is stored ion permanent memory. This file can be
utilized as and when required.
 It is possible to update the data.
 Files are highly useful to store huge amount of data
 Once the data is stored in a file, the same can be used in any other program
2. Differentiate the exception and error?
Errors are caused by the mistakes in program. There are three types of errors: syntax
error, Runtime error, logical error. The syntax error can be rectified when the compilers
throws errors. The logical errors are erroneous output; the program gets executed but the
output is not desired one. A syntactically correct statement might cause errors during
execution. Errors detected during execution/runtime are called exception
3. What is the difference between append and write mode?
The write pointer is set to end of file when the file is opened in “a” mode in
append mode the file can never be read. The contents can only be written at the
end of the file.In the write mode the write pointer is set to the beginning of the
file.
4. List some few common exception types and explain when they occur?
 ArithmeticError- Base class for all errors that occur for numeric calculations.
 OverflowError- Raised when a calculation exceeds maximum limit for a
numerictype.
 ZeroDivisionError- Raised when division or modulo by zero takes place.
 ImportError- Raised when an import statement fails.
 IndexError- Raised when an index is not found in a sequence.
 RuntimeError- Raised when a generated error does not fall into any category
5. What is file object?
A file object allows you to access, use, and manipulate all the user accessible
files. ItMaintains the state about the file it has opened
6. What is the special file that each package in python must contain?
Each package in python must contain a special file called _init_.py
7. Explain namespace and scoping?
Variables are names or identifiers that map to objects. A namespace is a dictionary
of variable names/keys and their corresponding object values. A python statement
can access variables in a local namespace and global namespace. If the local and
global variables have the same name, the local variable shadows the global variable.
Each function has its own local namespace.
8. What do you mean by file position?
The tell() method tells you the current position within the file; the read or write
willoccur at that many bytes from the beginning of the file.
Syntax: fileobject.tell ()
The seek () method changes the current file position. The offset argument
indicates the number of bytes to be moved. The from argument specifies the
reference position fromwhere the bytes are to be moved.
Syntax: fileobject.seek (offset[, where])

9. List the different ways to read a file?


The text file can be read in four different ways listed below
 Using Read Method
 Using ReadLine Method
 Using For Line
 Using In Line Method
10.Write a simple program which illustrates Handling exception?
x=int(input(Please enter a number:))
break
except ValueError:
print(Oops! That was no valid number. Try again…)
11.Write the syntax in python for Open () function?
file object=open(file_name [,access_mode][,buffering])
 file_name: the name of the file argument is a string value that contains the
name offile that you want to access.
 access_mode: the access mode determines the mode in which the file
has to beopened, i.e., read, write, append etc.,
 buffering: if the buffering values are set to 0, no buffering takes
place. If thebuffering value is 1, line buffering is performed while
accessing a file.
12.What is pickle in python?
Pickling save an object to a file for later retrieval. The pickle module helps to translate
almost any type of object to a string suitable for storage in database and then translate The
string back into objects.
13.Write a program that counts the number of words in file?
f=open(“text.txt”,”r”)
content = f.readline(20)
words = content.split() print(words)
14.What is argument of an exception?
An exception can have an argument, which is a value that gives additional
informationabout the problem. The contents of the argument vary by exception.
Argument Exception is thrown when a method is invoked and at least one of the
passedarguments does not meet the parameter specification of the called method.
15.Define the python working with binary files?
Binary file handles the data in the form of bytes. Hence, they can be used to read
or write text, images, or audio and video files. To open a binary file for reading
purpose we can use „rb‟mode. Here „b‟ is attached to r to represent that is a
binary file. Similarlyfor write bytes in binary file.
PART B AND C
1. Tabulate the different modes for opening a file and explain the same
withexample?
MODES DESCRIPTION
r opens a file for reading only. the file pointer is placed at the
beginning of the file. this is a default mode.
rb opens a file for reading only in binary format. the file pointer is
placed at the beginning of the file. this is a default mode.
r+ opens a file for both reading and writing. the file pointer is placed
at the beginning of the file.
rb+ opens a file for both reading and writing in binary format. the file
pointer is placed at the beginning of the file.
w opens a file for writing only. overwrites the file if the file exists.if
the file does not exists create a new file for writing.
wb opens a file for writing only in binary format. overwrites the file
if the file exists. if the file does not exists create a new file for
writing.
w+ opens a file for reading and writing. overwrites the file if the file
exists. if the file does not exists create a new file for writing.
wb+_ opens a file for both reading and writing in binary format only. .
overwrites the file if the file exists. if the file does not exists
create a new file for writing.
A open a file for appending. the file pointer s at the end of the file if
he file exists. that is the file is in append mode. if the file does not
exists, it creates a new file for writing
Ab open a file for appending in binary format. the file pointer s at the
end of the file if he file exists. that is the file is in append mode. if
the file does not exists, it creates a new file for writing
a+ open a file for appending and reading. the file pointer s at the end
of the file if he file exists. that is the file is in append mode. if the
file does not exists, it creates a new file for reading and writing
ab+ open a file for appending and reading in binary format. the file
pointer s at the end of the file if he file exists. that is the file is in
append mode. if the file does not exists, it creates a new file for
reading and writing
2. Explain briefly about file position in python?
The seek and tell methods in Python are used for manipulating the current
position of the file pointer in a file.
seek() method
The seek method allows you to move the file pointer to a specific position in the file. You
can use it to reposition the file pointer to a specific location, so that subsequent reads or
writes will start from that position.

Syntax
file.seek(offset, from_where)

The seek method takes two arguments: the first is the offset from the beginning ofthe file,
and the second is an optional reference point that specifies where the offset is relative to.
By default, the reference point is the beginning of the file. Theoffset can be positive (to
move the pointer forward) or negative (to move the pointer backward).
Example
tell() method
The tell method returns the current position of the file pointer, in bytes from the start of
the file. The position is an integer that represents the number of bytes from the beginning
of the file.’

Syntax:
file.tell()

The seek() and tell() methods are used for file cursor manipulation. The seek() method

EXAMPLE
with open("file.txt", "r") as f:
print(f.read(5)) # Prints the first 5 characters of the file
print("Current position:", f.tell()) # Prints the current position of the file pointer
f.seek(5) # Move the file pointer to the 6th character
print(f.read(5)) # Prints the next 5 characters of the file

repositions
the cursor to a specified byte offset, facilitating navigation within the file, while the tell()
method returns the current cursor position. These methods aid in precise file navigation and data
manipulation

3. Explain about the type of errors with example?


ERROR
Errors are the problems in a program due to which the program will stop the execution. On
the other hand, exceptions are raised when some internal eventsoccur which changes the
normal flow of the program types of Error occur in python.

1. Syntax errors
2. Logical errors (Exceptions)

SYNTAX ERRORS
When the proper syntax of the language is not followed then a syntax error
isthrown.
Example
# initialize the amount
variableamount = 10000
# check that You are eligible
to # purchase Dsa Self Paced
or notif(amount>2999)
print("You are eligible to purchase Dsa Self Paced")

LOGICAL ERRORS(EXCEPTION)
When in the runtime an error that occurs after passing the syntax test is called
exception or logical type. For example, when we divide any number by zero
thenthe ZeroDivisionError exception is raised, or when we import a module that
doesnot exist then ImportError is raised.
Example
# initialize the amount
variablemarks = 10000
# perform division with
0a = marks / 0
print(a)

Error Description

IndexError When the wrong index of a list is retrieved.

AssertionError It occurs when the assert statement fails

AttributeError It occurs when an attribute assignment is failed.

ImportError It occurs when an imported module is not found.

Error Description

KeyError It occurs when the key of the dictionary is not found.

NameError It occurs when the variable is not defined.

MemoryError It occurs when a program runs out of memory.

It occurs when a function and operation are applied in


TypeError an incorrect type.
7. What are the file opening and closing in python programming?
There are two types of files that can be handled in Python, normal text files and
binary files (written in binary language, 0s, and 1s). Opening a file refers to getting
the file ready either for reading or for writing. This can be done using the open()
function. This function returns a file object and takes two arguments,one that accepts
the file name and another that accepts the mode(Access Mode).
Syntax: File_object = open(“File_Name”, “Access_Mode”)
Parameters:
File_Name: It is the name of the file that needs to be opened.
Access_Mode: Access modes govern the type of operations
possible in theopened file. The below table gives the list of all
access mode available in python

Syntax Description
Operation

Read and r+ Open the file for reading and writing.


Write
w Open the file for writing.
Write Only
Open the file for reading and writing. Unlike “r+” is
Write and w+ doesn‟t raise an I/O error if file doesn‟t exist.
Read
Open the file for writing and creates new file if it
Append a doesn‟t exist. All additions are made at the end of the
Only file and no existing data can be modified.

Open the file for reading and writing and creates new
Append a+ file if it doesn‟t exist. All additions are made at the end
and Read of the file and no existing data can be modified.
Example

# open the file using open()


functionfile = open("sample.txt")
# Reading from file
print(file.read())
Closing a file in Python
Python automatically closes a file if the reference object of the file is
allocated toanother file, it is a standard practice to close an opened
file as a closed file reduces the risk of being unwarrantedly modified
or read.
Python has a close() method to close a file. The close() method
can be calledmore than once and if any operation is performed on
a closed file it raises a
The below code shows a simple use of close() method to close an
opened file.
Example
# open the file using open()
functionfile = open("sample.txt")
# Reading from fileprint(file.read())
# closing the file
file.close()

8. Explain briefly about reading and writing files with example?


Writing to a file
There are two ways to write in a file.
write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)

writelines() : For a list of string elements, each string is inserted in the textfile.Used
to insert multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
Reading from a file
There are three ways to read data from a text file.
read() : Returns the read bytes in form of a string. Reads n bytes, if no n
specified, reads the entire file.
File_object.read([n])
readline() : Reads a line of the file and returns in form of a string.For
specified n,reads at most n bytes. However, does not reads more than
one line, even if n exceeds the length of the line.
File_object.readline([n])

readlines() : Reads all the lines and return them as each line a string
element in alist.
File_object.readlines()
Example
# Program to show various ways to read and
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]# \n is
placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.writelines(L)
file1.close()
#to change file access modes
file1 = open("myfile.txt","r+")
print("Output of Read function is ")
print(file1.read())
print()
# seek(n) takes the file handle to the nth# byte from the beginning.
file1.seek(0)
print( "Output of Readline function is ")
print(file1.readline())
print file1.seek(0)
# To show difference between read and readline
print("Output of Read(9) function is ")
print(file1.read(9))
print() file1.seek(0)
print("Output of Readline(9) function is ")
print(file1.readline(9))
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()

UNIT IV
MODULES, PACKAGES AND FRAMEWORKS
Modules: Introduction – Module Loading and Execution – Packages – Making Your
Own Module – The Python Libraries for data processing, data mining and
visualization- NUMPY, Pandas, Matplotlib, Plotly-Frameworks- -Django, Flask,
Web2Py.
1. What is module and package in python?
MODULE
a. In python, module is a way to structure program. Each program file in a
module,which imports either modules like object and attribute.
b. A module is a simply a file that defines one or more related functions grouped
together. To reuse the function of a given module, we need to import module.
PACKAGE
c. A package is a collection of modules in Directories that gives a package
hierarchy. When a complex application/program is created it is better to be
organized.
d. The package gives a hierarchical file directory structure of the python
application environment that consists of modules and sub packages and sub-
sub packages
and soon.
2. What are the ways to import a module?
a. Using the import statement
b. Using from clause
c. Using from clause and *
3. What is meant by module in python?
In python, module is a way to structure program. Each program file in a module,which
imports either modules like object and attribute. A module is a simply a file that defines one
or more related functions groupedtogether. To reuse the function of a given module, we need
to import module.
Syntax: import <modulename>
4. List some built in modules in python?
a. OS module for interacting with the operating system.
b. Date time module for working with dates and times.
c. Math module for mathematical operations.
d. csv module for reading and writing csv files.
e. JSON module for working with JSON data.
5. What are the data visualization libraries in python?
 Matplotlib
 Seaborn
 Bokeh
 Plotly

PART B and C
1. Explain data visualization techniques in python ?
Python provides various libraries that come with different features for visualizing
data. All these libraries come with different features and can support various types of
graphs.
Scatter Plot
Scatter plots are used to observe relationships between variables and uses dots to
represent the relationship between them. The scatter() method in the matplotlib
library is used to draw a scatter plot.
Line Chart
Line Chart is used to represent a relationship between two data X and Y on a
different axis. It is plotted using the plot() function.
Bar Chart
A bar plot or bar chart is a graph that represents the category of data with rectangular
bars with lengths and heights that is proportional to the values which they represent.
It can be created using the bar() method.
Histogram
A histogram is basically used to represent data in the form of some groups. It is a
type of bar plot where the X-axis represents the bin ranges while the Y-axis gives
information about frequency. The hist() function is used to compute and create a
histogram. In histogram, if we pass categorical data then it will automatically
compute the frequency of that data i.e. how often each value occurred.
Seaborn
Seaborn is a high-level interface built on top of the Matplotlib. It provides beautiful
design styles and color palettes to make more attractive graphs.
To install seaborn type the below command in the terminal.
pip install seaborn
Scatter Plot
Scatter plot is plotted using the scatterplot() method. This is similar to Matplotlib,
but additional argument data is required.
Line Plot
Line Plot in Sea born plotted using the lineplot() method. In this, we can pass only
the data argument also.
BOKEH
Bokeh is mainly famous for its interactive charts visualization. Bokeh renders its
plots using HTML and JavaScript that uses modern web browsers for presenting
elegant, concise construction of novel graphics with high-level interactivity.
To install this type the below command in the terminal.
pip install bokeh
Interactive Data Visualization
One of the key features of Bokeh is to add interaction to the plots.
Interactive Legends
click_policy property makes the legend interactive. There are two types of
interactivity –
 Hiding: Hides the Glyphs.
 Muting: Hiding the glyph makes it vanish completely, on the other hand, muting
the glyph just de-emphasizes the glyph based on the parameters.

Adding Widgets
Bokeh provides GUI features similar to HTML forms like buttons, sliders,
checkboxes, etc. These provide an interactive interface to the plot that allows
changing the parameters of the plot, modifying plot data, etc. Let’s see how to use
and add some commonly used widgets.
 Buttons: This widget adds a simple button widget to the plot. We have to pass a
custom JavaScript function to the CustomJS() method of the models class.
 Checkbox Group: Adds a standard check box to the plot. Similarly to buttons
we have to pass the custom JavaScript function to the CustomJS() method of the
models class.
 Radio Group: Adds a simple radio button and accepts a custom JavaScript
function.

This is the last library of our list and you might be wondering why plotly.
 Plotly has hover tool capabilities that allow us to detect any outliers or anomalies
in numerous data points.
 It allows more customization.
 It makes the graph visually more attractive.
To install it type the below command in the terminal.
pip install plotly

UNIT V
OBJECT ORIENTED PROGRAMMING IN
UNIT V PYTHON
Creating a Class, Class methods, Class Inheritance, Encapsulation, Polymorphism,
class method vs. static methods, Python object persistence.
1. How to create a class in python?
A class is a user-defined blueprint or prototype from which objects are
created. Classes provide a means of bundling data and functionality
together. Creating a new class creates a new type of object, allowing
new instances of that type to be made. Each class instance can have
attributes attached to it for maintaining its state. Class instances can also
have methods (defined by their class) for modifying their state.

2. Define class method?


The classmethod() is an inbuilt function in Python, which returns a
class method for a given function.
classmethod() in Python Syntax
Syntax: classmethod(function)
Parameter :This function accepts the function name as a parameter.
Return Type:This function returns the converted class method.

3. What do you meant by class inheritance?

 Inheritance allows us to define a class that inherits all the methods and
properties from another class.
 Parent class is the class being inherited from, also called base class.
 Child class is the class that inherits from another class, also called derived
class.

4. Define encapsulation?
Encapsulation is a mechanism of wrapping the data (variables) and code
acting on the data (methods) together as a single unit. In encapsulation, the
variables of a class will be hidden from other classes, and can be accessed
only through the methods of their current class

5. Define polymorphism?
Polymorphism defines the ability to take different forms. Polymorphism in
Python allows us to define methods in the child class with the same name as
defined in their parent class.

6. What is the Static Method in Python?


A static method does not receive an implicit first argument. A static method is also a
method that is bound to the class and not the object of the class. This method can’t
access or modify the class state. It is present in a class because it makes sense for the
method to be present in class.

7. Define Class method vs Static Method


The difference between the Class method and the static method is:
 A class method takes cls as the first parameter while a static method needs no
specific parameters.
 A class method can access or modify the class state while a static method can’t
access or modify it.
 In general, static methods know nothing about the class state. They are utility-
type methods that take some parameters and work upon those parameters. On the
other hand class methods must have class as a parameter.
 We use @classmethod decorator in python to create a class method and we use
@staticmethod decorator to create a static method in python.

PART B AND C
1. Explain briefly about OOPs concept in python?
OOPS CONCEPT IN PYTHON
An object-oriented paradigm is to design the program using classes and objects. The
object is related to real-word entities such as book, house, pencil, etc. The oops
concept focuses on writing the reusable code. It is a widespread technique to solve the
problem by creating objects.
Major principles of object-oriented programming system are given below.
o Class
o Object
o Method
o Inheritance
o Polymorphism
o Data Abstraction
o Encapsulation
Class
The class can be defined as a collection of objects. It is a logical entity that has some
specific attributes and methods. For example: if you have an employee class, then it
should contain an attribute and method, i.e. an email id, name, age, salary, etc.

Object
The object is an entity that has state and behavior. It may be any real-world object like
the mouse, keyboard, chair, table, pen, etc.Everything in Python is an object, and
almost everything has attributes and methods. All functions have a built-in attribute
__doc__, which returns the docstring defined in the function source code.

Method
The method is a function that is associated with an object. In Python, a method is not
unique to class instances. Any object type can have methods.

Inheritance
Inheritance is the most important aspect of object-oriented programming, which
simulates the real-world concept of inheritance. It specifies that the child object
acquires all the properties and behaviors of the parent object.By using inheritance, we
can create a class which uses all the properties and behavior of another class. The new
class is known as a derived class or child class, and the one whose properties are
acquired is known as a base class or parent class.It provides the re-usability of the
code.

Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many, and
morph means shape. By polymorphism, we understand that one task can be performed
in different ways. For example - you have a class animal, and all animals speak. But
they speak differently. Here, the "speak" behavior is polymorphic in a sense and
depends on the animal. So, the abstract "animal" concept does not actually "speak",
but specific animals (like dogs and cats) have a concrete implementation of the action
"speak".

Encapsulation
Encapsulation is also an essential aspect of object-oriented programming. It is used to
restrict access to methods and variables. In encapsulation, code and data are wrapped
together within a single unit from being modified by accident.
Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are nearly
synonyms because data abstraction is achieved through encapsulation. Abstraction is
used to hide internal details and show only functionalities. Abstracting something
means to give names to things so that the name captures the core of what a function or
a whole program does.

2. Elaborate the difference between class method an static method?

The class method in Python is a method, which is bound to the class but not the object
of that class. The static methods are also same but there are some basic differences.
For class methods, we need to specify @classmethod decorator, and for static method
@staticmethod decorator is used.

Syntax for Class Method.


class my_class:
@classmethod
deffunction_name(cls, arguments):
#Function Body
return value

Syntax for Static Method.


class my_class:
@staticmethod
deffunction_name(arguments):
#Function Body
return value
differences between Classmethod and StaticMethod
Class Method Static Method
The class method takes cls The static method does not take any
(class) as first argument. specific parameter.
Class method can access and Static Method cannot access or modify
modify the class state. the class state.

The class method takes the Static methods do not know about class
class as parameter to know state. These methods are used to do some
about the state of that class. utility tasks by taking some parameters.
@classmethod decorator is @staticmethod decorator is used here.
used here.

The Static methods are used to do some utility tasks, and class methods are used
for factory methods. The factory methods can return class objects for different use
cases.

Example code
from datetime import date as dt
class Employee:
def __init__(self, name, age):
self.name = name
self.age = age
@staticmethod
defisAdult(age):
if age > 18:
return True
else:
return False
@classmethod
defemp_from_year(emp_class, name, year):
return emp_class(name, dt.today().year - year)
def __str__(self):
return 'Employee Name: {} and Age: {}'.format(self.name, self.age)
e1 = Employee('Dhiman', 25)
print(e1)
e2 = Employee.emp_from_year('Subhas', 1987)
print(e2)
print(Employee.isAdult(25))
print(Employee.isAdult(16))

You might also like