0% found this document useful (0 votes)
60 views18 pages

S1 Python Module - 1 Question & Answers For Students

The document provides a comprehensive overview of algorithmic thinking and Python programming, including problem-solving strategies, coding examples, and explanations of Python concepts. It covers various topics such as well-defined vs. ill-defined problems, data types, error correction, and the importance of testing and evaluation in programming. Additionally, it includes practical exercises and examples to illustrate key programming principles.

Uploaded by

arjiths17
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)
60 views18 pages

S1 Python Module - 1 Question & Answers For Students

The document provides a comprehensive overview of algorithmic thinking and Python programming, including problem-solving strategies, coding examples, and explanations of Python concepts. It covers various topics such as well-defined vs. ill-defined problems, data types, error correction, and the importance of testing and evaluation in programming. Additionally, it includes practical exercises and examples to illustrate key programming principles.

Uploaded by

arjiths17
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/ 18

ALGORITHMIC THINKING WITH PYTHON

MODULE -1
PROBLEM SOLVING STRATEGIES & ESSENTIALS OF PYTHON
PROGRAMMING

3-MARK QUESTIONS & ANSWERS

Q#1: Explain well-defined & ill-defined problems.

Answer:
A well-defined problem is one where all aspects—such as initial state, goal state, and possible
operations—are clearly specified. The solution path is structured and can be tested for correctness.
Example: Solving a mathematical equation like x + 3 = 7.

An ill-defined problem lacks clear goals or procedures. The solution may vary based on interpretation
or creativity.
Example: Writing an essay or designing a user interface.

Q#2: Create a Python program that accepts a number from the user and prints square and square root of
the number using math.sqrt().

Answer:

import math
num = float(input("Enter a number: "))
print("Square:", num ** 2)
print("Square Root:", math.sqrt(num))

Explanation:
The program imports the math module, accepts a number from the user, computes its square using
exponentiation, and computes the square root using math.sqrt().

Notes Prepared By: Prof. Filson P Rajan


St. Thomas College of Engineering & Technology, Kozhuvalloor
ALGORITHMIC THINKING WITH PYTHON

Q#3: Differentiate between numeric and string data types in Python with one example each.

Answer:

• Numeric data types: Used to store numbers. Examples include int, float, and complex.
Example: x = 10, y = 3.5
• String data type: Used to store a sequence of characters enclosed in quotes.
Example: name = "Python"

Difference:
Numeric data supports arithmetic operations; strings support text manipulation.

Q#4: Identify and correct the error(s) in the following code:

x = 5
y == 10
print(x+y)

Answer:
Error:
The line y == 10 uses the equality operator instead of assignment.

Corrected Code:

x = 5
y = 10
print(x + y)

Q#5: Create a Python program that calculates the square root and factorial of a number entered by the
user using the math module.

Answer:

import math
n = int(input("Enter a number: "))
print("Square Root:", math.sqrt(n))
print("Factorial:", math.factorial(n))

Notes Prepared By: Prof. Filson P Rajan


St. Thomas College of Engineering & Technology, Kozhuvalloor
ALGORITHMIC THINKING WITH PYTHON

Q#6: Show with an example how operator precedence affects the result of the expression 10 + 5 * 2.

Answer:
According to Python operator precedence, multiplication (*) is performed before addition (+).
So:
10 + 5 * 2 = 10 + (5 * 2) = 10 + 10 = 20

If evaluated left to right without precedence, the incorrect result would be (10 + 5) * 2 = 30.

Q#7: Debug the following code:

import Math
print(Math.sqrt(25))

Answer:
Error: Module name is case-sensitive; Math should be lowercase.

Corrected Code:

import math
print(math.sqrt(25))

Q#8: Identify and correct the error(s):

x = input("Enter a number: ")


y = input("Enter another number: ")
print("Sum is:", x + y)

Answer:
Error: Inputs are taken as strings; addition performs concatenation.
Correction: Convert inputs to integers.

x = int(input("Enter a number: "))


y = int(input("Enter another number: "))
print("Sum is:", x + y)

Notes Prepared By: Prof. Filson P Rajan


St. Thomas College of Engineering & Technology, Kozhuvalloor
ALGORITHMIC THINKING WITH PYTHON

Q#9: Differentiate Keywords & Identifiers/Variables in Python.


Answer:

• Keywords:
These are reserved words that have predefined meanings in Python. They cannot be used as
variable names.
Example: if, while, for, def, class.
• Identifiers/Variables:
These are user-defined names used to identify variables, functions, or classes.
Example: age, total_marks, sum_value.

Difference:

Aspect Keywords Identifiers


Defined by Python language Programmer

Count Fixed Unlimited


Example for, if num, total

Q#10: Identify the output of the following Python code snippet.

a = "Lets study Python"


print(a.upper())
print(a.title())

Answer:
Explanation:

• a.upper() converts all letters in the string to uppercase.


• a.title() converts the first letter of each word to uppercase.

Output:

LETS STUDY PYTHON


Lets Study Python

Q#11: Create a Python program that calculates the ceil and floor of a number entered by the user using
the math module.
Answer:

import math
num = float(input("Enter a number: "))
print("Ceil value:", math.ceil(num))
print("Floor value:", math.floor(num))

Notes Prepared By: Prof. Filson P Rajan


St. Thomas College of Engineering & Technology, Kozhuvalloor
ALGORITHMIC THINKING WITH PYTHON

Explanation:

• math.ceil() returns the smallest integer greater than or equal to the number.
• math.floor() returns the largest integer less than or equal to the number.

Q#12: Identify the output of the following code snippet.

import math
print(math.pow(5,2))
print(math.trunc(4.5))

Answer:

• math.pow(5, 2) returns 25.0 (float).


• math.trunc(4.5) returns 4 (removes decimal part without rounding).

Output:

25.0
4

Q#13: Identify and correct the errors in the following code snippet:

import math
print(math.squareroot(25))
print(math.floor(2.5)
print math.ceil(7.1))

Answer:
Errors:

1. Function name should be sqrt, not squareroot.


2. Missing closing parenthesis in the second print() statement.
3. The third print statement lacks parentheses (Python 3 syntax).

Corrected Code:

import math
print(math.sqrt(25))
print(math.floor(2.5))
print(math.ceil(7.1))

Notes Prepared By: Prof. Filson P Rajan


St. Thomas College of Engineering & Technology, Kozhuvalloor
ALGORITHMIC THINKING WITH PYTHON

4-MARK QUESTIONS & ANSWERS

Q#1: Explain the rules for creating an Identifier/Variable in Python with examples.

Answer:
Identifiers are names given to variables, functions, or classes in Python.
The following are the rules for naming identifiers:

1. Must begin with a letter (A–Z, a–z) or an underscore (_).


2. Cannot begin with a digit.
3. Can contain letters, digits, and underscores.
4. Case-sensitive (Age ≠ age).
5. Keywords cannot be used as identifiers.
6. No special characters (@, #, $, etc.) are allowed.

Examples:
Valid: name, _age, mark1
Invalid: 1name, for, total@sum

Q#2: Correct the following code that calculates the area of a circle:

import math
r = float(input(“Enter radius of the circle: “)
area = math.pi * r ^ 2
print("Area:", Area)

Answer:
Errors identified:

1. Missing closing parenthesis in input()


2. ^ is bitwise XOR, should use ** for power
3. Variable name Area should be lowercase
4. Missing double quotes consistency

Corrected Code:

import math
r = float(input("Enter radius of the circle: "))
area = math.pi * (r ** 2)
print("Area:", area)

Notes Prepared By: Prof. Filson P Rajan


St. Thomas College of Engineering & Technology, Kozhuvalloor
ALGORITHMIC THINKING WITH PYTHON

Q#3: “Formulating a model correctly reduces errors in later stages.” Justify this statement with an
example problem of your choice.

Answer:
Formulating a model means clearly defining the problem, inputs, outputs, and processing steps
before coding.
A correct model helps programmers avoid logical and design errors later.

Example:
For a program to calculate simple interest, the model should specify:

• Input: Principal (P), Rate (R), Time (T)


• Process: Apply formula SI = (P * R * T) / 100
• Output: Display Simple Interest

If we define this model beforehand, it prevents errors like incorrect formulas or missing variables.

Q#4: A kid wants to finish the game “Tower of Hanoi.” Show how Means–Ends Analysis can be used
to set sub-goals and reach the final target.

Answer:
Means–Ends Analysis (MEA) is a problem-solving strategy that reduces the difference between the
current and goal states by setting sub-goals.

For Tower of Hanoi:

• Goal: Move all disks from Source → Destination peg.


• Sub-goals:
1. Move (n−1) disks from Source → Auxiliary peg.
2. Move 1 largest disk from Source → Destination peg.
3. Move (n−1) disks from Auxiliary → Destination peg.

Each sub-goal brings the system closer to the final state.

Notes Prepared By: Prof. Filson P Rajan


St. Thomas College of Engineering & Technology, Kozhuvalloor
ALGORITHMIC THINKING WITH PYTHON

Q#5: Differentiate Trial and Error method or Backtracking method with example.

Answer:

Aspect Trial & Error Backtracking

Repeated attempts until a correct Tries partial solutions; if failure, goes back to
Definition
solution is found. previous step.

Approach Random or sequential guessing. Systematic exploration using recursion.

Guessing a password by trying multiple


Example Solving Sudoku or N-Queens problem.
options.

Less efficient, no memory of previous


Efficiency More efficient, avoids repeating failed paths.
attempts.

Q#6: You need to design a program to calculate simple interest. Demonstrate how you would move step
by step through the problem-solving process (from understanding to evaluation).
Answer:
Step 1 – Problem Understanding:
Identify what to calculate — Simple Interest (SI).

Step 2 – Problem Analysis:


Inputs: Principal (P), Rate (R), Time (T)
Formula: SI = (P * R * T) / 100

Step 3 – Algorithm Design:

1. Read P, R, T
2. Compute SI
3. Display SI

Step 4 – Implementation:

P = float(input("Enter principal: "))


R = float(input("Enter rate: "))
T = float(input("Enter time: "))
SI = (P * R * T) / 100
print("Simple Interest:", SI)

Step 5 – Testing & Evaluation:


Check with sample input: P=1000, R=5, T=2 → SI=100.
Notes Prepared By: Prof. Filson P Rajan
St. Thomas College of Engineering & Technology, Kozhuvalloor
ALGORITHMIC THINKING WITH PYTHON

Q#7: Describe the role of a computer as a model of computation in solving real-world problems with an
example.

Answer:
A computer as a model of computation refers to its ability to simulate logical processes for solving
problems using algorithms.
It accepts input, processes it using defined rules, and produces output efficiently.

Example:
A weather forecasting system uses models and algorithms to compute temperature and rainfall
predictions based on input data.

Q#8: “Testing and evaluating a program are equally important as developing it.” Justify this statement
with an example.

Answer:
Testing ensures the program works as intended, while evaluation checks its performance and usability.
Without testing, hidden bugs remain; without evaluation, the program may not meet user needs.

Example:
A banking app without proper testing may process incorrect transactions, leading to serious losses.

Hence, testing and evaluation help ensure reliability, accuracy, and efficiency.

Q#9: Create a Python program to swap two numbers using variables.


Answer:
Python allows swapping values of two variables in a single step without using a third variable.

Program:

x = int(input("Enter first number: "))


y = int(input("Enter second number: "))

x, y = y, x

print("After swapping:")
print("x =", x)
print("y =", y)

Notes Prepared By: Prof. Filson P Rajan


St. Thomas College of Engineering & Technology, Kozhuvalloor
ALGORITHMIC THINKING WITH PYTHON

Explanation:
The statement x, y = y, x simultaneously assigns the value of y to x and x to y using tuple
unpacking.

Q#10: Identify and correct the error in this code snippet:

import math
print(math.squareroot(25))
print(math.floor(2.5)
print math.ceil(7.1))

Answer:
Errors found:

1. math.squareroot() should be math.sqrt().


2. Missing closing parenthesis after math.floor(2.5).
3. Python 3 requires parentheses for print().

Corrected Code:

import math
print(math.sqrt(25))
print(math.floor(2.5))
print(math.ceil(7.1))

Q#11: Create a program in Python to take two numbers from the user and print their sum, difference,
product, and quotient.

Answer:

a = float(input("Enter first number: "))


b = float(input("Enter second number: "))

print("Sum =", a + b)
print("Difference =", a - b)
print("Product =", a * b)
print("Quotient =", a / b)

Explanation:
The program reads two numbers and performs basic arithmetic operations.

Notes Prepared By: Prof. Filson P Rajan


St. Thomas College of Engineering & Technology, Kozhuvalloor
ALGORITHMIC THINKING WITH PYTHON

Q#12: Find and correct the error in the following code:

name = input("Enter name: )


age = input("Enter age: ")
print("Your name is " Name " and age is " age)

Answer:
Errors:

1. Missing closing quotation in the first input statement.


2. Variable name Name should be lowercase (name).
3. String concatenation is incorrect.

Corrected Code:

name = input("Enter name: ")


age = input("Enter age: ")
print("Your name is", name, "and age is", age)

Q#13: Explain the significance of comments in Python programming with an example.

Answer:
Comments are used to explain code, improve readability, and help in debugging. Python ignores
comments during execution.

• Single-line comment: Starts with #


• Multi-line comment: Enclosed within triple quotes ''' ''' or """ """

Example:

# This program calculates area


radius = 5
area = 3.14 * radius * radius
print("Area =", area)

Notes Prepared By: Prof. Filson P Rajan


St. Thomas College of Engineering & Technology, Kozhuvalloor
ALGORITHMIC THINKING WITH PYTHON

5 - MARK QUESTIONS & ANSWERS

Q#1: Consider a real-life problem where someone wants to save money to buy a new phone. Explain
how they can use Means–Ends Analysis by setting milestones to achieve this goal.

Answer:
Means–Ends Analysis (MEA) is a problem-solving strategy that reduces the gap between the current
state and goal state by identifying intermediate steps (sub-goals).

Problem:
A person wants to buy a phone worth ₹30,000 but currently has ₹5,000.

Steps using MEA:

1. Current State: ₹5,000 saved.


2. Goal State: ₹30,000 required.
3. Difference: ₹25,000.
4. Sub-goals:
o Save ₹5,000 every month.
o Reduce unnecessary expenses.
o Open a recurring deposit for 5 months.
5. Result: After 5 months, goal achieved.

Conclusion:
MEA helps break a big problem into smaller achievable tasks, making goal attainment systematic and
efficient.

Q#2: Explain various steps involved in the problem-solving process of Python programming with a neat
diagram. Illustrate each step using an appropriate example.

Answer:
The problem-solving process in programming involves the following steps:

1. Problem Definition: Clearly understand the problem to be solved.


Example: Calculate area of a circle.
2. Problem Analysis: Identify inputs, process, and outputs.
o Input: radius
o Process: area = π * r²
o Output: area

Notes Prepared By: Prof. Filson P Rajan


St. Thomas College of Engineering & Technology, Kozhuvalloor
ALGORITHMIC THINKING WITH PYTHON

3. Algorithm Development: Write step-by-step logic for the problem.


1. Read radius
2. Compute area
3. Display area
4. Coding (Implementation): Write the algorithm in Python.
5. import math
6. r = float(input("Enter radius: "))
7. print("Area =", math.pi * r ** 2)
8. Testing & Debugging: Verify results with test data.
9. Documentation & Maintenance: Write comments and maintain the code for future use.

Diagram:

Problem Definition → Analysis → Algorithm → Coding → Testing → Maintenance

Q#3: While writing a Python program, you encounter multiple syntax errors. How can the Trial and
Error strategy help in identifying and fixing the issues?

Answer:
Trial and Error is a problem-solving strategy in which multiple attempts are made until the correct
solution is found.

In Programming:
When syntax or logical errors occur, the programmer modifies and re-runs the code several times until it
executes correctly.

Steps:

1. Identify the error message from the compiler/interpreter.


2. Make small code modifications.
3. Run the program again.
4. Observe results and repeat until output is correct.

Example:

# Error: Missing closing bracket


print("Hello World"

After trying different corrections, the final correct line is:

print("Hello World")

Notes Prepared By: Prof. Filson P Rajan


St. Thomas College of Engineering & Technology, Kozhuvalloor
ALGORITHMIC THINKING WITH PYTHON

Q#4: Consider the problem of finding whether a string is a palindrome. Write the algorithm for solving
this.

Answer:
Algorithm: To check whether a string is a palindrome

1. Start
2. Input a string str1
3. Reverse the string using slicing or loop
4. Compare the original and reversed strings
5. If both are equal,
Print "Palindrome"
Else,
Print "Not Palindrome"
6. Stop

Example:
Input: madam → Reversed: madam → Output: Palindrome

Q#5: You are given the task of building a simple Python calculator app. Explain the algorithm for
creating it.

Answer:
Algorithm: Simple Calculator

1. Start
2. Input two numbers a and b
3. Input operator choice (+, −, *, /)
4. If operator is ‘+’, print a + b
Else if operator is ‘−’, print a − b
Else if operator is ‘*’, print a * b
Else if operator is ‘/’, print a / b
Else, print “Invalid Choice”
5. Stop

Example Input/Output:

Enter a = 10
Enter b = 5
Enter operator = *
Result = 50

Notes Prepared By: Prof. Filson P Rajan


St. Thomas College of Engineering & Technology, Kozhuvalloor
ALGORITHMIC THINKING WITH PYTHON

Q#6: Write down the algorithm for creating a Python program that calculates the total marks, average,
and grade of students.

Answer:
Algorithm: Student Result Processing

1. Start
2. Input marks in 3 subjects: m1, m2, m3
3. Compute Total: total = m1 + m2 + m3
4. Compute Average: avg = total / 3
5. If avg ≥ 90 → Grade = 'A+'
Else if avg ≥ 80 → Grade = 'A'
Else if avg ≥ 70 → Grade = 'B'
Else if avg ≥ 60 → Grade = 'C'
Else → Grade = 'Fail'
6. Display total, average, and grade
7. Stop

Q#7: Differentiate Keywords and Operators (Arithmetic, Relational Operators) in Python with
examples.

Answer:

Aspect Keywords Operators

Predefined reserved words used for Symbols used to perform operations on


Definition
specific functions. values.

Examples if, else, for, while, def +, -, *, /, >, <, ==

Type Used for program control. Used for computations or comparisons.

Usage
if x > 10: sum = a + b
Example

Multiple operator categories: arithmetic,


Count Around 35 keywords in Python.
relational, logical, etc.

Notes Prepared By: Prof. Filson P Rajan


St. Thomas College of Engineering & Technology, Kozhuvalloor
ALGORITHMIC THINKING WITH PYTHON

Q#8: Create a Python program to check whether a given number entered by the user is even or odd.

Answer:

num = int(input("Enter a number: "))

if num % 2 == 0:
print("The number is Even")
else:
print("The number is Odd")

Explanation:
The modulo operator % checks the remainder when dividing the number by 2. If remainder = 0 → even;
else → odd.

Q#9: Find the error and correct it:

a =_int(input(“Enter a number” )
b = int(input(“Enter second number : ))
3Sum =a+b
Print(“The sum of “, a , “ & “, b , “is “, 3Sum)

Answer:
Errors:

1. _int should be int.


2. Missing closing parenthesis.
3. Variable name 3Sum invalid (cannot start with a digit).
4. Print should be lowercase.
5. Inconsistent quotes.

Corrected Code:

a = int(input("Enter a number: "))


b = int(input("Enter second number: "))
sum_ = a + b
print("The sum of", a, "and", b, "is", sum_)

Notes Prepared By: Prof. Filson P Rajan


St. Thomas College of Engineering & Technology, Kozhuvalloor
ALGORITHMIC THINKING WITH PYTHON

Q#10: Create a Python program that declares variables of different data types and prints their type using
type().

Answer:

a = 10 # Integer
b = 3.14 # Float
c = "Python" # String
d = True # Boolean
e = 5 + 2j # Complex

print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))

Output:

<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'complex'>

Q#11: Create a Python program to calculate the area of a circle using the formula πr².

Answer:

import math
r = float(input("Enter radius: "))
area = math.pi * (r ** 2)
print("Area of Circle =", area)

Explanation:
Uses the math module’s pi constant for accurate results and ** for exponentiation.

Notes Prepared By: Prof. Filson P Rajan


St. Thomas College of Engineering & Technology, Kozhuvalloor
ALGORITHMIC THINKING WITH PYTHON

Q#12: Create a Python program to read a student’s name, marks in three subjects, and print their total,
average, and grade.

Answer:

name = input("Enter student name: ")


m1 = float(input("Enter mark 1: "))
m2 = float(input("Enter mark 2: "))
m3 = float(input("Enter mark 3: "))

total = m1 + m2 + m3
avg = total / 3

if avg >= 90:


grade = "A+"
elif avg >= 80:
grade = "A"
elif avg >= 70:
grade = "B"
elif avg >= 60:
grade = "C"
else:
grade = "Fail"

print("Name:", name)
print("Total:", total)
print("Average:", avg)
print("Grade:", grade)

Notes Prepared By: Prof. Filson P Rajan


St. Thomas College of Engineering & Technology, Kozhuvalloor

You might also like