CS25C02 - COMPUTER PROGRAMMING (PYTHON)
Unit I: Introduction to Python - Part B Answers
1. Explain the steps in problem solving with suitable examples. (12 Marks)
Problem solving is a systematic process of analyzing a problem and developing a
solution that can be implemented as a computer program. The major steps involved
are:
Step 1: Problem Definition The problem must be clearly and precisely stated, iden-
tifying what is to be solved. Example: “Find the average of three numbers entered
by the user.”
Step 2: Problem Analysis Identify the inputs required, the outputs expected, and
the constraints or processing needed. This is often represented using a Problem Anal-
ysis Chart (PAC), which lists: - Given/Inputs - Required Output - Processing required
- Solution alternatives (if any)
Example: - Inputs: num1, num2, num3 - Output: average - Processing: average =
(num1 + num2 + num3) / 3
Step 3: Developing an Algorithm An algorithm is a step-by-step procedure to solve
the problem written in plain language.
Example Algorithm: 1. Start 2. Read three numbers num1, num2, num3 3. Compute
sum = num1 + num2 + num3 4. Compute average = sum / 3 5. Display average 6.
Stop
Step 4: Flowchart Design A flowchart represents the algorithm graphically using
standard symbols (oval for start/end, parallelogram for input/output, rectangle for
process, diamond for decision).
Step 5: Writing Pseudocode Pseudocode is an informal, English-like representation
of the algorithm closer to actual code.
Example Pseudocode:
BEGIN
READ num1, num2, num3
SET average = (num1 + num2 + num3) / 3
PRINT average
END
Step 6: Coding The algorithm/pseudocode is converted into actual program code
using a programming language such as Python.
Example Python Code:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
1
average = (num1 + num2 + num3) / 3
print("The average is:", average)
Step 7: Testing and Debugging The program is executed with sample inputs to
verify correctness. Errors (syntax, logical, runtime) are identified and corrected.
Step 8: Documentation and Maintenance The program is documented with com-
ments and explanations for future reference, and maintained for updates or modifica-
tions.
Conclusion: These systematic steps - definition, analysis, algorithm, flowchart, pseu-
docode, coding, testing, and documentation - ensure that a problem is solved in an
organized, error-free, and efficient manner.
2. Draw a flowchart and write pseudocode for finding the largest of three
numbers. (12 Marks)
Problem Analysis Chart:
Item Description
Inputs Three numbers A, B, C
Output The largest number
Processing Compare A, B, C pairwise to find the maximum
Algorithm: 1. Start 2. Read three numbers A, B, C 3. If A > B then - If A > C then
Largest = A - Else Largest = C 4. Else - If B > C then Largest = B - Else Largest = C
5. Display Largest 6. Stop
Pseudocode:
BEGIN
READ A, B, C
IF A > B THEN
IF A > C THEN
LARGEST = A
ELSE
LARGEST = C
ENDIF
ELSE
IF B > C THEN
LARGEST = B
ELSE
LARGEST = C
ENDIF
ENDIF
PRINT LARGEST
END
2
Flowchart (Description of Symbols and Flow):
1. Start (Oval/Terminal symbol)
2. Input/Output box (Parallelogram): Read A, B, C
3. Decision box (Diamond): Is A > B ?
• If YES, go to next decision: Is A > C ?
– If YES -> Process box: Largest = A
– If NO -> Process box: Largest = C
• If NO, go to decision: Is B > C ?
– If YES -> Process box: Largest = B
– If NO -> Process box: Largest = C
4. All four branches merge into a single flow line.
5. Output box (Parallelogram): Print Largest
6. End (Oval/Terminal symbol)
(Symbols used: Oval = Start/End, Parallelogram = Input/Output, Diamond = Decision,
Rectangle = Process, Arrows = Flow direction)
Equivalent Python Program:
A = float(input("Enter first number: "))
B = float(input("Enter second number: "))
C = float(input("Enter third number: "))
if A > B:
if A > C:
largest = A
else:
largest = C
else:
if B > C:
largest = B
else:
largest = C
print("The largest number is:", largest)
3. Write a Python program to calculate area and perimeter of geometric
shapes using arithmetic operators. (12 Marks)
Concept: Arithmetic operators in Python (+, -, *, /, **, %, //) are used to perform
mathematical computations such as calculating area and perimeter of shapes like
rectangle, square, circle, and triangle.
Formulas Used:
Shape Area Perimeter
Rectangle length × breadth 2 × (length + breadth)
3
Shape Area Perimeter
Square side ** 2 4 × side
Circle π × r ** 2 2×π×r
Triangle 0.5 × base × height sum of three sides
Python Program:
import math
print("---- Rectangle ----")
length = float(input("Enter length: "))
breadth = float(input("Enter breadth: "))
area_rect = length * breadth
peri_rect = 2 * (length + breadth)
print("Area of Rectangle =", area_rect)
print("Perimeter of Rectangle =", peri_rect)
print("\n---- Square ----")
side = float(input("Enter side of square: "))
area_square = side ** 2
peri_square = 4 * side
print("Area of Square =", area_square)
print("Perimeter of Square =", peri_square)
print("\n---- Circle ----")
radius = float(input("Enter radius of circle: "))
area_circle = [Link] * radius ** 2
peri_circle = 2 * [Link] * radius
print("Area of Circle = %.2f" % area_circle)
print("Perimeter (Circumference) of Circle = %.2f" % peri_circle)
print("\n---- Triangle ----")
base = float(input("Enter base of triangle: "))
height = float(input("Enter height of triangle: "))
a = float(input("Enter side a: "))
b = float(input("Enter side b: "))
c = float(input("Enter side c: "))
area_tri = 0.5 * base * height
peri_tri = a + b + c
print("Area of Triangle =", area_tri)
print("Perimeter of Triangle =", peri_tri)
Sample Output:
---- Rectangle ----
Enter length: 5
Enter breadth: 3
Area of Rectangle = 15.0
4
Perimeter of Rectangle = 16.0
---- Square ----
Enter side of square: 4
Area of Square = 16.0
Perimeter of Square = 16.0
---- Circle ----
Enter radius of circle: 7
Area of Circle = 153.94
Perimeter (Circumference) of Circle = 43.98
Explanation: - The ** operator is used for exponentiation (side squared). - The *
operator performs multiplication, + performs addition. - [Link] is imported from
the built-in math package to get an accurate value of π. - The program demonstrates
use of arithmetic operators (+, *, **, /) for real-world geometric computation.
4. Explain interactive and script mode with example codes. (12 Marks)
Python programs can be executed in two modes: Interactive Mode and Script
Mode.
1. Interactive Mode
In interactive mode, Python statements are typed and executed one at a time directly
at the Python interpreter prompt (>>>). The result of each statement is displayed
immediately after pressing Enter.
Characteristics: - Useful for testing small code snippets quickly. - Each line is exe-
cuted immediately; no need to save a file. - Good for learning, debugging, and exper-
imenting. - The interpreter is started by typing python or python3 in the command
line/terminal.
Example (Interactive Mode):
>>> a = 10
>>> b = 20
>>> c = a + b
>>> print(c)
30
>>> 5 * 6
30
Here, each line is typed and the output (30) is shown immediately after execution.
2. Script Mode
In script mode, a set of Python statements are written together in a file with a .py
extension, and the entire file is executed at once using the Python interpreter.
5
Characteristics: - Used for writing complete programs. - The file can be saved,
edited, and reused. - Suitable for large, complex, and reusable programs. - Executed
using the command: python [Link]
Example (Script Mode) - File: [Link]
# This program adds two numbers
a = 10
b = 20
c = a + b
print("The sum is:", c)
Execution:
$ python [Link]
The sum is: 30
Difference between Interactive and Script Mode:
Interactive Mode Script Mode
Executes statement by statement Executes the whole program at
once
Output shown immediately for each line Output shown after full execution
Not saved permanently Saved as a .py file for reuse
Best for testing small snippets Best for developing full
applications
Started using >>> prompt Run using python [Link]
Conclusion: Interactive mode is ideal for quick testing and learning Python concepts,
while script mode is used for developing, saving, and executing complete real-world
programs.
5. Discuss the importance of indentation, comments, and error messages in
Python programs. (12 Marks)
1. Indentation
Indentation refers to the spaces or tabs at the beginning of a line of code. Unlike
many other languages (C, Java) that use braces {} to define blocks of code, Python
uses indentation to define the scope of loops, functions, conditional statements, and
classes.
Importance of Indentation: - It defines the block structure of the program (which
statements belong to a loop, function, or condition). - Improves readability of the
code. - Incorrect indentation causes an IndentationError. - All statements within a
block must be indented at the same level (commonly 4 spaces).
Example:
6
num = 10
if num > 0:
print("Positive number") # indented - part of if block
print("This is also inside if")
print("This is outside if block") # not indented
If indentation is missing or inconsistent:
if num > 0:
print("Positive number") # IndentationError: expected an indented block
2. Comments
Comments are non-executable statements used to explain the code. Python ignores
comments during execution.
Types of Comments: - Single-line comment: starts with # - Multi-line comment:
enclosed within triple quotes ''' ... ''' or """ ... """
Importance of Comments: - Improves code readability and understanding. - Helps
other programmers (and the same programmer later) understand the logic. - Useful
for documentation and debugging (temporarily disabling code). - Does not affect
program execution or performance.
Example:
# This program calculates the square of a number
num = 5 # assigning value to variable num
square = num ** 2 # calculating square using ** operator
print(square) # display the result
"""
This is a multi-line comment
explaining the program's purpose
"""
3. Error Messages
An error message is the information Python displays when something goes wrong
during program execution. Error messages are essential for debugging.
Types of Errors: - Syntax Error: occurs when the code does not follow Python’s
grammar rules. python print("Hello" # SyntaxError: missing closing
parenthesis - Runtime Error (Exception): occurs during execution, e.g., dividing
by zero. python x = 10 / 0 # ZeroDivisionError: division by zero - Logical
Error: the program runs but produces incorrect results (no error message shown,
but output is wrong).
Importance of Error Messages: - They indicate the exact line and type of error,
helping locate the problem quickly. - Reduce debugging time. - Help programmers
understand what went wrong and how to fix it. - Encourage writing correct and robust
programs.
Example:
7
>>> print(10/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
Conclusion: Indentation defines program structure, comments improve readability
and documentation, and error messages assist in identifying and correcting mistakes
- together these make Python programs well-organized, understandable, and easier
to debug.
6. Write a Python program using built-in functions and demonstrate import-
ing from packages. (12 Marks)
Concept:
Python provides many built-in functions (such as print(), input(), len(), type(),
max(), min(), sum(), abs(), round(), pow(), sorted()) that are readily available with-
out any import.
In addition, Python has a large standard library organized into packages/modules
(such as math, random, statistics, datetime). These must be imported before use
with the import statement.
Ways of Importing:
import math # import entire module
from math import sqrt, pi # import specific functions
import random as rd # import with alias
Python Program:
# Demonstration of built-in functions
numbers = [12, 45, 7, 23, 56, 9]
print("List of numbers:", numbers)
print("Length of list (len):", len(numbers))
print("Maximum value (max):", max(numbers))
print("Minimum value (min):", min(numbers))
print("Sum of values (sum):", sum(numbers))
print("Sorted list (sorted):", sorted(numbers))
print("Type of numbers (type):", type(numbers))
print("Absolute value of -15 (abs):", abs(-15))
print("Rounded value of 7.567 (round):", round(7.567, 2))
print("Power 2^5 (pow):", pow(2, 5))
# Demonstration of importing from packages
import math
print("\nValue of pi ([Link]):", [Link])
print("Square root of 64 ([Link]):", [Link](64))
print("Factorial of 5 ([Link]):", [Link](5))
8
from random import randint
print("\nRandom number between 1 and 100:", randint(1, 100))
import statistics as st
data = [10, 20, 30, 40, 50]
print("\nMean of data ([Link]):", [Link](data))
print("Median of data ([Link]):", [Link](data))
Sample Output:
List of numbers: [12, 45, 7, 23, 56, 9]
Length of list (len): 6
Maximum value (max): 56
Minimum value (min): 7
Sum of values (sum): 152
Sorted list (sorted): [7, 9, 12, 23, 45, 56]
Type of numbers (type): <class 'list'>
Absolute value of -15 (abs): 15
Rounded value of 7.567 (round): 7.57
Power 2^5 (pow): 32
Value of pi ([Link]): 3.141592653589793
Square root of 64 ([Link]): 8.0
Factorial of 5 ([Link]): 120
Random number between 1 and 100: 47
Mean of data ([Link]): 30
Median of data ([Link]): 30
Explanation: - Functions like len(), max(), min(), sum(), sorted(), type(), abs(),
round(), and pow() are built-in functions, available directly without import. - The
math, random, and statistics modules are part of Python’s standard library and must
be imported before their functions (sqrt, pi, factorial, randint, mean, median) can
be used. - import module_name, from module import function_name, and import
module as alias are the three common ways of importing from packages.
End of Unit I - Part B Questions and Answers