0% found this document useful (0 votes)
11 views7 pages

Python Sess. Q.paper

Uploaded by

pm481628
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)
11 views7 pages

Python Sess. Q.paper

Uploaded by

pm481628
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/ 7

from last (included)" implies Str[-1] followed by Str[-2].

String slice for this is


Str[-1:-3:-1].
Example: s = "abcde" s[-1] is 'e' s[-2] is 'd' s[-1:-3:-1] gives 'ed'. This matches "starts from last
('e') to second item from last ('d')".
Okay, I think I have answers for all questions. I will format them clearly.Here are the answers to
the questions from your Python Programming exam paper:
SECTION A (Attempt all questions)
1.a. Difference between / and // operator with an example.
●​ The / (division) operator performs standard division and always returns a float (a
number with a decimal point), even if the division is whole.
○​ Example: 10 / 2 results in 5.0, and 7 / 2 results in 3.5.
●​ The // (floor division) operator performs division and returns the largest whole number
(integer) that is less than or equal to the result. It essentially truncates (removes) the
decimal part.
○​ Example: 10 // 2 results in 5, and 7 // 2 results in 3. For negative numbers, -7 // 2
results in -4.
1.b. How pass statement is different from a comment?
●​ pass statement:
○​ It is an actual Python statement that performs a null operation; essentially, it does
nothing when executed.
○​ It's used as a placeholder where code is syntactically required but no action needs
to be taken yet (e.g., in an empty function or class definition).
○​ The Python interpreter recognizes and executes the pass statement (though its
execution results in no action).
●​ Comment:
○​ Comments are explanatory notes in the code for human readers and are completely
ignored by the Python interpreter.
○​ They are used to make code more understandable.
○​ Single-line comments start with #, and multi-line comments (or docstrings) are
enclosed in triple quotes ("""...""" or '''...''').
In short: pass is a statement that does nothing during execution, while a comment is not
executed at all and is only for annotation.
1.c. Explain the purpose and working of loops.
●​ Purpose: Loops are used to execute a block of code repeatedly. They are essential for
automating repetitive tasks, iterating over collections of data (like lists or strings), and
controlling the flow of a program.
●​ Working:
○​ for loop: Iterates over a sequence (e.g., list, tuple, string, range) or other iterable
objects. In each iteration, a loop variable takes on the value of the current item in
the sequence, and the indented block of code is executed.​
# Example:​
for i in range(3): # i will be 0, then 1, then 2​
print(i)​

○​ while loop: Executes a block of code as long as a specified condition remains true.
The condition is checked before each iteration. If the condition is initially false, the
loop body will not execute at all. It's important to ensure the condition eventually
becomes false to avoid an infinite loop.​
# Example:​
count = 0​
while count < 3:​
print(count)​
count += 1 # Update condition variable​

1.d. Explain difference between break, continue and pass in python?


●​ break:
○​ Immediately terminates the innermost for or while loop it is in.
○​ Execution continues with the statement immediately following the terminated loop.
○​ Used to exit a loop prematurely when a specific condition is met.
●​ continue:
○​ Skips the remaining statements in the current iteration of the loop.
○​ Execution jumps to the beginning of the next iteration (for for loops) or re-evaluates
the loop's condition (for while loops).
○​ Used to bypass certain parts of the loop body for specific iterations.
●​ pass:
○​ A null statement; it does nothing.
○​ Used as a placeholder when a statement is syntactically required but no code
needs to be executed (e.g., defining an empty function or class).
1.e. Write a python program to reverse a string. Sample string: "s1234abcd" Expected
Output: "dcba4321s"
def reverse_string(input_string):​
return input_string[::-1]​

sample_string = "s1234abcd"​
expected_output = reverse_string(sample_string)​
print(expected_output)​

SECTION B (Attempt any two questions)


2. Explain Various data types used in python with example.
Python has several built-in data types:
●​ Numeric Types:
○​ int: Whole numbers (e.g., 10, -5, 0).​
age = 25​

○​ float: Numbers with a decimal point (e.g., 3.14, -0.5, 2e5 which is 2 \\times 10^5).​
price = 19.99​

○​ complex: Numbers with a real and imaginary part (e.g., 3+5j, 2-7j).​
c_num = 2 + 4j​

●​ Sequence Types:
○​ str (String): Ordered, immutable sequence of characters. Enclosed in single ('...'),
double ("..."), or triple ("""...""") quotes.​
name = "Alice"​
message = 'Hello'​
○​ list: Ordered, mutable (changeable) collection of items, which can be of different
types. Defined using square brackets [].​
my_list = [1, "apple", 3.0, True]​

○​ tuple: Ordered, immutable (unchangeable) collection of items. Defined using


parentheses ().​
my_tuple = (10, "banana", 2.5)​

●​ Mapping Type:
○​ dict (Dictionary): Unordered (in Python versions before 3.7, ordered from 3.7+)
collection of key-value pairs. Keys must be unique and immutable. Mutable.
Defined using curly braces {}.​
person = {"name": "Bob", "age": 30}​

●​ Set Types:
○​ set: Unordered collection of unique, immutable items. Mutable. Defined using curly
braces {} or set().​
my_set = {1, 2, 3, 3, "hello"} # Results in {1, 2, 3,
'hello'}​
empty_set = set()​

○​ frozenset: An immutable version of a set.​


frozen = frozenset([1, 2, 2, 3])​

●​ Boolean Type:
○​ bool: Represents truth values True or False.​
is_active = True​
has_error = False​

●​ None Type:
○​ NoneType: Has only one value, None, representing the absence of a value or a null
value.​
result = None​

3. i. Implement a python program to swap two numbers without using


Intermediate/Temporary variables. Prompt the user for input.
num1 = int(input("Enter the first number: "))​
num2 = int(input("Enter the second number: "))​

print(f"Before swapping: num1 = {num1}, num2 = {num2}")​

# Pythonic way using tuple packing and unpacking​
num1, num2 = num2, num1​

print(f"After swapping: num1 = {num1}, num2 = {num2}")​

(Alternative for integers: num1 = num1 + num2; num2 = num1 - num2; num1 = num1 - num2 or
using XOR)
3. ii. Implement a python program to check if a given year is a leap year or not.
year = int(input("Enter a year: "))​

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):​
print(f"{year} is a leap year.")​
else:​
print(f"{year} is not a leap year.")​

4. Explain the Identifiers, Keywords, Statements, Expressions, and Variables in python


programming language with examples.
●​ Identifiers: Names given to entities like variables, functions, classes, etc. (e.g.,
my_variable, calculate_sum, Student_Data). Rules:
○​ Can contain letters (a-z, A-Z), digits (0-9), and underscore (_).
○​ Cannot start with a digit.
○​ Cannot be a keyword.
○​ Case-sensitive.
●​ Keywords: Reserved words with special meanings that define the language's syntax and
structure (e.g., if, for, while, def, class, True, None). They cannot be used as identifier
names.​
import math # 'import' is a keyword​
def my_func(): # 'def' is a keyword​
pass # 'pass' is a keyword​

●​ Statements: Instructions that the Python interpreter can execute. They represent an
action or command.
○​ Assignment statement: x = 10
○​ Print statement (function call): print("Hello")
○​ Conditional statement: if x > 5: print("Greater")
○​ Loop statement: for i in range(3): print(i)
●​ Expressions: A combination of values, variables, operators, and function calls that
evaluates to a single value.
○​ 5 + 3 (evaluates to 8)
○​ x * 2 (evaluates to twice the value of x)
○​ name.upper() (evaluates to the uppercase version of the string name)
○​ y > 10 (evaluates to True or False)
●​ Variables: Named storage locations in memory used to hold data. In Python, variables
are created when you assign a value to them.​
age = 30 # 'age' is a variable storing the integer 30​
name = "Python" # 'name' is a variable storing the string "Python"​
pi_value = 3.14159 # 'pi_value' stores a float​

SECTION C (Attempt any two questions)


5. i. Implement a python program to check if a number is odd and divisible by 3. Prompt
the user for input.
number = int(input("Enter an integer: "))​

if number % 2 != 0 and number % 3 == 0:​
print(f"{number} is odd and divisible by 3.")​
else:​
if number % 2 == 0:​
print(f"{number} is not odd.")​
if number % 3 != 0:​
print(f"{number} is not divisible by 3.")​
if number % 2 == 0 or number % 3 !=0: # One or both conditions
failed​
print(f"{number} is NOT both odd and divisible by 3.")​

5. ii. Implement a python program to reverse a number and find the Sum of digits in the
reversed number. Prompt the user for input.
num_str = input("Enter an integer: ")​
try:​
original_number = int(num_str)​

# Handle negative sign if present for reversal display, but sum
uses absolute digits​
sign = ""​
if num_str.startswith('-'):​
sign = "-"​
num_str_for_reversal = num_str[1:]​
else:​
num_str_for_reversal = num_str​

# Reverse the digits of the number​
reversed_digits_str = num_str_for_reversal[::-1]​

# The reversed number as an integer (magnitude)​
reversed_number_magnitude = int(reversed_digits_str)​

# Calculate the sum of digits in the reversed number​
sum_of_digits = 0​
for digit_char in reversed_digits_str:​
sum_of_digits += int(digit_char)​

print(f"Original number: {original_number}")​
print(f"Reversed number: {sign}{reversed_number_magnitude}")​
print(f"Sum of digits in the reversed number
({reversed_digits_str}): {sum_of_digits}")​

except ValueError:​
print("Invalid input. Please enter a valid integer.")​

6. Illustrate different slicing constructs for the following operations on the string: Str =
"United College of Engineering & Technology"
Str = "United College of Engineering & Technology"​
print(f"Original String: '{Str}'\n")​

# i. Return a string that starts from the last to second item of the
string.​
# Interpretation: A string containing the last character followed by
the second-to-last character.​
# Example: for "abcde", result is "ed"​
# Str[-1] is the last, Str[-2] is second last. Slice Str[from:to:step]​
# Starts at -1 (last), goes towards beginning, stops *before* index
-3.​
op_i = Str[-1:-3:-1]​
print(f"i. Starts from last to second item (e.g., 'yg' from
'Technology'): '{op_i}'")​

# ii. Return a string that starts from 3rd item to second last item.​
# 3rd item is at index 2. Second last item is at index -2.​
# Slicing goes up to, but does not include, the stop index. So, stop
at -1.​
op_ii = Str[2:-1]​
print(f"ii. From 3rd item (index 2) up to (but not including) last
item: '{op_ii}'")​

# iii. Return a string that has only even position elements of string
Str.​
# (Assuming "even position" means 0-indexed: 0, 2, 4, ...)​
str1 = Str[::2] # Start at beginning, go to end, step by 2​
print(f"iii. Even position elements (0-indexed): '{str1}'")​

# iv. Return a string that started from the middle of the string Str.​
mid_index = len(Str) // 2​
op_iv = Str[mid_index:]​
print(f"iv. From middle (index {mid_index}) to end: '{op_iv}'")​

SECTION D (Attempt any one question)


(You would choose one of these. I will provide both.)
7.i. Implement a python Program to display a table of a number as input given by user.
try:​
num = int(input("Enter a number to display its multiplication
table: "))​
limit = int(input("Enter the limit for the table (e.g., up to 10):
"))​

print(f"\nMultiplication Table for {num} up to {limit}:\n")​
for i in range(1, limit + 1):​
print(f"{num} x {i} = {num * i}")​

except ValueError:​
print("Invalid input. Please enter valid integers.")​

7.ii. Implement a python program to construct following pattern


1​
2 3​
4 5 6​
7 8 9 10​
11 12 13 14 15​

rows = 5​
current_number = 1​
for i in range(1, rows + 1): # For each row​
for j in range(i): # For numbers in that row​
print(current_number, end=" ")​
current_number += 1​
print() # Newline after each row​

8. Implement a python program to insert any five elements in an empty list using for loop.
my_list = []​
print("Enter 5 elements for the list:")​

for i in range(5):​
element = input(f"Enter element {i + 1}: ")​
my_list.append(element)​

print("\nThe list with the 5 elements is:", my_list)​

9. Implement a python program to remove characters that have odd index values in a
given string. Sample String : 'abcdef' Expected Result : 'ace'
def remove_odd_index_chars(input_string):​
# Keep characters at even indices (0, 2, 4, ...)​
# This can be done by slicing with a step of 2​
return input_string[::2]​

# Sample String​
sample_string = 'abcdef'​
expected_result = remove_odd_index_chars(sample_string)​
print(f"Sample String: '{sample_string}'")​
print(f"Expected Result: '{expected_result}'")​

# Alternative using a loop (if explicit loop is required):​
# def remove_odd_index_chars_loop(input_string):​
# new_string = ""​
# for i in range(len(input_string)):​
# if i % 2 == 0: # Check if the index is even​
# new_string += input_string[i]​
# return new_string​
# result_loop = remove_odd_index_chars_loop(sample_string)​
# print(f"Result (with loop): '{result_loop}'")​

You might also like