Python
Python
Indentation refers to the spaces or tabs used at the beginning of a line to structure the code.
In Python, indentation is critical because it defines blocks of code (e.g., loops, functions,
conditionals). Unlike some other languages that use curly braces {} to group code, Python
relies on indentation to determine what code belongs to which block.
EX : if x > 5:
print("x is greater than 5") # Indentation here
b) Write code to print the elements of the list 11 = [10, 20, 30, 40, 50]
There's a slight issue with the variable name 11 — variable names cannot start with a
number. I'll assume you meant to name the list numbers. Here's the code to print the
elements:
The slice operator in Python allows you to extract a portion (or slice) of a sequence (like a
list, tuple, or string). The syntax for slicing is sequence[start:stop:step], where:
Use the extend() method or the += operator to add multiple elements at the end of a list.
The remove() method is used to remove the first occurrence of a specific element from a
list. If the element is not found, it raises a ValueError.
add_10 = lambda x: x + 10
print(add_10(5)) # Output: 15
Use the raise keyword followed by the exception type and the arguments (optional).
Example:
class CustomError(Exception):
pass
The re package in Python is used for working with regular expressions. EX:-
Example:
import re
pattern = r"\d+" # Matches one or more digits
result = re.findall(pattern, "There are 12 apples and 34 oranges")
print(result) # Output: ['12', '34']
The wb mode in file operations stands for write binary. It is used to open a file for writing in
binary mode. When you open a file in wb mode, you can write binary data (like images or
non-text files) to the file.
Q2]
a) What are the usages of zip(), tuple(), count(), and index() functions?
Function Description Example Usage Usage
EX:- Let's create a simple package called mypackage that has two modules module1.py and
module2.py.
mypackage/
__init__.py
module1.py
module2.py
2. Content of module1.py:
# mypackage/module1.py
def greet():
return "Hello from module 1!"
3. Content of module2.py:
# mypackage/module2.py
def farewell():
return "Goodbye from module 2!"
4. Content of __init__.py:
# mypackage/__init__.py
# This can be left empty or contain package-level variables or
functions.
Now, you can use this package in another Python script by importing it:
import mypackage.module1
import mypackage.module2
An anonymous function in Python is a function that does not have a name. It's typically
created using the lambda keyword. These functions are used for short, one-time operations
where defining a full function with a name might be overkill. Anonymous functions are often
used in places like map(), filter(), sorted(), etc., where a small function is required
temporarily.
1. Creating an anonymous function: You can create an anonymous function using the
lambda keyword followed by the parameters and the expression. The syntax is:
o (The lambda function takes two arguments x and y, and returns their sum.)
Example 2: Sorting a list of tuples based on the second value using lambda
# List of tuples
pairs = [(1, 'one'), (3, 'three'), (2, 'two')]
o (The lambda function is used as the sorting key to sort the list of tuples based on the
second value in each tuple.)
i) While loop :- A while loop repeatedly executes a block of code as long as a specified
condition evaluates to True. Once the condition becomes False, the loop terminates.
Syntax:
while condition:
# Code block
The condition is checked before each iteration. If it evaluates to True, the loop body is
executed; otherwise, the loop ends.
Make sure to include logic inside the loop that eventually makes the condition False, or
you'll get an infinite loop.
In this example, the while loop runs as long as count is less than or equal to 5. The count
+= 1 inside the loop ensures that the loop will eventually terminate.
ii)For loop :- A for loop is used to iterate over a sequence (like a list, tuple, string, or range).
The loop executes once for each item in the sequence.
Syntax:
The variable takes the value of each item in the sequence one by one.
The loop body executes for each item in the sequence until all items are processed.
In this example, the for loop iterates over the list numbers and prints each element.
The range() function generates a sequence of numbers, which is often used in for loops for
a specific range of iterations.
i)Input Operation(input()) :- The input() function is used to take user input from the
console. It always returns the input as a string.
Syntax: input(prompt)
o prompt is an optional string that is displayed to the user before taking input.
Hello, Alice!
In this example, input() takes a string input from the user, and print() displays a greeting
message.
ii) Output Operation(print()) :- The print() function is used to display output to the console.
It can take multiple arguments and can automatically handle the conversion of data types to
string.
In this example, print() outputs both the name and age variables.
Output: Hello-World!
The sep argument is used to specify the separator between the arguments (in this case, a
dash -).
The end argument specifies the ending character (in this case, an exclamation mark and a
newline \n).
Q3]
In this program, if the user inputs an age less than 18, an AgeException is raised, and an
error message is printed. The ValueError exception is also handled in case the user does not
input a valid integer.
class AgeException(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
If the string contains any characters other than alphanumeric characters (like spaces,
punctuation, etc.), the program will print that the string contains invalid characters.
Q4]
If the input string ends with "ing", like "sing", it will append "ly" instead:
Input:Enter a string: hi
Output:Modified string: hi
# Sample data
data = [{'item': 'item 1', 'amount': 400},
{'item': 'item2', 'amount': 300},
{'item': 'item1', 'amount': 750}]
Explanation:
o We iterate over each dictionary in the list and update the Counter object.
o The Counter keeps a running total for each unique item.
o After processing, we get the total amount for each item.
c) Python Program to Extract Year, Month, Date, and Time Using Lambda
Explanation:
o datetime.now() gives the current date and time.
o The lambda function extract_info takes a datetime object and returns a tuple
with the year, month, day, hour, minute, and second.
o We extract these values and print them.
Summary:
a) The program modifies a string by adding "ing" or "ly" based on the string's conditions.
b) The program combines values of the amount key in a list of dictionaries using Counter.
c) The program uses a lambda function to extract the year, month, date, hour, minute, and
second from the current date and time.
Q5]
a) Check1 = ['Learn', 'Quiz', 'Practice', 'Contribute']
Check2 = check1
Check3 = check1 [:]
Check2[0] = 'Code'
Check3[1] = 'Mcq'
Count = 0
For c in (check 1, check2 check3):
if c[0] == 'Code':
count + = 1
if c[1] == 'Mcq':
count + = 10
print (count)
Ans=>
# Initial lists
# Modify elements
Check2[0] = 'Code'
Check3[1] = 'Mcq'
# Initialize counter
count = 0
count += 1
count += 10
print(count)->12
b) Counter = {}
Def add To Counter (Country):
If country in counter:
Counter [country] + = 1
Else:
Counter [country] = 1
Add To Counter ('China')
Add To Counter ('Japan')
Add To Counter ('china')
Print (len(counter))
Ans=>
# Initialize an empty dictionary to store the country counts
counter = {}
def add_to_counter(country):
country = country.lower() # This ensures that 'China' and 'china' are counted as the same
if country in counter:
add_to_counter('China')
add_to_counter('Japan')
add_to_counter('china') # This will be counted as the same as 'China'
print(len(counter))
2