Python Sess. Q.paper
Python Sess. Q.paper
○ 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
○ 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]
● 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()
● 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
(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.")
● 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
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}'")
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}'")