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)
An algorithm is:
● 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
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
CHAPTER 2
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
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.
● 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)
DO
statement
WHILE condition
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:
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.
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.
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)
read value
END_WHILE
print sum
====================================================================
CHAPTER 3
● 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:
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
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:
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:
4. What is a constant?
=====================================================================
CHAPTER 5
The rules of indentation in Python are essential for defining blocks of code and ensuring proper
execution. Here are the key rules:
● Indent after an if, for, or while statement to indicate the block of code associated with the
control statement.
● Maintain the same level of indentation for statements that are part of the same block.
● Indenting to create blocks is not optional. It is the only way to define a block in Python.
● 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.
● 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.
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.
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
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.
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.
Pre-test/Post-t Pre-test loop: condition is checked Pre-test loop: condition is checked before
est before body execution. body execution.
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.
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.
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.
====================================================================
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.
● 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
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.
return a + b
Keyword Arguments: Arguments are passed by explicitly specifying the parameter name,
allowing you to skip or rearrange arguments.
Default Arguments: Functions can have default values for some parameters, which are used if
no corresponding argument is provided.
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)
def print_info(**kwargs):
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)
my_list = [1, 2, 3]
modify_list(my_list)
# Output:
=====================================================================
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.
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.
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
Suitable for collections of items that Suitable for collections of items that should
Usage may change. not change.
=====================================================================
CHAPTER 10
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.
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?
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)
fromkeys(seq[ Returns a new dictionary with keys from seq and value dict.fromkeys(['a', 'b'],
, v]) v (defaults to None). 0)
=====================================================================
CHAPTER 11
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
● 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
● 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
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.
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
Syntax Errors (Compile time errors): Errors caused by not following the proper structure
(syntax) of the language.
Runtime Errors (Exceptions): Errors that occur during the execution of the program.
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
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.
9. How do you handle the following issue in file processing with Python? Explain
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:
data = file.read()
except FileNotFoundError:
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:
data = file.read()
except PermissionError:
try:
while True:
line = file.readline()
if not line:
except EOFError:
By using try and except blocks, you can gracefully handle these errors and ensure your program
doesn't crash unexpectedly.
=====================================================================