Unit 1 – Computation Thinking & Problem Solving
Write an algorithm to find smallest among three numbers.
1. Ans: step1: Start
Step2: Read a,b,c
Step3: if(a<b)&&(a<c)then
Print “a is small”
Step4: Else if(b<c)then
Print “b is small”
Step5: Else
Print “c is small”
Which is better iteration or recursion? J us t i fy your answer.
2. Ans: Iteration: is generally better for performance and efficiency, using less memory and faster execution.
Recursion: is better suited for problems with naturally recursive structures (e.g., tree traversal) and can lead to
simpler, more readable code in such cases.
State t he qualit ies of a good algorithm.
3.
Ans : Correctness:
Efficiency
Clarity
Finiteness.
Generality
Enumerate the strategies inv olved in deve loping algorit hm.
4. Ans : The strategies involved in developing an algorithm include:
Problem Definition: Clearly understand and define the problem that needs to be solved, specifying inputs,
outputs, and any constraints.
Decomposition: Break the problem into smaller, manageable subproblems or steps, making it easier to devise a
solution.
Algorithm Design: Develop the step-by-step procedure for solving the problem, ensuring correctness, efficiency,
and clarity.
Optimization: Refine the algorithm to improve its performance in terms of time and space complexity, aiming for
efficiency without sacrificing correctness.
Testing and Validation: Test the algorithm with different inputs, including edge cases, to ensure it works as
expected and handles all possible scenarios
Write an algorithm to accept two numbers, compute the sum and print the result.
5.
Ans:Algorithm: Compute and Print the Sum of Two Numbers
1. Start
2. Input: Accept two numbers, num1 and num2.
3. Process: Calculate the sum of the two numbers, sum = num1 + num2.
4. Output: Print the value of sum.
5. End
Define an iterat ive statement.
6. A n s : An iterative statement is a programming construct that repeats a block of code multiple times until a condition is met
or for a specified number of iterations. Examples include for loops and while loops
How does flow of control work?
7. Ans: The flow of control in Python determines the order in which statements are executed in a program. It includes:
1. Sequential Flow: Executes statements one after another in order.
2. Decision-Making: Uses conditional statements like if, elif, and else to branch the flow.
3. Loops: Repeats a block of code using for or while loops.
4. Function Calls: Transfers control to functions and returns after execution.
Explain Towers of Hanoi problem.
8. Ans: The Towers of Hanoi problem is a mathematical puzzle involving three rods and n disks of different sizes. The goal is to
move all disks from the source rod to the destination rod, following these rules:
1. Only one disk can be moved at a time.
2. A disk can only be placed on top of a larger disk or an empty rod.
3. An auxiliary rod can be used for intermediate moves.
What is an algorithm ?
9. Ans: An algorithm is a step-by-step procedure or set of rules for solving a problem or performing a task. It consists of a finite
sequence of well-defined instructions that lead to a solution.
Example:
A simple algorithm to add two numbers:
1. Start
2. Input two numbers, a and b.
3. Calculate the sum: sum = a + b.
4. Output the sum.
5. End
Distinguish between algorithm and pogram.
10. Ans: An algorithm is a ste p-by-step procedure to solve a problem, independent of any programming language.
A program is an implementation of one or more algorithms written in a programming language to perform a specific
task.
Example: An algorithm sorts numbers; a program writes the code to actually sort them.
Write an algorithm to find the minimum number in a given list of numbers.
11. Ans: Algorithm to Find the Minimum Number in a Given List of Numbers:
1. Start.
2. Input: A list of numbers.
3. Set the first number in the list as the minimum.
4. For each number in the list (starting from the second element):
o If the number is smaller than the current minimum, update the minimum to this number.
5. Output the minimum number.
6. End.
Unit – 2 Data, Expressions, Statements
L i s t a ny f o ur b u i lt i n d at a t y pe s i n P yt ho n .
1. A n s: i) int – Integer type, e.g., 42
ii) float – Floating-point number, e.g., 3.14
iii) str – String type, e.g., "hello"
iv) list – List type, e.g., [1, 2, 3]
2. H ow do you ass ign a value t o a t uple in Pyt hon?
Ans: * In Python, you assign values to a tuple when creating it.
* e.g., my_tuple = (1, 2, 3).
* Since tuples are immutable, you cannot change values once assigned, but you can create a new tuple if needed.
3. What are the rules for writing an identifier?
Ans: The rules for writing an identifier in Python are:
1. Start with a Letter or Underscore: An identifier must begin with a letter (a-z, A-Z) or an underscore (_). It cannot
start with a number.
2. Contain Only Letters, Digits, and Underscores: After the first character, an identifier can contain letters, digits (0-
9), and underscores (_).
3. No Reserved Keywords: Identifiers cannot be any of Python's reserved keywords (e.g., if, else, for, etc.).
4. Case-Sensitive: Identifiers are case-sensitive, meaning variable, Variable, and VARIABLE are considered different
identifiers.
5. No Special Characters: Identifiers cannot contain special characters such as @, #, &, etc
Mention the types of arguments in python .
4.
Ans: Positional Arguments
Keyword Arguments
Default Arguments
Variable Arguments
Are comments executable statements in a Python program? How comments are included in a Python program?
5. Ans: No, comments are not executable statements in Python. They are ignored by the interpreter and used to explain code.
Single-line comments start with #, while multi-line comments use triple quotes (''' or """).
Write a snippet to display 'Hello World" in python interpreter.
6. Ans: print("Hello World")
This code uses the print() function to display "Hello World" in the Python interpreter.
7. Name the four types of scalar objects Python has.
Ans: The four types of scalar objects in Python are:
1. Integer (int) - Represents whole numbers.
2. Floating-point number (float) - Represents real numbers with decimals.
3. String (str) - Represents a sequence of characters.
4. Boolean (bool) - Represents True or False values.
8. Write a Python program to accept two numbers, multiply them and print the result.
Ans: Here is a Python program to accept two numbers, multiply them, and print the result:
# Accept two numbers from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Multiply the numbers
result = num1 * num2
# Print the result
print("The result of multiplication is:", result)
9. Write a Python program to accept two numbers, find the greatest and print the result.
Ans: Here is a Python program to accept two numbers, find the greatest, and print the result:
# Accept two numbers from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Find the greatest number
if num1 > num2:
greatest = num1
else:
greatest = num2
# Print the result
print("The greatest number is:", greatest)
10. What are keywords? Give examples.
Ans: Keywords are reserved words in a programming language that have special meanings and cannot be used as
identifiers (variable names, function names, etc.). They are fundamental to the syntax and structure of the language.
Examples of Python Keywords:
if
else
while
for
return
def
import
try
except
class
These keywords help define the flow of control and structure in Python programs.
11. State the reasons to divide programs into functions
Ans: Dividing programs into functions has several advantages:
1. Modularity: Functions allow breaking down a program into smaller, manageable parts, making it easier to develop,
test, and maintain.
2. Reusability: Functions can be reused across different parts of the program or in different projects, saving time and
effort.
3. Code Readability: Using functions makes the program more readable by providing a clear structure and avoiding
repetition of code.
4. Debugging and Testing: Functions can be tested and debugged independently, making it easier to identify and fix
issues.
5. Abstraction: Functions hide the implementation details and allow users to focus on the overall structure and logic.
6. Separation of Concerns: Different tasks are handled in separate functions, making the code cleaner and easier to
understand.
Unit – 3 Control Flow, Functions, Strings
What are t he purp os e s of pas s s t at e me nt in Pyt hon ?
1.
An s: T he pass statement in Python is used as a placeholder in empty code blocks, allowing the code to run without errors.
It's useful when logic is incomplete or will be implemented later.
What. is Linear Search?
2. Ans: Linear search is a simple algorithm that checks each element in a list one by one until the target value is found or the
end of the list is reached. It operates with a time complexity of O(n), where n is the number of elements.
Compare return value and composition.
3. A n s : R eturn value is the value that a function outputs when it finishes execution, allowing data to be sent back to the
caller.
Composition refers to combining multiple functions or objects to build more complex functionality, where one function calls
another as part of its process.
Define string immutability.
4.
Ans: String immutability means that once a string is created in Python, its value cannot be changed or modified. Any
operation that alters a string results in the creation of a new string object, rather than modifying the original.
Write a python program to Count Words in a s entence using spilt 0 function.
5.
Ans: sentence = input("Enter a sentence: ")
words = sentence.split()
word_count = len(words)
print("Number of words in the sentence:", word_count)
Name the two types of iterative statements supported by Python.
6.
Ans:The two types of iterative statements supported by Python are:
1. for loop: Iterates over a sequence (like a list, tuple, string, or range).
2. while loop: Repeats a block of code as long as a specified condition is True
D e fi ne a re curs iv e f un ct io n
7.
A n s: A recursive function is a function that calls itself to solve a problem by breaking it into smaller sub-problems. It must
have a base case to stop the recursion and prevent infinite calls.
Example:
def factorial(n):
if n == 0: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive case
Illustrate the use of * and + operators in string with example
8.
Ans:
1. * Operator: Repeats a string multiple times.
Example:
2. print("Hi" * 3) # Output: HiHiHi
3. + Operator: Concatenates (joins) two strings.
Example:
4. print("Hello" + " World") # Output: Hello World
Comment with an example on the use of local and global variable with the same identifier name.
9. Ans: If a local and a global variable share the same name, the local variable takes precedence within the function scope. The
global variable remains unaffected outside the function.
Example:
x = 10 # Global variable
def my_function():
x = 5 # Local variable
print("Local x:", x)
my_function()
print("Global x:", x)
Output:
Local x: 5
Global x: 10
Here, x inside the function is local, and the global x remains unchanged.
Define Fruitful Function.
10. Ans: A fruitful function is a function that returns a value after performing its task. The returned value can be stored in a
variable or used in further computations.
Example:
def add(a, b):
return a + b # Returns the sum
result = add(3, 5) # Fruitful function call
print(result) # Output: 8
Relate String and List
11.
Ans: Strings and lists in Python are both sequences of elements and share similar behaviors:
1. Indexing and Slicing: Both allow accessing elements using indices and slicing.
Example:
2. s = "hello"
3. lst = [1, 2, 3]
4. print(s[1], lst[1]) # Output: e 2
5. Iterability: Both can be looped through using a for loop.
Example:
6. for char in "abc": print(char) # Iterates over a string
7. for num in [1, 2, 3]: print(num) # Iterates over a list
However, strings are immutable, while lists are mutable.
Present the flow of execution for a while statement.
12. Ans: The flow of execution for a while statement in Python is as follows:
1. Check the Condition: The while loop first checks the condition specified.
2. Condition True: If the condition evaluates to True, the block of code inside the while loop is executed.
3. Reevaluate the Condition: After executing the code block, the condition is checked again.
4. Repeat or Exit:
o If the condition is still True, the loop repeats (steps 2 and 3).
o If the condition is False, the loop terminates and the program continues with the next statement after the
loop.
Example:
count = 0
while count < 5:
print(count)
count += 1 # Increment the counter
Flow:
The condition count < 5 is checked.
If True, the loop prints the value of count and increments it.
The process repeats until count becomes 5, causing the loop to exit.
Define recursion with an example.
13.
Ans: Recursion is a programming technique where a function calls itself in order to solve a problem. The function typically
has a base case that terminates the recursive calls.
Example:
A simple recursive function to calculate the factorial of a number:
def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
# Recursive case
else:
return n * factorial(n - 1)
# Example usage
result = factorial(5)
print(result) # Output: 120
Explanation:
The factorial function calls itself with a smaller value of n until it reaches the base case (n == 0 or n == 1).
The factorial of 5 is calculated as 5 * 4 * 3 * 2 * 1 = 120.
Unit - 4 Lists, Tuples, Dictionaries
Give examples for mutable and immutable objects.
1. Ans: Mutable objects: Examples include lists (list = [1, 2, 3]) and dictionaries (dict = {"a": 1}).
Immutable objects: Examples include strings (str = "hello") and tuples (tuple = (1, 2, 3)).
What is purpose of dictionary in Python?
2.
Ans: The purpose of a dictionary in Python is to store key-value pairs, allowing efficient data retrieval based on unique
keys. It's useful for fast lookups, modifications, and organization of data in a structured way.
Define cloning in list.
3. Ans: Cloning a list in Python refers to creating a copy of an existing list, so that changes to the new list do not affect the
original list. This can be done using methods like slicing (list_copy = original_list[:]), the copy() method (list_copy =
original_list.copy()), or the list() constructor (list_copy = list(original_list)).
W h a t is t h e be n e f i t o f us i n g t u p l e a s s i g n me n t i n p yt h o n ?
4. Ans: The benefit of using tuple assignment in Python is that it allows for simultaneous assignment of multiple variables in a
single line, making the code more concise and readable. It can also be used to swap values between variables easily without
the need for a temporary variable.
Example:
python
Copy code
a, b = 5, 10 # Simultaneous assignment
print(a, b) # Output: 5 10
# Swapping values
a, b = b, a
print(a, b) # Output: 10 5
In Python, how the values stored in a list are accessed? Should the elements of a list be of the same data type?
5.
Ans: In Python, the values stored in a list are accessed using indexing. The index starts at 0 for the first element. Example:
my_list[0].
The elements of a list do not have to be of the same data type. A list can contain different data types, such as integers,
strings, and floats. Example: [10, "hello", 3.14, True].
How Python's dictionaries store data? Give example.
6.
Ans: Python's dictionaries store data as key-value pairs, where each key is unique and maps to a corresponding value.
Example: my_dict = {"name": "John", "age": 30}
What is a tuple ? How literals of type tuple are written ? Give example.
7.
Ans: A tuple is an immutable (unchangeable) ordered collection of elements in Python. It can hold multiple items of
different data types.
Tuple Literals:
Tuples are written by enclosing elements in parentheses () and separating them by commas.
Example:
my_tuple = (1, "apple", 3.14, True)
In this example, my_tuple is a tuple containing an integer, a string, a float, and a boolean.
What is a list ? How lists differ from tuples ?
8.
Ans: A list is a mutable (modifiable) ordered collection of elements in Python. It can store items of different data types and
allows operations like appending, removing, and modifying elements.
Differences between Lists and Tuples:
1. Mutability:
o List: Mutable, meaning elements can be modified after creation.
o Tuple: Immutable, meaning once created, its elements cannot be changed.
2. Syntax:
o List: Defined using square brackets [].
o Tuple: Defined using parentheses ().
3. Performance:
o List: Slower than tuples due to its mutability.
o Tuple: Faster, as they are immutable.
Example:
# List
my_list = [1, 2, 3]
# Tuple
my_tuple = (1, 2, 3)
How to slice a list in Python ?
9. Ans: In Python, you can slice a list using the slice notation: list[start:stop:step].
start: The index to start slicing (inclusive).
stop: The index to end slicing (exclusive).
step: The interval between indices.
Example:
my_list = [10, 20, 30, 40, 50, 60]
# Slice from index 1 to 4 (excluding index 4)
sliced_list = my_list[1:4]
print(sliced_list) # Output: [20, 30, 40]
# Slice with a step of 2
sliced_list = my_list[::2]
print(sliced_list) # Output: [10, 30, 50]
You can also use negative indices to slice from the end of the list.
Give a:function that can take a value and return the first key mapping to that value in a dictionary
10. Ans: Here is a Python function that takes a value and returns the first key that maps to that value in a dictionary.
def get_key_by_value(d, value):
# Loop through dictionary items
for key, val in d.items():
if val == value:
return key # Return the first key with the matching value
return None # Return None if value not found
# Example usage
my_dict = {'a': 10, 'b': 20, 'c': 10}
result = get_key_by_value(my_dict, 10)
print(result) # Output: 'a' (first key with value 10)
Explanation:
The function iterates through the dictionary using d.items() to access each key-value pair.
It checks if the value matches the target value and returns the corresponding key.
If no match is found, it returns None.
Let list ['a ' , ' h ' ' c ' 'd, 'e', T]. Find the following
11.
(a) List [1:31
(b) 4:4]
(c) t[3:].
Ans: (a) t[1:3]
Extracts elements from index 1 up to (but not including) index 3.
Result: ['h', 'c']
(b) t[4:4]
Extracts elements starting at index 4 and stopping at index 4. Since start and stop indices are the same, it returns an empty
list.
Result: []
(c) t[3:]
Extracts elements from index 3 to the end of the list.
Result: ['d', 'e', 'T']
Unit – 5 Files, Modules, Packages
L i s t a n y f o u r f i l e o pe r at i o n s .
1.
Ans: open() – To open a file for reading, writing, or appending.
read() – To read the contents of a file.
write() – To write data to a file.
close() – To close an open file.
How do you delete a file in Python?
2. Ans: In Python, you can delete a file using the os.remove() method from the os module.
Example:
python
Copy code
import os
# Specify the file path
file_path = 'example.txt'
# Delete the file
os.remove(file_path)
print(f"{file_path} has been deleted.")
This will remove the specified file from the filesystem. If the file does not exist, it will raise a FileNotFoundError, so you may
want to handle this using a try-except block for better error management.
How do you use command line arguments to give input to the program?
3. Ans: In Python, you can use the sys.argv list from the sys module to access command-line arguments provided when running
the program.
Steps:
1. Import the sys module.
2. Use sys.argv, where sys.argv[0] is the script name and sys.argv[1:] contains the actual command-line arguments.
Example:
python
Copy code
import sys
# Access command-line arguments
if len(sys.argv) > 1:
print("Command-line arguments:", sys.argv[1:])
else:
print("No command-line arguments provided.")
Running the Program:
bash
Copy code
python script.py arg1 arg2 arg3
Output:
arduino
Copy code
Command-line arguments: ['arg1', 'arg2', 'arg3']
In this example, sys.argv[1], sys.argv[2], etc., will give you access to each argument passed to the program
Write the syntax for opening a file to write in binary mode.
4. Ans: The syntax for opening a file to write in binary mode in Python is:
file = open("filename", "wb")
Here:
"wb" stands for write in binary mode.
What are the different modules in Python?
5. Ans: Python has a wide range of modules, which are libraries that provide additional functionality. Some common types
include:
1. Standard Library Modules: Built-in modules like math, os, sys, datetime.
2. Third-party Modules: External modules like numpy, pandas, requests, flask.
How does try and execute work?
6. Ans: In Python, the try block is used to test code for errors, and the corresponding except block is used to handle
exceptions if they occur.
How it Works:
1. Code in the try block is executed.
2. If no error occurs, the except block is skipped.
3. If an error occurs, the control jumps to the except block, and the exception is handled.
Example:
try:
result = 10 / 0 # Error occurs here (division by zero)
except ZeroDivisionError:
print("Cannot divide by zero.")
Output:
Cannot divide by zero.
The program continues execution without crashing.
How do you handle the exception inside a program when you try to open a non-existent file?
7. Ans: To handle the exception for a non-existent file, use a try-except block to catch the FileNotFoundError.
Example:
try:
file = open("non_existent_file.txt", "r")
except FileNotFoundError:
print("File not found. Please check the file name or path.")
Output (if the file doesn't exist):
File not found. Please check the file name or path.
This prevents the program from crashing and allows proper error handling.
Write a Python script to display the current date and time.
8. Ans: Here is a Python script to display the current date and time:
from datetime import datetime
# Get the current date and time
current_datetime = datetime.now()
# Display the current date and time
print("Current date and time:", current_datetime)
This script uses the datetime module to fetch and display the current date and time.
Write a note on modular design.
9. Ans: Modular design is a software design approach that divides a system into smaller, self-contained units or modules. Each
module is responsible for a specific functionality and can be developed, tested, and maintained independently.
Advantages of Modular Design:
1. Reusability: Modules can be reused in different parts of the program or in other projects.
2. Maintainability: Easier to update or fix bugs in individual modules without affecting the entire system.
3. Scalability: Modules can be added or removed with minimal disruption to the overall system.
4. Collaboration: Multiple developers can work on different modules simultaneously, speeding up development.
Example:
In Python, each module can be a separate .py file. For instance, a math_operations.py module might handle mathematical
calculations, while a file_handler.py module manages file operations.
What is a module? Give example.
10.
Ans: A module in Python is a file containing Python code that can define functions, variables, and classes. It allows you to
organize and reuse code.
Example:
# my_module.py
def greet(name):
return f"Hello, {name}!"
# main.py
import my_module
print(my_module.greet("Alice")) # Output: Hello, Alice!
Find the syntax error in the code given :
11.
while True print (`Hello world')
Ans:
The syntax error in the given code is due to the missing colon (:) at the end of the while statement, and incorrect use of
backticks for printing.
Corrected Code:
while True:
print("Hello world")
Explanation:
The while loop requires a colon (:) at the end of the condition.
The print function should use double or single quotes (" " or ' ') instead of backticks (` `), which are not valid for
string literals in Python.