cn fornt (2)-1
cn fornt (2)-1
cn fornt (2)-1
* Indentation in Python refers to spaces or tabs used at b)* *What are the usages of zip(), tuple(), count(), and index() functions?* a)* *Add ‘ing’ or ‘ly’ to a string.* ,, python,, s = input("Enter a string: ")
the beginning of a code block to define its structure, particularly in loops, - zip(): Combines multiple iterables. if len(s) >= 3: ,, if s.endswith('ing'): ,, s += 'ly' ,, else: ,, s += 'ing' ,, print(s)
conditionals, and functions. - tuple(): Converts an iterable into a tuple. *b)* *Combine values in a list of dictionaries.*
b)Write code to print the elements of the list 11 = [10, 20, 30, 40, 50]. python..lst - count(): Counts occurrences of an element in a tuple. Python ,, from collections import Counter
= [10, 20, 30, 40, 50]..for element in lst: - index(): Returns the first index of an element in a tuple. data = [{'item': 'item1', 'amount': 400}, {'item': 'item2', 'amount': 300}, {'item': 'item1',
print(element) *c)* *What is an anonymous function? How to create it? Explain with example.* 'amount': 750}],, result = Counter() ,, for d in data: ,, result[d['item']] += d['amount']
c)What is a slice operator?* A slice operator ([:]) is used to access a subset of a An anonymous function is a function defined using lambda without a name. print(result)
Example: python,, square = lambda x: x * x,, print(square(5)) # Output: 25 a)* *Write a Python program to calculate \(X^Y\).*
sequence (like lists, tuples, or strings) by specifying start, stop, and step values. *c)* *Check if a string contains only certain characters.* x = int(input("Enter X: ")); y = int(input("Enter Y: ")) ; print(f"{x}^{y} = {x**y}")
d)What is a variable-length argument?Variable-length arguments allow a Python,, import re,, s = input("Enter a string: "),, if re.fullmatch(r"[a-zA-Z0-9]*", s): b)* *Write a Python program to check whether a number is perfect.*
function to accept any number of arguments using *args (non-keyworded) or print("String contains only allowed characters."),, else: num = int(input("Enter a number: ")); sum_div = sum(i for i in range(1, num) if num %
**kwargs (keyworded). print("String contains disallowed characters.") i == 0); if sum_div == num: .. print(f"{num} is a perfect number") .. else:
Example: python,, def var_args(*args):,, for arg in args:,, print(arg) c)* *Extract year, month, date, and time using Lambda.* print(f"{num} is not a perfect number")
f)* *Explain the remove() method.*The remove() method removes the first python ,, from datetime import datetime c)* *Use of seek() and tell() functions.*
occurrence of a specified value from a list.Example: ,, python,, lst = [1, 2, 3, 2] now = datetime.now() - seek(): Moves the file pointer to a specified location. tell(): Returns the current
lst.remove(2),, print(lst) # Output: [1, 3, 2] extract = lambda dt: (dt.year, dt.month, dt.day, dt.strftime("%H:%M:%S")) position of the file pointer.
*g)* *Write a lambda function to add 10 to a given integer.* print(extract(now))
Python,, add_ten = lambda x: x + 10,, print(add_ten(5)) # Output: 15
d)* *Demonstrate set with example.* A set is an unordered collection of unique *g) What are required arguments in a function?* c)What is a module? What is a package? Explain with example.
elements. Python ,, s = {1, 2, 3, 3} ,, print(s) # Output: {1, 2, 3} - Required arguments are the parameters that must be passed to the function - *Module*: A single Python file containing code.
*e)* *What is dictionary? Give example.* A dictionary is a collection of key- when it is called. If these arguments are not provided, the function will raise an - *Package*: A collection of modules organized in directories with an __init__.py file.
value pairs. Python ,, d = {"name": "Alice", "age": 25} ,, print(d["name"]) # error. *Example:- # In package/module.py def greet(): … print("Hello from package
Output: Alice h) Explain any 2 functions in the time module.* module!") ,, from package import module module.greet()
*f)* *What is regEx? Give example.* Regular expressions (regEx) are used for - time.time(): Returns the current time in seconds since the Epoch. a) How to handle exception in Python?*- Exceptions in Python are handled using try,
pattern matching in strings. Python ,, import result = re.search(r'\d+', 'Price is - time.sleep(): Pauses the execution of the program for the specified number of except blocks. You can also use else and finally blocks to handle code that runs when
123') seconds. no exception occurs and cleanup code respectively.
print(result.group()) # Output: 123. *i) What are the types of files in Python?* *b) Explain any 2 metacharacters used in regular expressions.*
a)* *Short note on data types in Python. - The main types of files in Python are: 1. Text files 2. Binary files - .: Matches any character except a newline. - ^: Matches the start of a string.
- *Numeric*: int, float, complex. - *Sequence*: list, tuple, range. - *Text*: str. *j) Write the use of seek & tell function.* *c) Explain any 2 built-in list functions.* - append(): Adds an element to the end of
- *Set*: set, frozenset. - *Mapping*: dict.- *Boolean*: True, False. - seek(): Moves the file pointer to a specific position in the file. the list. - pop(): Removes and returns the last item from the list.
- *Binary*: bytes, bytearray. - tell(): Returns the current position of the file pointer. *d) Explain backward indexing in strings.*
*c) Write a Python program to check if a given key already exists in a g)What is user-defined Module? Give example.* A user-defined module is a - In Python, you can index strings from the end using negative numbers. For example,
dictionary.* Python file containing custom functions, classes, or variables. string[-1] gives the last character, string[-2] gives the second last, and so on.
=> def check_key_in_dict(d, key): ,, if key in d: print(f"Key '{key}' exists.") *Example:* Create mymodule.py: ,, python ,, def greet(): ,, print("Hello from *e) Define identifiers.- Identifiers in Python are names given to variables, functions,
else: print(f"Key '{key}' does not exist.") # Example mymodule!") ,, *Usage:* ,, python ,, import mymodule ,, mymodule.greet() classes, etc. They must begin with a letter or underscore, followed by letters, digits, or
check_key_in_dict({'a': 1, 'b': 2}, 'a') # Output: Key 'a' exists. underscores.
a)* *Output of given code snippet.* d)* *Explain the following loops with example.* - *While loop:* Repeats while a
*h)* *Python is a case-sensitive language. Comment.* Corrected code: ,, python ,, check1 = ['Learn', 'Quiz', 'Practice', 'Contribute'] condition is true. ,, python,, i = 0,, while i < 5:,, print(i),, i += 1
Yes, Python differentiates between uppercase and lowercase letters. For example, check2 = check1 ,, check3 = check1[:] ,, check2[0] = 'Code' ,, check3[1] = 'Mcq' - *For loop:* Iterates over items in a sequence.
Variable and variable are distinct.*i)* *What is dry run in Python?* count = 0 ,, for c in (check1, check2, check3): Python,, for i in range(5):,, print(i)
A dry run refers to manually going through code to predict its behavior without if c[0] == 'Code': ,, count += 1 ,, if c[1] == 'Mcq': *e)* *How to perform input-output operations? Explain with example.*
actually running it. count += 10 ,, print(count) # Output: 11 - *Input:* input() to read user input.
b)* *Short note on exception handling.* b)* *Program to update Counter.* python ,, Counter = {} - *Output:* print() to display output.
Exception handling allows for managing errors during runtime using try, except, def addToCounter(country): ,, if country in Counter: ,, Counter[country] += 1 Example: ,, python,, name = input("Enter your name: "),, print(f"Hello, {name}!")
and finally. else: ,, Counter[country] = 1 ,, addToCounter("USA"),, addToCounter("India") a)* *Reverse a string and eliminate the letter ‘s’.* python,, s = input("Enter a string:
x=1/0 addToCounter("USA") ,, print(Counter) # Output: {'USA': 2, 'India': 1} "),, reversed_s = s[::-1].replace('s', '').replace('S', ''),, print(reversed_s)
except ZeroDivisionError as e: a)* *What are the advantages of Python?* - Easy to learn and use. *b)* *Raise an exception if age is less than 18.*
print("Error:", e) - Extensive library support. - Platform-independent. - Strong community support. Python,, class AgeException(Exception): ,, pass ,, age = int(input("Enter your age:
finally: - Dynamic typing and memory management. *b)* *List out main differences ")),, if age < 18: ,, raise AgeException("Age is less than 18.").
print("Execution completed") between lists & tuples.* - *Lists*: Mutable, defined with square brackets []. - *d)* *Demonstrate list slicing.*
*Tuples*: Immutable, defined with parentheses ().*c)* *Python is a scripting lst = [10, 20, 30, 40, 50] .. print(lst[1:4]) # Output: [20, 30, 40]
language. Comment.* j)* *What is lambda function? Give example.* e)* *A tuple is an ordered collection of items. Comment.* Yes, tuples maintain the
A lambda function is an anonymous function defined using the lambda keyword. order of elements, and the elements can be accessed via indices
Python:,, square = lambda x: x * x:,,print(square(4)) # Output: 16
e)* *How to add multiple elements at the end of a list?* a)* *Recursive function to display the sum of digits until a single digit.* a) What is dry run in Python? - A dry run is the process of manually walking through
Use the extend() method. Python,, lst = [1, 2, 3],, lst.extend([4, 5, 6]) def sum_of_digits(n):,, if n < 10:,, return n the code to understand how it works and to check for any logical errors, without
print(lst) # Output: [1, 2, 3, 4, 5, 6] return sum_of_digits(sum(int(digit) for digit in str(n))) actually running the code.
f)* *Explain the remove() method.* The remove() method removes the first num = int(input("Enter a number: ")) ,, b) Give the purpose of selection statements in Python.*
occurrence of a specified value from a list.Example:,, python,, lst = [1, 2, 3, 2] print("Single-digit sum:", sum_of_digits(num)) - Selection statements like if, if-else, and if-elif-else are used to make decisions in the
lst.remove(2),, print(lst) # Output: [1, 3, 2] b)* *Compute sum of squares of list integers.* program, allowing different paths of execution based on conditions.
*g)* *Write a lambda function to add 10 to a given integer.* n = int(input("Enter number of integers: ")) c) List the types of type conversion in Python. => The types of type conversion in
Python,, add_ten = lambda x: x + 10,, print(add_ten(5)) # Output: 15 lst = [int(input()) for _ in range(n)] Python are: 1. Implicit type conversion (Automatic) 2. Explicit type conversion
a)* *What is a package? Explain with example how to create a package.* print("Sum of squares:", sum(x**2 for x in lst)) d) What is the use of pass statement? - The pass statement in Python is used as a
A package is a collection of Python modules organized in directories with an c)* *Count occurrences of "India" and "Country" in pledge.txt.* placeholder for future code. It allows the program to run without any errors if a block
__init__.py file. *Example:*1. Create a directory mypackage. with open("pledge.txt", "r") as file: of code is empty, especially in class or function definitions.
2. Inside mypackage, add __init__.py and modules like module1.py. text = file.read() e) Explain the function enumerate().:- The enumerate() function in Python adds a
Python,, # In module1.py,, def greet():,, print("Hello from module1!") print("India:", text.count("India")) counter to an iterable and returns it as an enumerate object, which can then be used
3. Import and use:,, python,, from mypackage import module1 print("Country:", text.count("Country")) in loops. It is useful when you need both index and value in a loop.
module1.greet() b)* *Output of the second code snippet:* f) Explain the extend method of list.* - The extend() method adds all elements of an
The code raises an error because the decorator @f is applied incorrectly, leading to iterable (like another list or tuple) to the end of the list. For example: list1.extend([4,
a recursive call that violates the decorator's logic. 5]) will add 4 and 5 to list1.