Question Bank for Python_Answerkey
Question Bank for Python_Answerkey
2 marks Questions
UNIT-I: INTRODUCTION
1. What is the history of Python programming language?
python was created by Guido van Rossum in the late 1980s at the
National Research Institute for Mathematics and Computer Science 1
(CWI) in the Netherlands. It was conceived as a successor to the ABC
language and first released in 1991. Its design philosophy emphasizes
code readability with notable use of significant whitespace
2. List four key features of Python.
Readability: Python's syntax is designed to be clean and easy to
understand.
Interpreted: Python code is executed line by line, making debugging
easier.
Dynamically Typed: You don't need to declare the type of a variable.
Extensive Libraries: Python has a large standard library and a vast
ecosystem of third-party packages.
code
point = (10, 20)
x, y = point # x gets 10, y gets 20
print(f"x: {x}, y: {y}")
a, b, c = 1, "hello", True # Assigning multiple values at once
print(f"a: {a}, b: {b}, c: {c}")
15. Write a Python program to exchange the values of two variables.
a=5
b = 10
# Method 1: Using a temporary variable
temp = a
a=b
b = temp
print(f"After exchange (using temp): a = {a}, b = {b}")
#Method 2: Using tuple assignment (more Pythonic)
x=5
y = 10
x, y = y, x
print(f"After exchange (using tuple assignment): x = {x}, y = {y}")
16. Create a program to calculate the distance between two points using
coordinates.
import math
x1 = float(input("Enter x-coordinate of the first point: "))
y1 = float(input("Enter y-coordinate of the first point: "))
x2 = float(input("Enter x-coordinate of the second point: "))
y2 = float(input("Enter y-coordinate of the second point: "))
distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
print(f"The distance between the two points is: {distance}")
17. Compare the use of comments and expressions in a Python program.
Comments are explanatory notes added to the code to make it more
understandable for humans. They are ignored by the Python interpreter.
Comments start with a # and can be single-line or multi-line (using triple
quotes, though these are often used for docstrings).
Expressions are combinations of values, variables, operators, and
function calls that evaluate to a value. They represent computations or
data retrieval that the Python interpreter executes.
In essence, comments are for human readers, while expressions are
instructions for the computer to execute.
18. Analyze how Python’s interactive mode differs from script mode.
Interactive Mode: You type and execute Python code one line (or a
block) at a time. The interpreter reads your input, evaluates it, and prints
the result immediately (REPL: Read-Eval-Print Loop). It's great for quick
testing, exploration, and learning.
Script Mode: You write a complete Python program in one or more files
(with a .py extension). You then execute the entire script using the
Python interpreter (python your_script.py). This is used for
developing larger applications and reusable code.
23. Explain the difference between "while" and "for" loops in Python.
end: The index where the slice ends (exclusive, defaults to the end of the
string if omitted).
my_string = "PythonIsFun"
26. Demonstrate the use of a for loop to print the characters of a string.
text = "Hello"
for char in text:
print(char)
String formatting operations in Python are highly effective for creating dynamic
and readable strings by embedding variables or expressions within string
literals. Python offers several powerful methods:
● %-formatting (older style): While still functional, it's less readable and
prone to errors if the types don't match.
● .format() method: This is a more versatile and readable approach,
allowing you to use positional or keyword arguments for substitution.
● f-strings (formatted string literals - Python 3.6+): This is the most
modern and often the most concise and readable way to format strings.
You can directly embed expressions inside curly braces {} within the
string.
F-strings, in particular, enhance code clarity and reduce verbosity, making string
formatting very effective in Python.
However, for file I/O, it's generally recommended to use the more flexible
.format() method or f-strings for better readability and control.
33. Explain the difference between local and global scope in Python
functions.
Local Scope:
Variables defined inside a function have local scope. They are only accessible
within that specific function. Once the function finishes executing, these
variables are destroyed.
Global Scope:
Variables defined outside of any function have global scope. They are
accessible from anywhere in the program, including inside functions.
However, to modify a global variable from within a function, you need to
explicitly declare it using the global keyword.
You can read data from a file in Python using the open() function to
open the file and then various methods of the file object:
result = square(5)
print(result)
# Output: 25
36. Create a program to write "Hello, File!" to a text file.
try:
with open("my_file.txt", "w") as file:
file.write("Hello, File!\n")
print("Successfully wrote to my_file.txt")
except Exception as e:
print(f"An error occurred: {e}")
37. Compare function composition and recursion with examples.
Function Composition: This involves combining multiple functions to
create a more complex operation. The output of one function becomes the
input of another. It's a way to build functionality step-by-step
def add_two(x):
return x + 2
def multiply_by_three(y):
return y * 3
result = multiply_by_three(add_two(5)) # add_two(5) returns 7, then
multiply_by_three(7) returns 21
print(result)
# Output: 21
Recursion: As defined earlier, a function calls itself to solve a problem
by breaking it down into smaller, self-similar instances
def factorial_recursive(n):
if n == 0:
return 1 # Base case
else:
return n * factorial_recursive(n - 1) # Recursive step
result = factorial_recursive(5)
print(result) # Output: 120
● List: Lists are mutable, meaning you can change their contents after
creation (add, remove, or modify elements). They are defined using
square brackets [].
● Tuple: Tuples are immutable, meaning once created, their contents
cannot be changed. They are defined using parentheses (), although the
parentheses are optional in some contexts.
Lists are typically used for collections of items where you might need to modify
the order or content, while tuples are used for collections of items that should
remain fixed.
.keys(): Returns a view object that displays a list of all the keys in the
dictionary.
.values(): Returns a view object that displays a list of all the values
in the dictionary.
Mutability in Python lists means that you can modify the list object after it has
been created. This includes:
This ability to change the contents of a list in-place makes them a dynamic and
flexible data structure.
# Using the .get() method (safer, returns None if key doesn't exist)
print(student.get("city")) # Output: None
print(student.get("age", "N/A")) # Output: 20 (returns default "N/A" if key
not found)
Lists are used when the order of elements matters and duplicates are allowed,
while sets are used when you need to work with unique elements and perform
set-related operations efficiently
48. Analyze the difference between aliasing and cloning in lists.
Aliasing: When you assign one list to another variable (e.g., list2 =
list1), you are not creating a new list. Instead, both variables refer to
the same list object in memory. Changes made through one alias will
affect the other.
list1 = [1, 2, 3]
list2 = list1 # Aliasing
list2.append(4)
print(list1)
# Output: [1, 2, 3, 4] (list1 is also changed)
Cloning: Cloning creates a completely new list object with the same
elements as the original. Changes to the clone will not affect the original
list. You can clone a list using slicing ([:]) or the copy() method
list1 = [1, 2, 3]
list2 = list1[:] # Cloning using slicing
list3 = list1.copy() # Cloning using the copy() method
list2.append(4)
list3.remove(1)
print(list1) # Output: [1, 2, 3] (original list remains unchanged)
print(list2) # Output: [1, 2, 3, 4]
print(list3) # Output: [2, 3]
49. Assess the usefulness of NumPy over traditional Python lists for
numerical operations.
50. Design a program using Matplotlib to plot a simple line graph with
given data points.
Explanation:
1. Make sure you have the matplotlib library installed. If not, you can
install it using pip:
Bash
python line_graph.py
3 marks Questions:
UNIT-I: INTRODUCTION
1. Outline the history of Python programming language with key
milestones.
Python's journey began in the late 1980s with Guido van Rossum at CWI in the
Netherlands, conceived as a successor to ABC.
● Early 1990s: The first version, Python 0.9.0, was released in 1991.
● 1994: Python 1.0 was released, featuring functional programming tools
like map, filter, and reduce.
● 2000: Python 2.0 introduced list comprehensions and a garbage collection
system. This era saw Python's growing adoption.
● 2008: Python 3.0 (Python 3000 or Py3k) was released, introducing
significant changes aimed at modernizing the language and addressing
design flaws. This led to a period of dual Python 2 and 3 usage.
● 2020: Python 2 officially reached its end-of-life, marking the full
transition to Python 3, which continues to evolve with new features and
improvements in subsequent versions.
2. List and briefly describe three features of Python that make it
popular.
Readability: Python's syntax emphasizes clarity and conciseness, using
significant whitespace for code block definition. This makes it easier to
read, understand, and maintain code, often described as being almost
English-like.
Versatility: Python supports multiple programming paradigms, including
procedural, object-oriented, and functional programming. Its extensive
standard library and 1 vast ecosystem of third-party packages make it
suitable for a wide range of applications, from web development 2 and
data science to scripting and automation.
Large and Supportive Community: Python boasts a vibrant and active
community of developers. This translates to abundant online resources,
tutorials, libraries, and frameworks, making it easier for both beginners
and experienced programmers to find solutions and support.
Single quotes ('...'): Used to enclose single-line strings. Useful when the
string contains double quotes.
print(message)
print(greeting)
Triple quotes ('''...''' or """..."""): Used for multi-line strings or
docstrings (documentation strings used to explain code). They can span
multiple lines without the need for escape characters.
print(poem)
def my_function():
pass
print(my_function. doc )
5. Write a Python program that takes a user’s age as input and prints a
greeting message.
age_str = input("Please enter your age: ")
try:
age = int(age_str)
if age < 18:
print(f"Hello young one! You are {age} years old.")
else:
print(f"Greetings! You are {age} years old.")
except ValueError:
print("Invalid input. Please enter a valid integer for your age.)
6. Demonstrate the use of multi-line statements in Python with a simple
example.
Using multi-line statements improves the readability of your code,
especially when dealing with lengthy lines that would otherwise be
difficult to follow on a single line. Python's flexibility in handling these
structures makes the code cleaner and more maintainable.
# Using a backslash (\) to break a long statement into multiple lines
long_string = "This is a very long string that needs to be broken " \
"into multiple lines for better readability."
print(long_string)
# Implicitly breaking a statement within parentheses ()
result = (10 + 5 - 3 * 2
+ 8 / 4)
print(result)
# Implicitly breaking a statement within square brackets [] (for lists)
my_list = [
"apple",
"banana",
"cherry",
"date"
]
print(my_list)
# Implicitly breaking a statement within curly braces {} (for
dictionaries)
my_info = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
print(my_info)
10. Design a Python program that accepts two strings as input and
concatenates them with a space.
string1 = input("Enter the first string: ")
string2 = input("Enter the second string: ")
concatenated_string = string1 + " " + string2
print("The concatenated string is:", concatenated_string)
Operators with higher precedence are evaluated before operators with lower
precedence. Parentheses can be used to override 1 the default precedence.
Comments in Python are explanatory notes added to the code to make it more
understandable for humans. They are ignored by the Python interpreter and do
not affect the program's execution. Comments are crucial for:
Single-line comments: Start with a hash symbol (#) and continue to the end of
the line.
count = 0
code:
"""
Args:
Returns:
"""
19. Justify the use of type conversion in handling mixed data types in
expressions.
type conversion (or type casting) is essential when you need to perform
operations involving different data types that Python doesn't
automatically handle. Without explicit conversion, you might encounter
TypeError exceptions because certain operations are not defined
between incompatible types
For example, you cannot directly add a string and an integer:
num_str = "10"
num_int = 5
# result = num_str + num_int # This will raise a TypeError
To perform the addition, you need to convert the string to an integer (or
the integer to a string):
result_int = int(num_str) + num_int # Convert string to integer
print(result_int) # Output: 15
result_str = num_str + str(num_int) # Convert integer to string
print(result_str) # Output: 105
20. Design a program to circulate the values of four variables in a
clockwise manner.
def circulate_clockwise(a, b, c, d):
"""Circulates the values of four variables clockwise (a->b, b->c, c->d,
d->a)."""
temp = d
d=c
c=b
b=a
a = temp
return a, b, c, d
Output: 1, 2 (stops at 3)
22. List and briefly explain three in-built string methods in Python.
Answer:
1. lower():
The lower() method converts all characters in a string to lowercase. It’s useful when you
want to make a string case-insensitive.
Example:
text = "Hello"
print(text.lower())
Output: "hello"
2. upper():
The upper() method converts all characters in a string to uppercase. It's commonly used
when you need to make text uniform in all caps.
Example:
text = "hello"
print(text.upper())
Output: "HELLO"
3. strip():
The strip() method removes any leading and trailing whitespace (spaces, tabs, etc.) from a
string. It's helpful when you want to clean up extra spaces from the start or end of a string.
Example:
text = " Hello World "
print(text.strip())
Output: "Hello World"
23. Explain the role of the "else" clause when used with loops in Python.
Answer:
Role of the else Clause with Loops:
In Python, the else clause can be used in both for and while loops. It runs only if the loop
completes normally, meaning without being interrupted by a break statement. If the loop
is stopped by a break, the else block is skipped.
Key Points:
• The else block is executed when the loop finishes all its iterations without encountering
a break.
• It is often used to specify what to do when the loop successfully completes all tasks
(e.g., a search that didn’t find a match).
Example:
for i in range(1, 4):
print(i)
else:
print("Loop completed without interruption")
Output:
1
2
3
Loop completed without interruption
If you use a break, the else block will not run:
for i in range(1, 4):
if i == 2:
break
print(i)
else:
print("Loop completed without interruption")
Output:
1
(No output from the else because the loop was interrupted by break)
24. Discuss how string formatting operations enhance output readability.
Answer :
String Formatting and Output Readability:
String formatting in Python makes it easier to create and control the appearance of output.
It helps make the text more readable, organized, and clear by inserting variables into strings
and aligning them as needed.
Key Benefits:
1. Inserting Variables Cleanly: String formatting allows you to insert variables directly
into a string, making your code more concise and readable.
Example:
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
Output: My name is Alice and I am 25 years old.
This avoids awkward concatenation and makes the output more natural.
2. Controlling Alignment and Spacing: Formatting helps align text, numbers, or tables
neatly, which makes the output easier to read, especially for reports or tables.
Example:
print(f"{'Name':<10} {'Age':<5}")
print(f"{'Alice':<10} {25:<5}")
print(f"{'Bob':<10} {30:<5}")
Output:
Name Age
Alice 25
Bob 30
3. Formatting Numbers: String formatting allows you to control the precision or the
appearance of numbers, which is helpful for showing things like currency or
percentages.
Example:
price = 49.995
print(f"Price: ${price:.2f}")
Output: Price: $50.00
25. Write a Python program using nested if statements to classify a number as
even/odd and positive/negative.
Answer:
# Get input from the user
num = int(input("Enter a number: "))
while Loop:
• Used when you don’t know in advance how many times to loop.
• It keeps running as long as a condition is true.
Example:
i=0
while i < 5:
print(i)
i += 1
Output:
0
1
2
3
4
28.Differentiate between string slicing and string methods in manipulating
strings.
Answer:
1. String Slicing:
• What it is: A way to extract part of a string using index positions.
• How it works: Use square brackets [] with a start and end index.
Example:
text = "Hello World"
print(text[0:5])
Output:
Hello
2 . String Methods:
• What they are: Built-in functions used to modify or analyze strings.
Examples:
text = " Hello "
print(text.strip()) # Removes extra spaces
print(text.upper()) # Converts to uppercase
Output:
Hello
HELLO
29. Evaluate the efficiency of using the "pass" statement in program
development.
Answer:
Evaluating the Efficiency of the pass Statement:
The pass statement in Python is a placeholder. It does nothing
when executed, but it lets the code run without errors when a block
is required syntactically.
Why it's useful:
1. Helps During Development:
When you're still planning or writing your code, you might
leave some parts incomplete. Instead of deleting them or writing
dummy code, you can use pass.
Example:
def future_function():
pass # I'll write this later
2. Prevents Syntax Errors:
Python requires at least one statement inside loops, functions,
classes, or if blocks. pass fills that need when you have nothing
to put yet.
3. Keeps Code Structure Clear:
It allows you to outline your program without breaking it,
which is helpful when working on big projects step-by-step.
30. Design a program to check if a string is a palindrome using a while loop.
Answer:
strr = str(input("Enter a string: "))
org_str = strr.lower()
rev_str = org_str[::-1]
if org_str == rev_str:
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
def multiply_by_three(x):
return x * 3
# Compose the functions
result = multiply_by_three(add_two(4))
print(result)
Output:
18 # (4 + 2) * 3
Recursion:
• What it is: Recursion is when a function calls itself to solve a smaller part of the
problem.
• It's useful for tasks that can be broken down into smaller, similar sub-tasks — like
calculating factorials or traversing trees.
Example:
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
Output:
120
32. List three key operations involved in file handling in Python.
Answer:
Three Key File Handling Operations in Python:
1. Opening a File
Before you can read or write a file, you need to open it using the open() function.
Example:
file = open("example.txt", "r") # "r" means read mode
2. Reading or Writing
Once the file is open, you can either read its content or write new content.
Read Example:
content = file.read()
Write Example:
file = open("example.txt", "w")
file.write("Hello, World!")
3. Closing the File
Always close the file after you're done to free up system resources.
Example:
file.close()
33. Explain the difference between local and global variables with an
example.
Answer:
Local vs Global Variables in Python
Global Variable:
• A variable declared outside any function.
• It can be used anywhere in the program, including inside
functions (unless overridden).
Local Variable:
• A variable declared inside a function.
• It can only be used within that function, not outside.
Example:
x = 10 # Global variable
def show():
y = 5 # Local variable
print("Inside function: x =", x) # Can access global
print("Inside function: y =", y)
show()
print("Outside function: x =", x)
# print(y) # This would give an error because y is local
Output:
Inside function: x = 10
Inside function: y = 5
Outside function: x = 10
34. Discuss how format operators improve file output in Python.
Answer:
Example:
name = "Alice"
score = 95.678
Code:
with open("report.txt", "w") as f:
f.write(f"Student: {name}\n")
f.write(f"Score: {score:.2f}\n")
Output:
Content in report.txt:
Student: Alice
Score: 95.68
35. Write a Python function that takes two parameters and returns their
product.
Answer:
def product(a,b):
return a * b
36. Create a program to read a text file and print its contents line by line.
Answer:
# Open the file in read mode
with open("sample.txt", "r") as file:
# Loop through each line in the file
for line in file:
print(line.strip()) # .strip() removes extra newline characters
37. Compare the use of return values versus print statements in functions.
Answer:
Return Values vs Print Statements in Functions
Return Values:
• return sends a value back to the caller of the function.
• The value can be stored, used in calculations, or passed to other functions.
• It makes the function more reusable and flexible.
Example:
def add(a, b):
return a + b
result = add(3, 4)
print(result) # Output: 7
Best for logic, calculations, and when you need to use the result later.
Print Statements:
• print() simply displays output on the screen.
• It’s used for debugging or showing results to the user.
• Doesn’t give back a value to work with in the rest of the program.
Example:
def add(a, b):
print(a + b)
add(3, 4) # Output: 7
You can’t use the result of print() for further processing.
38. Analyze the advantages of recursion over iteration in solving problems
like factorial.
Answer:
Advantage of Recursion
1. Simpler & Cleaner Code
• Recursion allows you to express a problem (like factorial) in a natural
and elegant way.
• The code is often shorter and easier to understand logically.
Example (Factorial using Recursion):
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
2. Matches the Problem’s Structure
• Some problems, like factorial, tree traversal, or Fibonacci, are
naturally recursive in definition.
• Recursion directly mirrors the way the problem is described
mathematically.
3. Useful for Complex Structures
• Recursion is very effective in handling problems with nested or
branching structures like trees and graphs.
Disadvantage:
• Recursion uses more memory (due to the call stack).
• It can be less efficient than iteration for simple tasks unless carefully
optimized.
39. Assess the importance of proper file path handling in file operations.
Answer:
Importance of Proper File Handling
1. Finding the Right File
If the path is incorrect, Python won’t be able to locate the file — causing errors like
FileNotFoundError. Using the right path ensures your program works smoothly
across folders.
2. Cross-Platform Compatibility
Different operating systems use different path styles (e.g., Windows uses \,
Linux/macOS use /). Using tools like os.path or Pathlib helps your code work on
any system.
Example:
import os
path = os.path.join("folder", "file.txt")
3. Avoiding Accidental Data Loss
Using a wrong or absolute path (like C:\) might overwrite important files or save
them in the wrong place. Correct paths keep files organized and safe.
40. Design a recursive function to compute the nth Fibonacci number.
Answer:
def fact(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
Fnm1 = fact(n-1)
Fnm2 = fact(n-2)
Fib = Fnm1 + Fnm2
return Fib
info = get_student_info()
print(info) # Output: ('Alice', 85)
45. Write a Python program to sort a list of numbers using a list method.
Answer:
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()
print(numbers) # Output: [1, 1, 2, 3, 4, 5, 6, 9]
46. Create a dictionary to store student names and marks, then print the
highest mark.
Answer:
students = {'Alice': 85, 'Bob': 90, 'Charlie': 92}
highest_mark = max(students, key=students.get)
print(f"The highest mark is {students[highest_mark]} by
{highest_mark}")
47. Compare the use of sets and lists for storing unique elements.
Answer:
• Sets are unordered collections that automatically ensure uniqueness of
elements. They are ideal when you need to store unique elements and perform set
operations like union, intersection, or difference.
• Lists allow duplicate values and maintain order. They are useful when the order
of elements matters, and duplicates are acceptable.
48. Analyze the difference between cloning and aliasing in list operations.
Answer:
plt.bar(students, marks)
plt.xlabel('Students')
plt.ylabel('Marks')
plt.title('Bar Chart of Student Marks')
plt.show()
5 marks Questions:
UNIT-I: INTRODUCTION
1. Describe the history of Python, highlighting its origin, major versions,
and contributors.
Answer:
History of Python – 5 Marks
Python was created by Guido van Rossum in the late 1980s at the Centrum Wiskunde
& Informatica (CWI) in the Netherlands. He started working on it as a hobby
project during Christmas in 1989 and released the first version, Python 0.9.0, in
1991. His goal was to make a language that combined readability, simplicity, and
power, inspired by the ABC language and C.
The name “Python” was actually inspired by Monty Python’s Flying Circus, a British
comedy show — not the snake!
Major Versions:
• Python 1.0 (1994): Introduced basic features like functions, modules, and
exception handling.
• Python 2.0 (2000): Added list comprehensions, garbage collection, and Unicode
support. It was popular but had some design issues.
• Python 3.0 (2008): A complete redesign to fix long-term flaws — but not
backward compatible. Introduced better syntax, print as a function, and better
Unicode handling.
Contributors & Growth:
Guido remained Python’s “Benevolent Dictator For Life (BDFL)” until he stepped
down in 2018. Since then, Python’s development is led by a core development
team and the Python Software Foundation (PSF). Thanks to its clean syntax and
versatility, Python has become one of the most popular programming languages
in the world, used in web development, AI, data science, automation, and more.
2. Enumerate and explain five key features of Python that distinguish it
from other programming languages.
Answer:
Five Key Features of Python – 5 Marks
1. Simple and Readable Syntax
Python code looks almost like plain English, making it easy to write
and understand. This simplicity helps beginners learn programming
faster and makes collaboration easier.
2. Interpreted Language
Python doesn't need to be compiled. You can run code line by line
using an interpreter, which is great for testing, debugging, and rapid
development.
3. Dynamically Typed
You don’t need to declare data types for variables. Python figures it
out on its own at runtime, which speeds up coding and reduces
boilerplate.
4. Extensive Standard Library
Python comes with a “batteries-included” philosophy. It includes
built-in modules for things like file handling, regular expressions,
math, and even web services—saving time and effort.
5. Large Community and Versatility
Python has a massive global community and tons of third-party
libraries. Whether you’re doing web development (like with
Django), data science (with Pandas/Numpy), or automation, there’s
likely already a solution in Python.
def greet():
"""This function prints a greeting message."""
print("Hi!")
Why It Matters:
• Flexibility: You can choose quotes based on the content.
• Avoid Escaping: Using different quotes avoids backslashes (e.g., using
double quotes for a string with a single quote).
• Docstrings: Triple quotes are essential for documenting functions and
classes.
Sample Output:
yaml
CopyEdit
Enter your name: Sara
Enter your age: 21
Welcome, Sara! You are 21 years old.
# Displaying results
print("Area of rectangle:", area)
print("Perimeter of rectangle:", perimeter)
Sample Output:
Enter the length of the rectangle: 5
Enter the breadth of the rectangle: 3
Area of rectangle: 15.0
Perimeter of rectangle: 16.0
Combined Example:
age = input("Enter your age: ")
print("You are", age, "years old.")
8. Differentiate between Python’s script mode and interactive mode,
analyzing their advantages in coding.
Answer:
10. Design a Python program that takes three inputs (name, city, and hobby)
and generates a personalized multi-line story.
Answer:
Algorithm:
1. Start
2. Prompt the user to enter their name.
3. Prompt the user to enter the city they live in.
4. Prompt the user to enter their favorite hobby.
5. Store the inputs (name, city, hobby).
6. Use the inputs to create a multi-line string (story) with placeholders for the
name, city, and hobby.
7. Print the personalized story.
8. End
Code:
# Taking input from the user
name = input("Enter your name: ")
city = input("Enter the city you live in: ")
hobby = input("Enter your favorite hobby: ")
The end.
"""
# Displaying the story
print(story)
Output:
Enter your name: isha
Enter the city you live in: Paris
Enter your favorite hobby: painting
The end.
11. List and describe the five basic data types in Python, providing an
example for each.
Python offers a variety of built-in data types, which are crucial for storing and
manipulating data. Here's a detailed breakdown:
1. Integer (int)
o Represents whole numbers without a decimal point.
o Example: age = 25
o Use case: Counting, indexing, etc.
2. Float (float)
o Represents real numbers or numbers with a decimal point.
o Example: height = 5.9
o Use case: Measurements, scientific calculations, etc.
3. String (str)
o Represents sequences of characters enclosed in quotes.
o Example: name = "Alice"
o Use case: Storing text, messages, and labels.
4. Boolean (bool)
o Represents truth values: True or False.
o Example: is_adult = True
o Use case: Conditional expressions, flags.
5. List (list)
o An ordered, mutable collection of items, which can be of mixed types.
o Example: fruits = ["apple", "banana", "cherry"]
o Use case: Storing collections of data, like items, names, etc.
12. Explain the precedence of operators in Python with a table and examples
of arithmetic operations.
Python follows operator precedence rules to determine the order in which
operations are evaluated. Here's a breakdown:
Operator Description Example
() Parentheses (3 + 2) * 4
** Exponentiation 2 ** 3
Multiplication, Division, Modulo, Floor 4 * 5, 10 /
*, /, %, //
Division 2
+, - Addition, Subtraction 3 + 2, 5 - 2
Example:
result = 3 + 5 * 2 / 4 # According to precedence, 5 * 2 is done first
print(result) # Output: 5.0
13. Discuss how tuple assignment works in Python and illustrate its use in
swapping values with an example.
Tuple assignment allows multiple variables to be assigned values
simultaneously, and it's commonly used in swapping variables.
Example (Swapping values):
x=5
y = 10
x, y = y, x # Swap using tuple assignment
print(x, y) # Output: 10 5
How it works:
• On the right side of the assignment (y, x), Python creates a tuple of the values of
y and x.
• On the left side (x, y), Python unpacks the tuple, assigning the first element to x
and the second element to y.
15. Write a Python program to exchange the values of two variables using
tuple assignment and verify the result.
Algorithm:
1. Start
2. Assign initial values to two variables (e.g., x and y).
3. Swap their values using tuple assignment.
4. Print the values of x and y to verify the swap.
5. End.
Python Program:
# Initial values
x=3
y=7
# Calculating distance
distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
19. Evaluate the necessity of type conversion in Python when working with
mixed data types in expressions.
In Python, type conversion (or casting) is required when mixing different data
types in expressions, such as trying to combine strings with numbers.
Example:
age = 25
message = "Your age is " + str(age) # Converting int to string
print(message) # Output: Your age is 25
# Circulating values
a, b, c, d, e = e, a, b, c, d
21. Define and explain the purpose of "break," "continue," and "pass"
statements in Python loops with examples.
• Break: The break statement is used to exit a loop prematurely when a certain
condition is met.
o Example:
o for i in range(5):
o if i == 3:
o break
o print(i) # Output: 0, 1, 2
o Purpose: Exits the loop when a specific condition is encountered, skipping
the remaining iterations.
• Continue: The continue statement skips the rest of the current loop iteration and
proceeds to the next iteration.
o Example:
o for i in range(5):
o if i == 3:
o continue
o print(i) # Output: 0, 1, 2, 4
o Purpose: Skips the current iteration of the loop, allowing the loop to
continue from the next iteration.
• Pass: The pass statement is a placeholder that does nothing but is used
syntactically to maintain the structure of the program.
o Example:
o for i in range(5):
o if i == 3:
o pass
o print(i) # Output: 0, 1, 2, 3, 4
o Purpose: Used where a statement is syntactically required but no action is
needed.
22. List and describe five in-built string methods in Python, including their
syntax and use.
1. str.lower(): Converts all characters in a string to lowercase.
o Syntax: string.lower()
o Example:
o text = "HELLO"
o print(text.lower()) # Output: hello
2. str.upper(): Converts all characters in a string to uppercase.
o Syntax: string.upper()
o Example:
o text = "hello"
o print(text.upper()) # Output: HELLO
3. str.replace(): Replaces a specified substring with another substring.
o Syntax: string.replace(old, new)
o Example:
o text = "Hello world"
o print(text.replace("world", "Python")) # Output: Hello Python
4. str.split(): Splits a string into a list based on a delimiter (space by default).
o Syntax: string.split(delimiter)
o Example:
o text = "Python is awesome"
o print(text.split()) # Output: ['Python', 'is', 'awesome']
5. str.strip(): Removes leading and trailing whitespaces from a string.
o Syntax: string.strip()
o Example:
o text = " Hello "
o print(text.strip()) # Output: Hello
23. Discuss the significance of the "else" clause with loops, providing an
example of its application.
The else clause in loops runs only if the loop completes without being interrupted
by a break statement. It’s useful when you want to execute something after the
loop finishes naturally.
Example:
for i in range(5):
print(i)
else:
print("Loop finished!") # Output: Loop finished!
• Significance: The else block executes only if the loop wasn’t terminated early
using break. If the loop was interrupted by break, the else block is skipped.
24. Explain string formatting operations in Python and illustrate with two
different methods.
Python provides multiple ways to format strings. Here are two common methods:
1. F-strings (formatted string literals):
o Syntax: f"string {variable}"
o Example:
o name = "Alice"
o age = 25
o print(f"Hello, {name}. You are {age} years old.") # Output: Hello, Alice.
You are 25 years old.
2. str.format() method:
o Syntax: "string {}".format(variable)
o Example:
o name = "Bob"
o age = 30
o print("Hello, {}. You are {} years old.".format(name, age)) # Output:
Hello, Bob. You are 30 years old.
Both methods provide powerful ways to create dynamic strings by inserting
variables inside them.
26. Create a program using a for loop to reverse a string and print the result
with proper formatting.
Algorithm:
1. Start
2. Accept input for the string.
3. Use a for loop to iterate over the string in reverse order.
4. Print the reversed string.
5. End.
Python Program:
# Accepting input string
text = input("Enter a string: ")
27. Compare the use of "while" and "for" loops in Python, providing
examples for different scenarios.
• For loop: Best for iterating over a known range or iterable (like a list or a string).
It's ideal when the number of iterations is predetermined.
o Example:
o for i in range(5):
o print(i) # Output: 0, 1, 2, 3, 4
• While loop: Best for situations where the loop needs to continue until a certain
condition is met, and you may not know how many iterations will occur.
o Example:
o i=0
o while i < 5:
o print(i) # Output: 0, 1, 2, 3, 4
o i += 1
Key Difference: Use a for loop when you know how many times you need to
iterate. Use a while loop when you are unsure and want to iterate based on a
condition.
28. Analyze the differences between string slicing and string methods in
terms of flexibility and efficiency.
• String Slicing: Allows you to extract a part of the string by specifying the
starting and ending indices.
o Example:
o text = "Python"
o sliced_text = text[1:4] # Output: 'yth'
o Flexibility: String slicing provides great flexibility when working with
specific indices.
o Efficiency: It is efficient because slicing directly accesses a portion of the
string.
• String Methods: Offer pre-built functionality like converting case, replacing
substrings, etc.
o Example:
o text = "Python"
o upper_text = text.upper() # Output: 'PYTHON'
o Flexibility: String methods are great for common tasks but are limited to
predefined actions.
o Efficiency: Less flexible than slicing, but can simplify tasks without
requiring custom code.
29. Assess the usefulness of the "continue" statement versus "if-else" logic in
loop control.
• continue Statement: Skips the current iteration and moves to the next iteration of
the loop.
o Usefulness: It is useful when you want to skip some iterations without
affecting the rest of the loop’s logic.
o Example:
o for i in range(5):
o if i == 3:
o continue
o print(i) # Output: 0, 1, 2, 4
• if-else Logic: Allows you to decide what to do in each iteration based on a
condition.
o Usefulness: It is more explicit and can be used to handle more complex
logic.
o Example:
o for i in range(5):
o if i == 3:
o print("Skipping 3")
o else:
o print(i) # Output: 0, 1, 2, Skipping 3, 4
**Example Output**:
Enter a string: radar radar is a palindrome.
---
31. Define recursion and function composition in Python, providing an example for
each concept.
• Recursion: Recursion occurs when a function calls itself to solve a smaller
instance of the same problem, usually with a base case to stop further
recursion.
Example:
def factorial(n):
if n == 0: # Base case
return 1
else:
return n * factorial(n - 1)
• Purpose: Recursion helps break down problems into simpler sub-problems,
especially useful for problems like tree traversal or calculating factorials.
def multiply(x):
return x * 2
def composed_function(x):
return multiply(add(x)) # First add, then multiply
result = composed_function(4)
print(result) # Output: 14 (4 + 3 = 7, 7 * 2 = 14)
• Purpose: Function composition simplifies complex operations by combining
smaller, reusable functions.
32. Explain the process of reading and writing files in Python, including the role of
format operators.
• Reading Files: Use open() to open a file in read mode ('r'), then read the
content using methods like .read() or .readlines().
• Writing Files: Use open() with write ('w') or append ('a') mode to write data
to the file.
Format Operators: These are used for formatting strings when writing to files, like
using f-strings or .format().
Example (Reading and Writing Files):
# Writing to a file
with open("data.txt", "w") as file:
file.write("Hello, world!\n")
file.write("This is a test file.\n")
33. Discuss the difference between local and global scope in Python functions with
a detailed example.
• Local Scope: Variables defined inside a function are local to that function
and cannot be accessed from outside.
• Global Scope: Variables defined outside any function are global and can be
accessed throughout the script, even inside functions.
Example:
x = 10 # Global variable
def my_function():
y = 5 # Local variable
print("Inside function: x =", x) # Global variable accessed
print("Inside function: y =", y) # Local variable accessed
my_function()
print("Outside function: x =", x)
# print("Outside function: y =", y) # This will raise an error since y is local
• Purpose: Understanding scope helps manage variable access and avoid
naming conflicts in programs.
34. Explain how filenames and paths are handled in Python file operations, with an
example.
• File Paths:
o Relative Path: Specifies the file location relative to the current working
directory.
o Absolute Path: Specifies the full path to the file, starting from the root
of the file system.
• Path Handling in Python: Use os and os.path for manipulating file paths
(e.g., joining paths, getting the file name).
Example:
# Absolute path
with open("C:/Users/username/Documents/sample.txt", "r") as file:
print(file.read())
# Relative path
with open("sample.txt", "r") as file:
print(file.read())
• Purpose: Understanding file paths ensures that files can be accessed
correctly, whether they are in the same directory or in different locations.
35. Write a Python function that takes three numbers as parameters and returns
their average.
Algorithm:
1. Start.
2. Accept three numbers as input.
3. Calculate their sum.
4. Divide the sum by 3 to find the average.
5. Return the average.
6. End.
Python Program:
def average(num1, num2, num3):
return (num1 + num2 + num3) / 3
# Example usage
result = average(10, 20, 30)
print(f"The average is: {result}") # Output: 20.0
36. Create a program to write a list of student names to a file and then read and
display them.
Algorithm:
1. Define a list of student names.
2. Open a file in write mode and write the names.
3. Close the file after writing.
4. Open the file in read mode and display the names.
5. End.
Python Program:
# List of student names
students = ["Alice", "Bob", "Charlie", "Diana"]
37. Compare the use of recursion versus iteration in solving a factorial problem,
with examples.
• Recursion: A function calls itself to reduce the problem to smaller
subproblems, useful for problems like factorials.
• Iteration: Uses a loop to repeatedly execute the same code until a condition is
met, often more efficient for simple repetitive tasks.
Factorial using Recursion:
def factorial_recursive(n):
if n == 0:
return 1
return n * factorial_recursive(n - 1)
Factorial using Iteration:
def factorial_iterative(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
• Comparison: Recursion is more elegant but may lead to stack overflow for
large inputs. Iteration tends to be more efficient and easier to understand.
38. Analyze the advantages and limitations of using return values in functions
compared to global variables.
• Return Values: Functions return values to provide output, keeping the scope
of the result limited to the function.
o Advantage: Makes code modular and easier to debug.
o Limitation: Requires passing the result around explicitly.
• Global Variables: Can be accessed anywhere in the program.
o Advantage: Convenient for sharing data across functions.
o Limitation: Makes debugging difficult due to unpredictable side effects
and changes.
• Recommendation: Prefer return values for better code structure and
maintainability.
39. Evaluate the importance of proper error handling in file operations in Python.
• Error Handling: When working with files, proper error handling ensures
that your program can handle issues like missing files, permissions errors,
and other I/O problems without crashing.
• Common Techniques: Use try-except blocks to handle exceptions and
provide feedback or alternative actions.
Example:
try:
with open("non_existent_file.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("Error: The file was not found!")
• Purpose: Proper error handling ensures that your program runs smoothly
even in unpredictable situations, improving user experience and program
reliability.
40. Design a recursive function to compute the sum of digits in a number and test it
with user input.
Algorithm:
1. Start.
2. Accept a number as input.
3. If the number is 0, return 0 (base case).
4. Otherwise, return the last digit of the number plus the sum of the remaining
digits.
5. End.
Python Program:
def sum_of_digits(n):
if n == 0:
return 0
else:
return n % 10 + sum_of_digits(n // 10)
41. Define and differentiate between lists, tuples, and sets in Python with examples.
• Lists: Lists are ordered, mutable collections that can hold heterogeneous
items. You can change their contents (e.g., add, remove, or modify elements).
Example:
my_list = [1, 2, 3, 'apple', True]
my_list[0] = 10 # Modifying an element
• Tuples: Tuples are ordered, immutable collections. Once created, their
content cannot be changed. Tuples are typically used for storing data that
should not be altered.
Example:
my_tuple = (1, 2, 3, 'apple')
# my_tuple[0] = 10 # This would raise an error because tuples are immutable
• Sets: Sets are unordered collections of unique items. They do not allow
duplicate values and do not maintain any specific order.
Example:
my_set = {1, 2, 3, 4}
my_set.add(5) # Adding an element to a set
42. List and explain five dictionary methods in Python, including their practical
applications.
1. get(): Retrieves the value associated with a specified key. If the key is not
found, it returns a default value.
Example:
my_dict = {'name': 'Alice', 'age': 25}
print(my_dict.get('name')) # Output: Alice
2. keys(): Returns a view of all keys in the dictionary.
Example:
print(my_dict.keys()) # Output: dict_keys(['name', 'age'])
3. values(): Returns a view of all values in the dictionary.
Example:
print(my_dict.values()) # Output: dict_values(['Alice', 25])
4. update(): Updates the dictionary with key-value pairs from another
dictionary or an iterable.
Example:
my_dict.update({'city': 'New York'})
print(my_dict) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
5. pop(): Removes a key-value pair and returns the value.
Example:
age = my_dict.pop('age') # Removes 'age' and returns the value
print(age) # Output: 25
43. Discuss the concept of mutability in lists and immutability in tuples, with
examples of their implications.
• Mutability (Lists): Lists are mutable, meaning their elements can be changed
after creation. This makes them flexible for scenarios where data might need
to be updated.
Example:
my_list = [1, 2, 3]
my_list[0] = 10 # Modifying a list element
• Immutability (Tuples): Tuples are immutable, which means once created,
their content cannot be changed. This ensures that tuples are safer when
data should not be modified.
Example:
my_tuple = (1, 2, 3)
# my_tuple[0] = 10 # This would raise an error
Implications:
• Mutability of lists makes them suitable for dynamic operations, like updating
a collection.
• Immutability of tuples ensures that the data remains unchanged, making
them useful as keys in dictionaries or when the data should remain constant.
44. Explain how tuples can be used as return values in functions, with an
illustrative example.
• Tuples can be returned by functions to return multiple values from a
function at once. Since tuples are immutable, this can ensure that the
returned values are not modified outside the function.
Example:
def get_user_info():
name = "Alice"
age = 30
return name, age # Returning a tuple
result = get_user_info()
print(result) # Output: ('Alice', 30)
• Purpose: Returning a tuple allows multiple values to be returned efficiently
in a single return statement, which is especially useful when you need to
return related data.
45. Write a Python program to create a list, perform slicing, and append elements,
displaying the results.
Algorithm:
1. Create a list of some initial values.
2. Perform slicing to extract a portion of the list.
3. Append new elements to the list.
4. Display the updated list.
Python Program:
# Step 1: Create a list
my_list = [1, 2, 3, 4, 5]
46. Create a dictionary of five items (product: price) and write a program to
calculate the total price.
Algorithm:
1. Create a dictionary with product names as keys and their prices as values.
2. Iterate through the dictionary to sum up the prices.
3. Display the total price.
Python Program:
# Step 1: Create a dictionary of products and prices
products = {'apple': 1.2, 'banana': 0.5, 'orange': 0.8, 'grapes': 2.5, 'watermelon':
3.0}
47. Compare the use of sets and lists for storing and manipulating data, with
examples of operations.
• Sets:
o Unordered collections with no duplicate elements. They are fast for
membership testing.
o Operations: Union (|), Intersection (&), Difference (-).
Example:
my_set = {1, 2, 3}
my_set.add(4) # Adding an element
print(my_set) # Output: {1, 2, 3, 4}
• Lists:
o Ordered collections that can contain duplicates.
o Operations: Append, Insert, Remove, Pop.
Example:
my_list = [1, 2, 3, 2]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 2, 4]
• Comparison:
o Sets are more efficient for membership testing and eliminating
duplicates, but they don't maintain order.
o Lists maintain order and allow duplicates, making them suitable for
storing sequences.
48. Analyze the differences between aliasing and cloning in lists, demonstrating
their effects on code.
• Aliasing: When two variables point to the same object in memory, changes to
one variable will affect the other.
Example (Aliasing):
list1 = [1, 2, 3]
list2 = list1 # list2 is now an alias of list1
list2[0] = 10
print(list1) # Output: [10, 2, 3] (list1 is affected)
• Cloning: Creating a copy of the list ensures that changes to the new list do
not affect the original list.
Example (Cloning):
list1 = [1, 2, 3]
list2 = list1.copy() # Cloning list1
list2[0] = 10
print(list1) # Output: [1, 2, 3] (list1 is not affected)
• Implications: Aliasing can lead to unintended side effects, while cloning
avoids this issue by creating independent copies.
49. Assess the advantages of using NumPy and pandas over traditional Python lists
for data analysis.
• NumPy:
o Provides an efficient, vectorized way to perform mathematical and
statistical operations.
o Supports multi-dimensional arrays and offers optimized performance.
• pandas:
o Built on top of NumPy, pandas offers DataFrames, which are ideal for
handling structured data (like tables).
o Efficient for working with time series, missing data, and large datasets.
• Advantages:
o Efficiency: NumPy and pandas outperform lists for large data sets due
to optimized C-based implementations.
o Convenience: pandas provides easy-to-use data manipulation
functions, like grouping, merging, and reshaping data.
50. Design a Python program using Matplotlib to plot a line graph of temperature
data over a week.
Algorithm:
1. Import necessary libraries (matplotlib for plotting, numpy for data).
2. Create a list of temperature data for each day of the week.
3. Use Matplotlib's plot() function to create a line graph.
4. Add labels and a title to the graph.
5. Display the graph.
Python Program:
import matplotlib.pyplot as plt
# Step 1: Temperature data (in Celsius) for each day of the week
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
temperatures = [22, 24
, 23, 21, 25, 27, 26]
Step 2: Plot the data
plt.plot(days, temperatures, marker='o')
Step 3: Add labels and title
plt.xlabel('Day of the Week') plt.ylabel('Temperature (°C)') plt.title('Temperature
Data Over a Week')
Step 4: Display the graph
plt.show()
Output: