Unit 3: Q&A
NOTE: The following are questions from Unit-3. Try to read and understand the theory
questions. For programs some of them will be easy / similar to Unit-2. Others try to
study and understand.
1) What are statements in python?
An instruction given to the computer to perform an action
Example: x = 10 # assignment statement
print(x) # print statement
2) What is an expression in python?
A combination of variables, constants, and operators that evaluates to a value.
Example: y = 2 + 3 * 4 # expression is (2 + 3 * 4) = 14
3) Differentiate between statements and expressions with examples.
Statement Expression
Statements may or may not produce a Expressions always produce a
value. value.
Every expression can be a
Not every statement is an expression.
statement
Ex: x = 5 (does something, doesn’t return
3 + 2 (evaluates to 5).
a value).
4) Evaluate the following expression:
a=5
b=3
c = a ** b + a % b
Answer: a ** b = 125, a % b = 2 → c = 125+2 => 127
5) What are strings?
A string is a sequence of characters inside quotes. Ex: s = "Hello World"
Strings in python are surrounded by either single quotation marks, or double quotation
marks.
6) Are strings mutable or immutable in python?
Strings are immutable, meaning their contents cannot be changed after they are
created. Any operation that appears to modify a string, such as concatenation or
changing a character, actually creates a new string object with the new value. The
original string object remains unchanged, and the variable is then made to refer to this
new object.
7) Can you use quotes within a string?
Yes, quotes can be used inside a string, as long as they don't match the quotes
surrounding the string.
Example: print("It's alright")
print("His name is 'Johnny'")
print('His name is "Johnny"')
8) Assign a string to a variable and print the output
a = “Hello”
print(a)
9) What is multiline string and how do you declare it? Give example
Multiline strings are used to store text that spans across multiple lines. A multiline string
can be assigned to a variable using three quotes.
Example:
a = """Mumbai is a city,
Maharashtra is a state in India,
Python is programming language
and is easy to learn"""
10) Are strings considered as array in python?
Yes, like many other popular programming languages, strings in Python are arrays of
unicode characters. However, Python does not have a character data type, a single
character is simply a string with a length of 1. Square brackets can be used to access
elements of the string.
11) Define a string and print the character at position 1
a = "Hello, World!"
print(a[1]) # prints e
Note: the first character has the position 0
12) Can we loop through strings? If yes, give example?
Since strings are arrays, we can loop through the characters in a string, with a for loop.
Example:
for x in "banana":
print(x)
13) Write a code to get the length of a string.
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a)) #output: 13
14) How to check if a certain phrase or character is present in a string? Give example.
To check if a certain phrase or character is present in a string, we can use the keyword
in
Example:
txt = "Python is a programming language"
print("Python" in txt)
If present it will return true, else it will return false.
15) check if a certain phrase or character is present in a string using if statement.
txt = " Python is a programming language”
if " programming " in txt:
print("Yes, ' programming ' is present.")
16) List any four string operations that can be performed on the string
s= “Hello World”
s[0] # 'H'
s[-1] # 'd'
s[0:5] # 'Hello'
len(s) # 11
17) List down some string methods/functions and their use?
upper() → Converts to upper case
lower() → Converts to lower case
strip() → removes any leading, and trailing whitespaces.
replace(a, b) → Replace text
split() → Break string into list
join() → Join list into string
Example:
s = " Python Programming "
print([Link]()) # "Python Programming"
print([Link]()) # "PYTHON PROGRAMMING "
print([Link]()) # "python programming "
print([Link]("Python", "C")) # " C Programming "
print([Link]()) # ['Python', 'Programming']
18) Explain different types of errors that occur in python programming.
Syntax errors
A syntax error (also called a "parsing error") occurs when the code does not follow the
grammatical rules of the Python language. The Python interpreter detects these errors
while parsing the code and stops execution immediately, before the program even runs.
A clear error message, including the file name, line number, and a marker pointing to
the location of the error, is displayed to help you debug
Runtime errors (Exceptions)
A runtime error, or an "exception," occurs during the execution of a program. Unlike a
syntax error, the code is grammatically correct, but an error occurs when a specific
instruction cannot be carried out. If not handled, an exception will terminate the
program.
Logical errors
A logical error (or "bug") is the most difficult type of error to find because the program
runs without crashing and without any error messages. Instead, it produces an incorrect
or unintended result because the code's logic is flawed.
19) How Exception is Handled using try-except-finally blocks, explain with example
try block: This block contains the code that might raise an exception. The Python
interpreter first executes the statements inside this block.
except block: If an exception occurs within the try block, the interpreter stops
executing the rest of the try block and immediately jumps to the except block. This
block contains the code to handle the specific error. You can specify
different except blocks to handle different types of exceptions.
finally block: This block contains code that will always execute, regardless of whether
an exception occurred in the try block or was caught by an except block. It is most often
used for cleanup tasks, such as closing files or releasing network connections
Example:
try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
result = numerator / denominator
print(f"The result is: {result}")
except ZeroDivisionError:
# This block runs if a ZeroDivisionError occurs
print("Error: You cannot divide by zero.")
except ValueError:
# This block handles cases where the user inputs non-numeric data
print("Error: Invalid input. Please enter a number.")
finally:
# This block always executes
print("Execution complete. Thank you for using the calculator.")
20) If the employee’s basic salary is input through the keyboard. His dearness
allowance is 45% of basic salary, and house rent allowance is 25% of basic salary.
Write a program to calculate his gross salary.
basic = float(input("Enter Basic: "))
DA = 0.45*basic
HRA = 0.25*basic
print("Gross Salary =", basic+DA+HRA)
21) If a five-digit number is input through the keyboard, write a program to calculate
the sum of its digits.
number_str = input("Enter a five-digit number: ")
total_sum = 0
for digit_char in number_str:
total_sum += int(digit_char)
print("The sum of the digits of”, number_str, “is”, total_sum)
22) Differentiate between an error and an exception in Python
Feature Error Exception
Detected during parsing
(Syntax Errors) or are Occurs during the
Occurrence
bugs in the program's logic execution of a program.
(Logical Errors).
Missing a colon after Dividing a number by zero
Example an if statement causes raises
a SyntaxError. a ZeroDivisionError.
Cannot be handled with
Can be gracefully handled
a try-except block (except
and caught with a try-
in certain advanced
Handling except block, preventing
dynamic execution
the program from
scenarios) and must be
crashing.
fixed in the code.
Prevents the program from Disrupts the normal flow
Program Flow
running at all (Syntax of the program but allows
Error) or leads to incorrect it to be rerouted to a
behavior (Logical Error). specific handling block.
23) A library charges a fine for every book returned late. For first 5 days the fine is 1
rupee, for 6-10 days fine is 2 rupee and above 10 days fine is 5 rupees. If you return
the book after 30 days your membership will be cancelled. Write a program to
accept the number of days the member is late to return the book and display the
fine or the appropriate message.
days = int(input("Enter days late: "))
if days <= 5:
print("Fine =", days*1)
elif days <= 10:
print("Fine =", days*2)
elif days <= 30:
print("Fine =", days*5)
else:
print("Membership Cancelled")
24) The distance between two cities (in km.) is input through the keyboard. Write a
python program to convert and print this distance in meters and centimeters.
km = float(input("Enter km: "))
print("Meters:", km*1000, "Centimeters:", km*100000)
25) Explain about reading and writing files in python
File reading and writing are handled using the built-in open() function, which returns
a file object (or "handle"). The file object is then used with various methods for
operations like reading, writing, or appending. The recommended and safest approach
is to use the with statement, which ensures the file is automatically closed after its use.
Core components of file handling:
i. The open() function: this function is used to open a file. It takes a file path and
a mode as its primary arguments.
syntax: open(file_path, mode)
File Modes: The mode argument determines what operations can be performed on the
file. Common modes include:
'r': Read mode (default). Opens the file for reading. Raises a FileNotFoundError if the
file doesn't exist.
'w': Write mode. Opens the file for writing. Creates a new file if it doesn't
exist. Warning: If the file already exists, all its contents are erased (truncated).
'a': Append mode. Opens the file for appending. New data is added to the end of the
file, preserving its existing content. Creates a new file if it doesn't exist.
'x': Exclusive creation mode. Creates a new file but raises a FileExistsError if the file
already exists.
't': Text mode (default). Handles the file as text and performs encoding/decoding.
'b': Binary mode. Handles the file as raw bytes, used for non-text files like images or
executables
The with statement: It is best practice to use the with statement, also known as a
context manager, for file handling. This simplifies the process by guaranteeing that the
file is automatically and safely closed, even if errors occur.
26) Explain following Exceptions.
a. IO Error
b. EOF Error
c. Import Error
IO Error: An IOError (or OSError in modern Python versions) is an exception that
occurs when an input/output operation fails. This exception is typically associated with
file system and operating system-level issues.
EOF Error: EOF error (End-of-File Error) is raised when a built-in function
like input() reaches the end of a file or data stream unexpectedly, without reading any
data. This usually happens in non-interactive environments or when a program expects
more input but none is provided.
Import Error: An ImportError is raised when an import statement fails to load a module
or a specific name from a module. The Python interpreter cannot find the module or
definition it is being asked to load.
27) Explain in steps how to open, close and Save the files in python
Step 1: Open the file using the with statement
with open("my_notes.txt", "w") as file:
# The file is now open and can be written to.
# Its contents will be overwritten.
Step 2: Write or read the file
with open("my_notes.txt", "w") as file:
[Link]("This is my first line.\n")
[Link]("This is my second line.")
To append data:
with open("my_notes.txt", "a") as file:
[Link]("\nAdding a new line to the end.")
To read data:
with open("my_notes.txt", "r") as file:
content = [Link]()
print(content)
Step 3: Close and save the file
When using the with statement, you do not need to call a close() method explicitly.
Python automatically closes the file for you when the code block inside
the with statement is finished. If with is not used:
file = open("manual_notes.txt", "w")
[Link]("Manual write operation.\n")
# If an error occurs here, the file might remain open.
[Link]() # You must remember to call close() manually.
28) A program has to be written in python which will take two numbers as input from
user and perform the division in such a way that program should not terminate
(because of ZeroDivisionError) even if user input is zero.
# Function to perform safe division
def safe_divide():
try:
# Prompt the user for input and convert to floating-point numbers
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
# Attempt the division
result = numerator / denominator
# If no error occurs, print the result
print(f"The result of {numerator} / {denominator} is: {result}")
except ZeroDivisionError:
# This block executes if a ZeroDivisionError occurs
print("Error: The denominator cannot be zero.")
except ValueError:
# This block handles cases where the user inputs a non-numeric value
print("Error: Invalid input. Please enter valid numbers.")
# Call the function to run the program
safe_divide()
29) If any integer is input through the keyboard. Write a python program to find out
whether it is a prime number or non-prime number.
n = int(input("Enter number: "))
for i in range(2,n):
if n%i==0:
print("Not Prime"); break
else:
print("Prime")
30) How string matching done in Python using regular expression?
import re
if [Link]("cat","concatenate"):
print("Found")
31) If any two numbers are the input by user, write a program to design a simple
arithmetic calculator (addition, subtraction, multiplication and division) with the
help of OOP concepts.
a = int(input(“Enter the first number:”))
b = int(input(“Enter the second number:”))
class Calc:
def add(self,a,b):
return a+b
def sub(self,a,b):
return a-b
def mul(self,a,b):
return a*b
def div(self,a,b):
return a/b
c = Calc()
print([Link](a,b))
print([Link](a,b))
print([Link](a,b))
print([Link](a,b))