Python Question & Answers - Dec-2024 Question Paper
Python Question & Answers - Dec-2024 Question Paper
Division (/)
Divides the first number by the second and returns a floating-point result.
Example: 9 / 2 results in 4.5.
5. Floor Division (//)
Divides the first number by the second and returns the largest integer less than or equal to the
result.
Example: 9 // 2 results in 4.
6. Modulus (%)
Returns the remainder of the division.
Example: 9 % 2 results in 1.
Example Code:
a = 10
b=3
Python provides several built-in data types to handle different kinds of data.
Here's a concise explanation of the basic data types with examples:
1. Numeric Types
Examples:
x = 10 # int
y = 3.14 # float
z = 2 + 3j # complex
2. Sequence Types
3. Mapping Type
Example:
4. Set Types
Examples:
5. Boolean Type
Example:
6. Binary Types
Examples:
7. None Type
NoneType: Represents the absence of a value.
Example:
These data types allow Python to handle a wide variety of data efficiently. You can use
the type() function to check the type of any variable. For example:
The program prompts the user for input (gender, age, height, and weight) and calls the
eligibility function.
Example Output:
mathematica
Copy
Edit
Enter gender (male/female): male
Enter age: 22
Enter height in cm: 160
Enter weight in kg: 65
Eligible to donate blood.
If the conditions aren’t met, it will print:
Certainly! Both while and for loops are used for repetitive tasks in Python, but they work
differently. Here's a breakdown of how each loop works and a sample program that
demonstrates both:
1. while loop:
The while loop continues to execute as long as the given condition is True. Once the condition becomes
False, the loop terminates.
2. for loop:
The for loop iterates over a sequence (like a list, string, or range) and executes the block of
code for each item in that sequence.
Example Program:
python
CopyEdit
# Using 'while' loop
print("Using while loop:")
counter = 1
while counter <= 5: # The loop will run until counter becomes greater than 5
print(f"Iteration {counter}")
counter += 1 # Increment the counter to avoid an infinite loop
# Using 'for' loop
print("\nUsing for loop:")
# Using range() to create a sequence from 1 to 5
for i in range(1, 6): # Loop will run from 1 to 5 (inclusive of 1 and exclusive of 6)
print(f"Iteration {i}")
Explanation:
While loop:
For loop:
The for loop uses range(1, 6) to create a sequence of numbers from 1 to 5 (since range
excludes the upper limit, 6 in this case).
It runs for each number in the range and prints the iteration number.
Output:
Using while loop:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Key Differences:
The while loop is typically used when you don't know how many iterations you need to run
beforehand, but you have a condition that will eventually stop the loop.
The for loop is used when you have a known sequence or range to iterate over.
Question :13 (a)
Newton's second law of motion is expressed as F = m x a ,where F is force , m is mass and a is
acceleration. Write a python program using calculate () function to calculate the acceleration
is mass of an object and the force on that object are given as input. Display the result to the
user.
Test case 1 2
Input Mass = 5,Force = 1050 Mass = 3,Force = 564
Output 210 188
You can write a Python program that uses the formula F=m×aF = m \times aF=m×a to calculate
acceleration (aaa) given the force (FFF) and mass (mmm) of an object. Rearranging the formula
to calculate
a=Fma acceleration, we get:
= \frac{F}{m}a=mF
Now, I'll create a calculate() function to perform this calculation and display the result to the
user.
Python Program:
# Test case 1
mass1 = 5
force1 = 1050
result1 = calculate(mass1, force1)
print(f"For Mass = {mass1} kg and Force = {force1} N, Acceleration = {result1} m/s²")
# Test case 2
mass2 = 3
force2 = 564
result2 = calculate(mass2, force2)
print(f"For Mass = {mass2} kg and Force = {force2} N, Acceleration = {result2} m/s²")
Explanation:
Output:
This code can be easily modified to take input from the user or handle multiple test cases
dynamically.
Question :13 (b)
Write a python program to find the sum of the cubes of the indvidual digits of a given integer
number.
Here's a Python program that calculates the sum of the cubes of the individual digits of a given
integer number:
def sum_of_cubes_of_digits(number):
# Ensure the number is positive
number = abs(number)
return sum_cubes
# Example usage
num = int(input("Enter an integer: "))
result = sum_of_cubes_of_digits(num)
print("Sum of cubes of digits:", result)
Example:
1³ + 2³ + 3³ = 1 + 8 + 27 = 36
What is a Function?
A function in Python is a reusable block of code that performs a specific task. It helps in
breaking down large programs into smaller, manageable pieces and promotes code reuse.
You define a function using the def keyword, and you can call it wherever needed.
🔹 Function Syntax:
def function_name(parameters):
# Function body
return value
python
CopyEdit
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet("Alice", 30)
Output:
Hello Alice, you are 30 years old.
2. Keyword Arguments
greet(age=25, name="Bob")
Output:
Hello Bob, you are 25 years old.
3. Default Arguments
Output:
4. Variable-length Arguments
Used when you're not sure how many arguments will be passed.
def total_sum(*numbers):
print("Sum:", sum(numbers))
total_sum(1, 2, 3, 4)
def count_vowels_and_consonants(text):
vowels = "aeiouAEIOU"
vowel_count = 0
consonant_count = 0
# Example usage
user_input = input("Enter a string: ")
vowels, consonants = count_vowels_and_consonants(user_input)
Input:
Output:
Number of vowels: 3
Number of consonants: 7
Question :15 (a)
Describe any four string functions in python with sample program.
Here are four commonly used string functions in Python along with examples:
Output:
HELLO WORLD
🔹 2. lower() – Convert to Lowercase
Output:
python programming
🔹 3. replace(old, new) – Replace Substring
Output:
I love Python
🔹 4. split(separator) – Split String
Description: Splits the string into a list based on the given separator (default is whitespace).
text = "apple,banana,grape"
fruits = text.split(",")
print(fruits)
Output:
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)
Output:
Hello World
Output:
text = "Programming"
print(text[0:6]) # First 6 characters
print(text[-3:]) # Last 3 characters
Output:
Progra
ing
🔹 5. Comparison Operators (==, !=, <, >, <=, >=)
Compares two strings lexicographically (alphabetical order based on Unicode values).
Output:
TRUE
TRUE
TRUE
Question :16
Construct a python program that uses a dictionary that contains 20 employee names and
employee ids.The program should ask the user to enter their employee name employee id. If
the employee name is not in the dictionary. The program should indicate that the person is
''not a valid employee'' of the industry. if the employee name is in the dictionary ,but the
user does not enter the right employee id, the program should say that the employee id ''is
valid''. If the employee id is correct , then the program should tell her the user that they are
now ''logged in'' to the onsite page of employee name to interact with the client/customer.
Here's a complete Python program that implements the behavior you described using a
dictionary of 20 employees and their IDs:
✅ Sample Run:
Input:
Output:
Another Input:
Output:
Employee ID is invalid.
Another Input:
Output:
Not a valid employee of the industry.
🔹 i) get() Method
Description:
Returns the value for the specified key. If the key is not found, it returns a default value (None if not specified).
# Using get()
print(employee.get("name")) # Output: Alice
print(employee.get("age")) # Output: None
print(employee.get("age", "N/A")) # Output: N/A
# Using keys()
print(employee.keys()) # Output: dict_keys(['name', 'id'])
# Using pop()
removed_value = employee.pop("dept")
print(removed_value) # Output: IT
print(employee) # Output: {'name': 'Charlie', 'id': 'E103'}
print(employee)
# Output: {'name': 'David', 'id': 'E104', 'dept': 'HR', 'location': 'New York', 'role': 'Manager'}
Here’s a clear comparison between Lists, Tuples, and Dictionaries in Python, along with
examples:
🔸 1. List
✅ Characteristics:
Ordered
📌 Example:
🔧 Use Case:
When you need a collection of items that may change (e.g., a shopping cart).
🔸 2. Tuple
✅ Characteristics:
Ordered
Uses parentheses ()
📌 Example:
🔧 Use Case:
When you need a fixed set of values that shouldn't change (e.g., geographic coordinates).
🔸 3. Dictionary
✅ Characteristics:
Mutable
📌 Example:
🔧 Use Case:
When you need to associate keys with values (e.g., employee records, configuration settings).
🧠 Summary Table:
Collections Key-value
Use Case Fixed data
that change mappings
Question :18
Expalin in detail python files , its types and operations that can be performed on files with
examples.
Python Files: Explanation, Types, and Operations
🔹 What is a File in Python?
A file is a named location on disk to store data permanently. In Python, you can create, read,
write, and append files using built-in functions.
🔹 Types of Files
Example: sample.txt
Example: image.jpg
🔹 File Operations in Python
Basic Syntax:
file = open("filename", "mode")
Modes:
Mode Description
Method Description
.readlines(
Reads all lines into a list
)
# Append
with open("employee.txt", "a") as f:
f.write("\nDepartment: HR")
# Read
with open("employee.txt", "r") as f:
data = f.read()
print(data)
✅ Summary
Feature Text File Binary File
Human- Machine-
Format
readable readable
Mode 'r', 'w', 'a' 'rb', 'wb', etc
Documents, Images,
Use Case
Logs Videos
What is an Exception?
An exception is a runtime error that disrupts the normal flow of a program. Python provides a
powerful and flexible way to handle such errors using try, except, else, and finally blocks.
Exception
Description
Type
ZeroDivisi
Raised when dividing by zero.
onError
ValueError Raised when a function receives the correct type but inappropriate value.
FileNotFo
Raised when a file operation fails due to file not existing.
undError
ImportErro
Raised when importing a module fails.
r
AttributeEr
Raised when an invalid attribute is accessed.
ror
NameErro
Raised when a variable is not defined.
r
Indentatio
Raised when indentation is not correct.
nError
✅ TypeError
try:
num = "2" + 3
except TypeError:
print("Cannot add string and integer.")
✅ ValueError
try:
age = int("twenty")
except ValueError:
print("Invalid input: expected a number.")
✅ IndexError
list1 = [1, 2, 3]
try:
print(list1[5])
except IndexError:
print("Index out of range.")
✅ KeyError
try:
f = open("file.txt", "r")
except FileNotFoundError:
print("File not found.")
finally:
print("Closing file or cleaning up.")
✅ Summary
Exceptions help make your program more robust and user-friendly.
Exception handling in Python is a mechanism to deal with runtime errors and ensure the
program doesn’t crash unexpectedly.
🔹 Why Handle Exceptions?
Keyword Description
try Code that might cause an exception
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
print(a / b)
except (ValueError, ZeroDivisionError) as e:
print("Error:", e)
try:
x = int("abc")
except Exception as e:
print("An error occurred:", e)
✅ Note: Use general Exception only when you're unsure of the exact error, but it’s better to
catch specific exceptions when possible.
try:
check_age(16)
except ValueError as ve:
print("Exception:", ve)
✅ Summary
Block Purpose
try To wrap code that may cause an exception