0% found this document useful (0 votes)
18 views31 pages

Programming With Python (CT108-3-1-PYP) ALL 12 CHAPTERS QUESTION ANSWERS (THEORY)

Programming with Python (CT108-3-1-PYP) ALL 12 CHAPTERS QUESTION ANSWERS (THEORY)

Uploaded by

Rafaya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views31 pages

Programming With Python (CT108-3-1-PYP) ALL 12 CHAPTERS QUESTION ANSWERS (THEORY)

Programming with Python (CT108-3-1-PYP) ALL 12 CHAPTERS QUESTION ANSWERS (THEORY)

Uploaded by

Rafaya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

CHAPTER 1

1. What are the difficulties related to problem-solving?

● We do not understand the problem correctly.


● Sometimes we do not define the problem correctly or adequately.
● People get afraid of taking decisions while solving problems.
● Sometimes the list of alternatives is incomplete.
● The sequence of solutions to the problems is not logical many times.
● One of the most difficult tasks for the problem solver is writing the instructions​

2. What are the steps to developing a program?

1. Define: Define the problem. Includes input, output and processing.


2. Outline: Outline the solution. Major tasks and subtasks, mainline logic, functions,
control structures, variables etc..
3. Develop: Develop the outline into an algorithm. Includes Flowcharts/Pseudocodes
4. Test: Test the algorithm for correctness. Check for logic errors.
5. Code: Code the algorithm into a specific programming language.
6. Run: Run the program on the computer.
7. Document and Maintain: Document and maintain the program​

3. What are the steps to define a problem?

Inputs: A list of source data provided to the problem.


Outputs: A list of the outputs required.
Processing: A list of actions needed to produce the required outputs.
Defining Diagram (IPO Chart): This step involves carefully reading and rereading the problem
until you completely understand what is required​

4. What is an algorithm? What tools are often used to develop an algorithm?

An algorithm is:

● A set of detailed, unambiguous, ordered instructions developed to describe the processes


necessary to produce the desired output from a given input.
● Written in simple English and is not a formal document. However, it must be simple,
precise, unambiguous, give the correct solution in all cases, and eventually end.

Tools often used to develop an algorithm:


● Pseudocode: Structured English that allows the programmer to concentrate on the logic
of the problem.
● Flowcharts: Pictorial ways to express algorithms or processes, showing the flow of
execution​

5. What are the six basic computer operations?

● Receive Information (input): Using verbs like READ, OBTAIN, GET, INPUT.
● Produce Information (output): Using verbs like PRINT, DISPLAY, SHOW, OUTPUT,
PUT.
● Perform Arithmetic (Process): Using mathematical symbols like +, -, *, /, and verbs like
Compute, Calculate, Determine.
● Assign a Value (Process): Using verbs like Initialize, Set, Save, Store.
● Compare Two Variables and Select One of Two Alternative Actions (Process): Using
keywords like IF, THEN, ELSE, ENDIF.
● Repeat a Group of Actions (Process): Using keywords like FOR, WHILE,
ENDWHILE, REPEAT, UNTIL

6. What is a sequential structure?

A sequential structure is a series of steps or statements that are executed in the order they are
written in an algorithm. It involves the following sequence:

● Start
● Statement 1
● Statement 2
● ...
● Statement n+1
● End The flow of control is sequential, as shown in examples like calculating the area and
perimeter of a rectangle​

What are the basic flowchart symbols? (Important for mcq)


=====================================================================

CHAPTER 2

1. What are the types of operators? Give example

Types of Operators:

● Relational Operators:
○ > (Greater than)
○ >= (Greater than or equal to)
○ < (Less than)
○ <= (Less than or equal to)
○ == (Equal)
○ != (Not equal)
● Logical Operators:
○ && (AND)
■ Example: (x > y) && (y > z) is true if both conditions are true
○ || (OR)
■ Example: (x <= z) || (y == z) is true if either condition is true
○ ! (NOT)
■ Example: !(x >= z) reverses the value of the expression​

2. What are the types of Nested Selections (Nested IF statement)?

A nested IF statement is an IF statement that appears inside another IF statement. Nested IF


statements can be either linear or non-linear, and they are used to handle situations where
multiple criteria must be evaluated before an action is taken.
Linear Nested IF Statements: These are used when a field is being tested for various values,
and a different action is to be taken for each value. Each ELSE immediately follows the IF
condition to which it corresponds.

Non-linear Nested IF Statements: These are used when an IF statement contains another IF
statement, forming a more complex branching structure. The inner IF statement is only executed
if the outer IF condition is true.

3. What are the two styles of repetition or loop? Give examples.

Two Styles of Repetition or Loop:

● Pre-test Loop: The condition is tested before the loop body is executed.

Example:

WHILE condition

statement

END_WHILE

● Post-test Loop: The condition is tested after the loop body is executed. (Note: Not used
in Python)

Example (Not in Python):

DO

statement

WHILE condition

4. What are the types of loops? Explain with examples.


Loops are fundamental control structures in programming that allow the execution of a block of
code multiple times. There are two primary types of loops: for and while.

1. For Loop

A for loop is typically used when the number of iterations is known beforehand. It iterates over a
sequence (like a list or range) and executes the block of code for each element in the sequence.
Best used when the number of iterations is known or can be determined before entering the loop.

Example:

for i in range(1, 6):

print(i)

2. While Loop

A while loop is used when the number of iterations is not known beforehand, and the loop
continues as long as a specified condition is true. Best used when the number of iterations is not
known and depends on a condition evaluated during each iteration.

# Example: Print numbers from 1 to 5

i=1

while i <= 5:

print(i)

i += 1

3. Nested Loop: There is also another type of loop called a nested loop. A nested loop is a loop
inside another loop. The inner loop executes all its iterations for each iteration of the outer loop.
Nested loops are useful for performing complex iterations, such as iterating over
multi-dimensional data structures like matrices or performing operations that require multiple
levels of looping. Both for loop and while loops can have nested loops.

5. What is a sentinel? Give an example.

A sentinel is a special value in a list of values that indicates the end of data. It is a value that
cannot be confused with a valid value (e.g., -999 for a test score).

Example:
sum = 0

read value

WHILE(value != -999)

sum = sum + value

read value

END_WHILE

print sum

====================================================================

CHAPTER 3

1. What is a programming language?

A programming language is:

● A set of rules that provides a way of telling a computer what operations to perform.
● A set of rules for communicating an algorithm.
● It provides a linguistic framework for describing computations.
● A notational system for describing computation in a machine-readable and
human-readable form.
● A tool for developing executable models for a class of problem domains

2. What is a program?

A program is:

● A set of instructions to the computer to perform a job/task.


● A little piece of our intelligence in the computer.
● Something we can encode and give to others to save them the time and energy of figuring
it out.
● A piece of creative art, especially when we do a good job on user experience

3. What is a syntax?

The syntax is the set of legal structures and commands that can be used in a particular
programming language. It defines how the code should be written and structured so that the
compiler or interpreter can understand it​
4. What is a console?

A console is the text box onto which output is printed. Some source code editors pop up the
console as an external window, while others contain their own console window​

5. Why python is a good choice for new programmers?

Python is a good choice for new programmers because:

● It is easy to learn and use.


● It is relatively fast.
● It is object-oriented and strongly typed.
● It is widely used and portable.
● It supports concepts such as polymorphism, operation overloading, and multiple
inheritance.
● It uses indentation to define code blocks, making it more readable.
● It is free and open-source.
● It has built-in types and tools, as well as extensive libraries and third-party utilities.
● It runs on virtually every major platform used today​

6. What are the basic datatypes?

The basic datatypes in Python are:

● Integers (default for numbers)


○ Example: z = 5 / 2 results in 2 (integer division)
● Floats
○ Example: x = 3.456
● Strings
○ Can use double quotes "" or single quotes ''
○ Example: "abc" == 'abc'
○ Triple double-quotes """ for multi-line strings or strings that contain both ' and "
inside them​
● Boolean: True or False
● None Type: None. Used when we want an empty variable.
7. What are the ways of interacting with Python? Explain.

Interactive Mode: Takes single user inputs, evaluates them, and returns the result to the user
(read-eval-print-loop or REPL).

● Benefits:
○ Use as a sandbox to explore new features.
○ Easy to write quick "throwaway" scripts.
○ Useful for debugging.
○ Can be used as a calculator.

Script Mode (Manual Mode): Execute a Python script from the command line.

● Benefits:
○ Run long, complicated programs.
○ The script contains all the commands and can be executed as a whole.

====================================================================

CHAPTER 4

1. What is a variable?

A variable is:

● A name that is used to refer to a memory location.


● Known as an identifier in Python and is used to hold a value.
● Variables in Python do not need to have their type specified because Python is an infer
language and automatically determines the variable type

2. What are the rules for naming a variable?

The rules for naming a variable are:


1. The first character of the variable must be an alphabet or an underscore (_).
2. All characters except the first character may be an alphabet (lowercase a-z or uppercase
A-Z) or digits (0-9).
3. Identifier names must not use any whitespace or special characters (!@#%).
4. Identifier names must not be similar to any Python keyword.
5. Identifier names are case-sensitive. For example, NAME and name are different variables​

3. What are the types of variable?

There are two main types of variables in Python:

Global Variables:

● Can be used throughout the program and have a scope in the entire program.
● A variable declared outside a function is a global variable by default.
● Python provides the global keyword to use a global variable inside a function.

Local Variables:

● Declared inside a function and have scope within the function.


● Cannot be used outside the function.

Fig: Local Variable and Global variable.

4. What is a constant?

● A constant is a type of variable whose value cannot be changed.


● Helpful to think of constants as containers that hold information which cannot be
changed later.
● Refer to names associated with values that never change during a program’s execution.
● Fixed values such as numbers, letters, and strings are called “constants” because their
value does not change.
● Constants are usually declared and assigned in a module.
5. What are the reserved python keywords?

6. What is the rule of precedence for doing arithmetic operations in python?

Highest precedence rule to lowest precedence rule

1. Parenthesis are always respected


2. Exponentiation (raise to a power)
3. Multiplication, Division, and Remainder
4. Addition and Subtraction
5. Left to right

=====================================================================

CHAPTER 5

1. What are the rules of indentation?

The rules of indentation in Python are essential for defining blocks of code and ensuring proper
execution. Here are the key rules:

1. Increase Indent After Control Statements:

● Indent after an if, for, or while statement to indicate the block of code associated with the
control statement.

2. Maintain Indent to Indicate Scope:

● Maintain the same level of indentation for statements that are part of the same block.

3. Reduce Indent to End Block:


● Reduce the indentation to the level of the control statement to indicate the end of the
block.

4. Blank Lines and Comments:

● Blank lines are ignored and do not affect indentation.


● Comments on a line by themselves are ignored with respect to indentation.

5. Blocks are Mandatory:

● Indenting to create blocks is not optional. It is the only way to define a block in Python.

2. Why indentation is necessary?

Indentation is crucial in Python for several reasons:

1. Defining Block of Code:

● Unlike many other programming languages that use braces {} to define blocks of code,
Python uses indentation to indicate a block of code. This includes functions, loops,
conditionals, and other structures.
● Correct indentation is essential for the interpreter to understand the structure of the code.

2. Readability and Maintainability:

● Proper indentation enhances the readability of the code, making it easier to understand
and maintain.
● It helps to visually distinguish different blocks of code, such as nested loops or
conditionals, which can be crucial in debugging and code reviews.

3. Consistency:

● Indentation enforces a consistent coding style across the codebase, which is particularly
important in collaborative environments.
● Consistent indentation helps new developers to quickly grasp the code structure and
logic.

4. Avoiding Errors:

● Incorrect indentation can lead to syntax errors or logical errors that can be difficult to
trace and fix.
● Python will raise an IndentationError if the indentation is not consistent.
3. Explain One Way Decision making in Python.

One Way Decision Making involves using an if statement to execute a block of code if a
specified condition is true. If the condition is false, the block of code is skipped.

4. Explain Two Way Decision making.

Two Way Decision Making uses an if-else statement to choose between two blocks of code based
on a condition. If the condition is true, the if block is executed; otherwise, the else block is
executed.

5. Explain Multi Way Decision making.

Multi Way Decision Making uses if-elif-else statements to evaluate multiple conditions
sequentially. The first condition that evaluates to true will have its corresponding block executed,
and the rest will be skipped. If none of the conditions are true, the else block is executed.

====================================================================
CHAPTER 6

Construct When To Use

Pre-test loops You want the stopping condition to be checked before the loop
body is executed (typically used when you want a loop to execute
zero or more times).

While The most powerful looping construct: you can write a ‘while’ loop
to mimic the behavior of any other type of loop. In general, it
should be used when you want a pre-test loop which can be used
for most any arbitrary stopping condition e.g., execute the loop as
long as the user doesn’t enter a negative number.

For In Python it can be used to step through some sequence

Post-test: None in You want to execute the body of the loop before checking the
Python stopping condition (typically used to ensure that the body of the
loop will execute at least once). The logic can be simulated with a
while loop.

1. Compare While Loops and For Loops.

Feature While Loop For Loop


Used when the number of iterations is Used when the number of iterations is
Usage not known beforehand. known beforehand.
Control Condition-controlled loop. Count-controlled loop.
Syntax while condition: for variable in iterable:
# code to execute # code to execute
Initialization Initialization outside the loop. Initialization within the loop structure.
Condition
Check Before the loop body executes. Implicit in the range or iterable definition.
Typical Use Indefinite loops where the condition Definite loops where the iteration count is
Cases can change dynamically. fixed.
Examples
i=1 total = 0
while i <= 3: for i in range(1, 4):
print(i) total += i
i += 1 print(f"i={i}, total={total}")

Pre-test/Post-t Pre-test loop: condition is checked Pre-test loop: condition is checked before
est before body execution. body execution.

2. Explain Erroneous For Loops

Erroneous for loops occur when the logic or range specified causes the loop to either not execute
or to produce incorrect results. Common errors include:

Incorrect Range: Specifying a range where the start and end values are reversed or where the
step value causes the loop to never run.

Off-by-One Errors: Miscalculating the start or end value, causing one iteration too few or too
many.

3. Explain Sentinel Loops

A sentinel loop continues to process data until it encounters a special value, known as the
sentinel, which indicates the end of the data. The sentinel value must be distinguishable from the
valid data values and is not processed as part of the data.

4. Explain finite and infinite loops.

Finite Loops: A loop that executes a predetermined number of times. The stopping condition
will eventually be met, terminating the loop.

Infinite Loops: A loop that never meets its stopping condition and continues to execute
indefinitely. Typically caused by a logical error where the loop control variable is not updated
correctly.

Causes of Infinite Loops:


1. Condition Never Becomes False: The loop condition is never falsified.
2. Control Variable Not Updated: The variable controlling the loop is not modified
correctly.

====================================================================

CHAPTER 7

1. What is a function?

A function is a block of organized, reusable code that performs a single, related action. Functions
provide better modularity for your application and a high degree of code reusability. You have
already seen some examples of Python's built-in functions, such as print(), but you can also
create your own functions to perform specific tasks.

2. What are the importance of function?

Functions are important for several reasons:

● Reusability: Functions allow you to write a block of code once and reuse it multiple
times, reducing redundancy.
● Maintainability: Functions help break down complex problems into smaller, more
manageable pieces, making the code easier to understand and maintain.
● Modularity: Functions encapsulate code into modular blocks, improving code
organization and readability.
● Debugging: Functions simplify debugging since you can test and debug each function
independently.
● Collaboration: Functions enable team collaboration by allowing different team members
to work on separate functions

3. What are the types of function in python?

There are two main types of functions in Python:

1. Built-in Functions: These are functions provided by Python, such as print(), len(),
type(), etc.
2. User-defined Functions: These are functions that you create to perform specific tasks in
your programs.

4. What are the ways of passing arguments to functions?

There are several ways to pass arguments to functions in Python:


Positional Arguments: The most common type where arguments are passed in the same order
as the parameters.

def add(a, b):

return a + b

print(add(5, 3)) # Output: 8

Keyword Arguments: Arguments are passed by explicitly specifying the parameter name,
allowing you to skip or rearrange arguments.

def greet(name, message):

return f"{message}, {name}!"

print(greet(message="Good morning", name="Alice")) # Output: Good morning, Alice!

Default Arguments: Functions can have default values for some parameters, which are used if
no corresponding argument is provided.

def greet(name, message="Hello"):

return f"{message}, {name}!"

print(greet("Alice")) # Output: Hello, Alice!

Variable-length Arguments: Functions can accept a variable number of arguments using *args
for non-keyword arguments and **kwargs for keyword arguments.

def add(*args):

return sum(args)

print(add(1, 2, 3, 4)) # Output: 10

def print_info(**kwargs):

for key, value in kwargs.items():

print(f"{key}: {value}")
print_info(name="Alice", age=30) # Output: name: Alice, age: 30

Pass by Reference vs. Pass by Value: In Python, all parameters (arguments) are passed by
reference, meaning changes to mutable objects inside a function affect the original object.

def modify_list(lst):

lst.append(4)

print("Inside function:", lst)

my_list = [1, 2, 3]

modify_list(my_list)

print("Outside function:", my_list)

# Output:

# Inside function: [1, 2, 3, 4]

# Outside function: [1, 2, 3, 4]

=====================================================================

CHAPTER 8

1. What is a string?

A string in Python is a sequence of characters. It can include letters, numbers, punctuation, and
any other keyboard characters. Strings are defined by enclosing the characters within single (') or
double (") quotes.

2. What are the characteristics of a string?

Characteristics of a String:

1. Immutable: Strings cannot be changed after they are created. Any operation that
modifies a string will create a new string.
2. Sequence of Characters: A string is a sequence, meaning it can be indexed, sliced, and
iterated over.
3. Concatenation: Strings can be concatenated using the + operator.
4. Repetition: Strings can be repeated using the * operator.
5. Length: The length of a string can be determined using the len() function.
6. Membership Testing: You can check if a substring exists within a string using the in
keyword.
7. String Methods: Strings have a variety of built-in methods for manipulation, such as
upper(), lower(), find(), replace(), and split().
8. Unicode Support: Python strings support Unicode, which allows for the representation
of a vast range of characters from various languages and symbol sets.

3. What are the built in string methods?

capitalize()
1 Capitalizes first letter of string
center(width, fillchar)
Returns a space-padded string with the original string centered to a total of width
2 columns
count(str, beg= 0,end=len(string))
Counts how many times str occurs in string, or in a substring of string if starting index
3 beg and ending index end are given
decode(encoding='UTF-8',errors='strict')
Decodes the string using the codec registered for encoding. encoding defaults to the
3 default string encoding.
encode(encoding='UTF-8',errors='strict')
Returns encoded string version of string; on error, default is to raise a ValueError unless
4 errors is given with 'ignore' or 'replace'.
endswith(suffix, beg=0, end=len(string))
Determines if string or a substring of string (if starting index beg and ending index end
5 are given) ends with suffix; Returns true if so, and false otherwise
expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not
6 provided
find(str, beg=0 end=len(string))
Determine if str occurs in string, or in a substring of string if starting index beg and
7 ending index end are given; returns index if found and -1 otherwise
index(str, beg=0, end=len(string))
8
Same as find(), but raises an exception if str not found
isa1num()
Returns true if string has at least 1 character and all characters are alphanumeric and
9 false otherwise
isalpha()
Returns true if string has at least 1 character and all characters are alphabetic and false
10 otherwise
isdigit()
11 Returns true if string contains only digits and false otherwise
islower()
Returns true if string has at least 1 cased character and all cased characters are in
12 lowercase and false otherwise
isnumeric()
13 Returns true if a unicode string contains only numeric characters and false otherwise
isspace()
14 Returns true if string contains only whitespace characters and false otherwise
istitle()
15 Returns true if string is properly "titlecased" and false otherwise
isupper()
Returns true if string has at least one cased character and all cased characters are in
16 uppercase and false otherwise
join(seq)
Merges (concatenates) the string representations of elements in sequence seq into a
17 string, with separator string
len(string)
18 Returns the length of the string
ljust(width[, fillchar])
Returns a space-padded string with the original string left-justified to a total of width
19 columns
lower()
20 Converts all uppercase letters in string to lowercase
lstrip()
21
Removes all leading whitespace in string
maketrans()
22 Returns a translation table to be used in translate function.
max(str)
23 Returns the max alphabetical character from the string str
min(str)
24 Returns the min alphabetical character from the string str
replace(old, new [, max])
Replaces all occurrences of old in string with new, or at most max occurrences if max
25 given
rfind(str, beg=0,end=len(string))
26 Same as find(), but search backwards in string
rindex( str, beg=0, end=len(string))
27 Same as index(), but search backwards in string
rjust(width,[, fillchar])
Returns a space-padded string with the original string right-justified to a total of width
28 columns.
rstrip()
29 Removes all trailing whitespace of string
split(str="", num=string.count(str))
Splits string according to delimiter str (space if not provided) and returns list of
30 substrings; split into at most num substrings if given
splitlines( num=string.count('\n'))
Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs
31 removed
startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if starting index beg and ending index end
32 are given) starts with substring str; Returns true if so, and false otherwise
strip([chars])
33 Performs both lstrip() and rstrip() on string
swapcase()
34
Inverts case for all letters in string
title()
Returns "titlecased" version of string, that is, all words begin with uppercase, and the
35 rest are lowercase
translate(table, deletechars="")
Translates string according to translation table str(256 chars), removing those in the del
36 string
upper()
37 Converts lowercase letters in string to uppercase
zfill (width)
Returns original string leftpadded with zeros to a total of width characters; intended for
38 numbers, zfill() retains any sign given (less one zero)
isdecimal()
39 Returns true if a unicode string contains only decimal characters and false otherwise

=====================================================================

CHAPTER 9

1. Whats the difference between append and Concatenate in Lists?

Feature Append Concatenate


Adds a single element to the end of
Definition the list. Combines two lists into a new list.
Syntax list.append(element) list1 + list2
Can add any data type (int, str, list,
Data Type etc.). Only combines lists.
Modifies
Original List Yes No, creates a new list.
Example my_list.append(3) new_list = list1 + list2
Result new_list = [1, 2] + [3, 4] results in [1, 2, 3,
Example my_list = [1, 2, 3] 4]

2. What are the list methods?


Method Description Example
append(item) Adds an item to the end of the list. list.append(3)
insert(index, item) Inserts an item at a specified index. list.insert(2, 3)
remove(item) Removes the first occurrence of an item. list.remove(3)
extend(second_list) Appends elements of another list to the end. list.extend([4, 5, 6])
count(item) Returns the number of occurrences of an item. list.count(3)

sort() Sorts the list in ascending order. list.sort()

reverse() Reverses the order of the list. list.reverse()


Removes and returns the item at the specified
pop(index) index. list.pop(2)

clear() Removes all items from the list. list.clear()


Returns the index of the first occurrence of an
index(item) item. list.index(3)

copy() Returns a shallow copy of the list. list.copy()

3. Explain the difference between a string and a list.

Feature String List

Definition Sequence of characters. Sequence of elements (can be of any type).

Mutable No (immutable). Yes (mutable).

Syntax Enclosed in quotes (' or "). Enclosed in square brackets ([ ]).


Element Accessed by index, returns a
Access character. Accessed by index, returns an element.
Various string-specific methods Various list-specific methods (e.g., append,
Methods (e.g., upper, find). sort).

Concatenation Uses + operator. Uses + operator to concatenate two lists.


Example s = "hello" lst = [1, 2, 3]
Immutability
Example s[0] = 'H' raises an error. lst[0] = 10 modifies the list.

4. Explain the differences between List and Tuple.


Feature List Tuple

Syntax Enclosed in square brackets [ ]. Enclosed in parentheses ( ).

Mutable Yes (mutable). No (immutable).


Has methods like append, remove,
Methods sort. Fewer methods available compared to lists.

Suitable for collections of items that Suitable for collections of items that should
Usage may change. not change.

Performance Slower due to mutability. Faster due to immutability.


Example lst = [1, 2, 3] tpl = (1, 2, 3)

5. Explain the differences between Dictionary and Tuple.

Feature Tuple Dictionary

Order Order is maintained. No guaranteed order (in versions < 3.7).

Mutable No (immutable). Yes (mutable).


Element
Access Accessed via index. Accessed using keys.

Syntax Enclosed in parentheses ( ). Enclosed in curly braces { }.


Key-Value
Pairs No Yes
Suitable for associative arrays (key-value
Usage Suitable for fixed collections of items. pairs).
Example tpl = (1, 2, 3) dict = {'a': 1, 'b': 2}

=====================================================================

CHAPTER 10

1. Compare tuples, dictionaries and sets.

Feature Tuple Dictionary Set

Ordered, immutable Unordered collection of Unordered collection of


Definition collection of items. key-value pairs. unique elements.
Enclosed in curly braces { }
Enclosed in with key-value pairs
Syntax parentheses ( ). separated by colons :. Enclosed in curly braces { }.
Yes (mutable for
Mutable No (immutable). Yes (mutable). addition/removal).

Indexing Accessed via index. Accessed via keys. Not supported.


No guaranteed order (in
Order Maintains order. versions < 3.7). No order.

Allows duplicate Keys must be unique; values


Duplicates elements. can be duplicated. Does not allow duplicates.

Example tpl = (1, 2, 3) dct = {'a': 1, 'b': 2} st = {1, 2, 3}

keys(), values(), items(), add(), remove(), union(),


Methods count(), index(). get(), update(). intersection().
Suitable for mathematical set
Suitable for fixed Suitable for associative operations and unique
Usage collections of items. arrays (key-value pairs). collections.

2. What are the set methods?

Method Description Example

add(item) Adds an item to the set. set1.add('kiwi')


update(iterabl
e) Adds multiple items from an iterable to the set. set1.update(['a', 'b'])
Removes an item from the set (raises KeyError if
remove(item) not found). set1.remove('kiwi')

Removes an item from the set (does not raise error


discard(item) if not found). set1.discard('kiwi')

Removes and returns an arbitrary item from the


pop() set. set1.pop()
clear() Removes all items from the set. set1.clear()

copy() Returns a shallow copy of the set. set2 = set1.copy()

union(*sets) Returns the union of sets as a new set. set1.union(set2)


intersection(*
sets) Returns the intersection of sets as a new set. set1.intersection(set2)
difference(*se
ts) Returns the difference of sets as a new set. set1.difference(set2)

symmetric_dif Returns the symmetric difference of sets as a new set1.symmetric_difference(s


ference(set) set. et2)

3. What are the set operations?

Operation Operator Description


Union ` `
Intersection & Contains all elements that are in both sets A and B.
Difference - Contains all elements that are in set A but not in set B.
Symmetric Contains all elements that are either in set A or set B, but not in
Difference ^ both.

4. Why are tuples more efficient?

Immutability: Since tuples are immutable, Python does not need to allocate extra memory to
accommodate potential changes, making tuples more memory efficient than lists.

Performance: Tuples can be faster than lists when iterating over a large collection of elements,
as the fixed size and immutability allow Python to optimize memory usage and access speed.

5. What are the tuple methods?

Method Description Example

count(item) Returns the number of times the item appears in the tuple. tpl.count(2)
Returns the index of the first occurrence of the item in the
index(item) tuple. tpl.index(2)
6. What are the built in methods and functions for dictionaries?

Method Description Example

clear() Removes all items from the dictionary. dct.clear()

copy() Returns a shallow copy of the dictionary. dct2 = dct.copy()

Returns the value of the key. If key does not exist,


get(key[, d]) returns d (defaults to None). dct.get('a', 0)

Returns a view object with a list of the dictionary's


items() key-value pairs. dct.items()

Returns a view object with a list of the dictionary's


keys() keys. dct.keys()

Returns a view object with a list of the dictionary's


values() values. dct.values()

Removes the item with the specified key and returns its
pop(key[, d]) value. If key does not exist, returns d. dct.pop('a', 0)

Removes and returns an arbitrary key-value pair. Raises


popitem() KeyError if the dictionary is empty. dct.popitem()

update([other] Updates the dictionary with the key-value pairs from


) other, overwriting existing keys. dct.update({'b': 2})

fromkeys(seq[ Returns a new dictionary with keys from seq and value dict.fromkeys(['a', 'b'],
, v]) v (defaults to None). 0)

Function Description Example

len(dct) Returns the number of items in the dictionary. len(dct)

sorted(dct) Returns a new sorted list of the dictionary's keys. sorted(dct)

=====================================================================
CHAPTER 11

1. What is file handling?

File handling is a mechanism by which we can read data from disk files in a Python program or
write data from a Python program to disk files. It allows us to store data entered through a
Python program permanently in a disk file​

2. What are the advantages of file systems?

● Data is stored permanently: Data can be stored permanently on disk and retrieved later.
● Updation becomes easy: Data can be easily updated.
● Data can be shared among various programs: Multiple programs can access and
modify the same data.
● Huge amount of data can be stored: Large volumes of data can be stored efficiently

3. What are the types of data files?

● Text File: Stores information in ASCII or UNICODE characters. Each line is terminated
by a special character called EOL (End of Line).
● Binary File: Stores information in the same format as it is in memory. It is faster and
easier for programs to read and write than text files. Data cannot be directly read and
must be accessed through a Python program

4. Discuss the types of File Access Modes.

Mode Description Notes


Write only. If the file does not exist, it is created. If the file
w exists, the existing data is deleted. wb for binary files.
Read only. The file must exist, otherwise an I/O error is
r raised. rb for binary files.
Append. New data is added to the end of existing data. If
a the file does not exist, it is created. ab for binary files.

Write and read. Opens the file for both reading and writing. w+b or wb+ for
w+ The text is overwritten and deleted from an existing file. binary files.

Read and write. Opens the file for both reading and writing. r+b or rb+ for binary
r+ If the file does not exist, an I/O error is raised. files.
Append and read. Can read and write in the file. New
written text will be added at the end following the a+b or ab+ for binary
a+ previously written data. files.
Exclusive creation mode. Opens the file for writing but only
if the file does not already exist. If the file exists, an error is
x raised.

5. What is exception handling?

Exception handling in Python is a mechanism to handle runtime errors, ensuring the normal flow
of the program's execution is maintained. It involves using the try, except, else, and finally
blocks to test and handle errors that occur during program execution

6. What are the types of errors in python?

Syntax Errors (Compile time errors): Errors caused by not following the proper structure
(syntax) of the language.

● Example: def main() (missing colon)

Runtime Errors (Exceptions): Errors that occur during the execution of the program.

● Example: Division by zero, file not found.

Logical Errors: Errors that occur when the program runs without crashing but produces
incorrect results. These are due to mistakes in the program's logic

7. What are the built in exceptions in python?

Exception Description
ZeroDivisionError Raised when division or modulo by zero occurs.
NameError Raised when a local or global name is not found.
IndentationError Raised when there is incorrect indentation.
IOError Raised when an I/O operation fails.
Raised when there is no input from input() function and the end of file
EOFError is reached.

8. What are the different types of exception handling?

Exception Description Example


Handling
Type
python try: print(x) except: print("An
try Block of code to test for errors. exception occurred")
python except: print("An exception
except Block of code to handle the error. occurred")

python try: print("Hello") except:


Block of code to be executed if no print("An exception occurred") else:
else errors occur in the try block. print("No error")

Block of code to be executed


regardless of whether an exception python try: print("Hello") finally:
finally occurs or not. print("This block is always executed")

python try: print(1 / 0) except


Specific Handling specific exceptions by ZeroDivisionError: print("Division by
Exceptions mentioning the exception type. zero error")

python try: print(1 / "a") except


Multiple Handling multiple exceptions by (ZeroDivisionError, TypeError):
Exceptions using a tuple of exception types. print("An error occurred")

python import logging try: print(x)


Logging Logging exceptions for debugging except Exception as e:
Exceptions purposes using the logging module. logging.exception("Error occurred")

9. How do you handle the following issue in file processing with Python? Explain

Common file-related errors include:

● trying to read a file that doesn't exist,


● lacking permissions to access a file,
● encountering unexpected end-of-file conditions.
To handle common file-related errors in Python, such as trying to read a file that doesn't exist,
lacking permissions to access a file, or encountering unexpected end-of-file conditions, you can
use exception handling with try and except blocks. Here is how you can address each issue:

Trying to read a file that doesn't exist: Use a try block to attempt to open the file, and an
except block to catch a FileNotFoundError exception if the file doesn't exist.

try:

with open('filename.txt', 'r') as file:

data = file.read()

except FileNotFoundError:

print("The file does not exist.")

Lacking permissions to access a file: Catch the PermissionError exception to handle cases
where the program lacks the necessary permissions to read or write to the file.

try:

with open('filename.txt', 'r') as file:

data = file.read()

except PermissionError:

print("You do not have permission to access this file.")

Encountering unexpected end-of-file conditions: Catch the EOFError exception to handle


unexpected end-of-file conditions when reading from a file.

try:

with open('filename.txt', 'r') as file:

while True:

line = file.readline()

if not line:

break # End of file reached


print(line)

except EOFError:

print("Unexpected end of file encountered.")

By using try and except blocks, you can gracefully handle these errors and ensure your program
doesn't crash unexpectedly.

=====================================================================

You might also like