Python
Python
In Python, comments are written using the # symbol. Anything after the # on the same line is
considered a comment and is ignored by the Python interpreter.
python
Copy code
The index() method is used to find the index of the first occurrence of a specified substring in
a string. It raises a ValueError if the substring is not found.
python
Copy code
The range() function generates a sequence of numbers. It can take up to three parameters:
python
Copy code
range(5) # [0, 1, 2, 3, 4]
python
Copy code
def print_message():
clock(): (Deprecated in Python 3.8+) It was used to return the processor time used by the
program.
gmtime(): This function returns the current time in Coordinated Universal Time (UTC) as a
time structure (struct_time).
python
Copy code
import time
The syntax for handling exceptions in Python is done using try, except, and optionally finally.
python
Copy code
try:
except ExceptionType:
finally:
The enumerate() function adds a counter to an iterable and returns it as an enumerate object.
It is commonly used in loops to get both the index and the element.
python
Copy code
print(index, fruit)
# Output:
# 0 apple
# 1 banana
# 2 cherry
a) Which methods are used to read from a file? Explain any two with examples.
python
Copy code
content = file.read()
print(content)
python
Copy code
line = file.readline()
print(line)
b) What are the usage of dictionary copy(), get(), items(), and keys() methods?
get(key, default): Returns the value for the specified key. If the key is not found, it returns the
default value.
items(): Returns a view object that displays a list of dictionary's key-value tuple pairs.
python
Copy code
print(my_dict.get('a')) # 1
python
Copy code
set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1.union(set2)) # {1, 2, 3, 4}
print(set1.intersection(set2)) # {2, 3}
python
Copy code
if condition:
# code to execute
if else: Executes one block of code if a condition is true, otherwise executes another block.
python
Copy code
if condition:
# code if true
else:
# code if false
python
Copy code
for i in range(5):
if i == 3:
continue: Skips the current iteration and proceeds to the next one.
python
Copy code
for i in range(5):
if i == 3:
print(i)
Easy to read and write: Python has simple and clean syntax.
Dynamically typed: No need to declare variable types explicitly.
python
Copy code
N=5
python
Copy code
def count_vowels_consonants(string):
vowels = "aeiouAEIOU"
v_count = c_count = 0
if char.isalpha():
if char in vowels:
v_count += 1
else:
c_count += 1
v, c = count_vowels_consonants(string)
c) Write a Python function that accepts a string and counts the number of uppercase and
lowercase letters.
python
Copy code
def count_upper_lower(string):
upper = lower = 0
if char.isupper():
upper += 1
elif char.islower():
lower += 1
u, l = count_upper_lower(string)
a) What is indentation?
Indentation in Python refers to the spaces or tabs at the beginning of a code block. It is
essential in Python because it defines the structure and scope of control flow constructs
such as loops, functions, and conditionals. Python uses indentation to determine which
statements belong to the same block of code.
python
Copy code
my_list = [10, 20, 30, 40, 50]
print(element)
The slice operator in Python ([:]) allows you to access parts of sequences like lists, tuples, and
strings. It lets you extract a subset of items from a sequence by specifying the start and stop
positions. The syntax is sequence[start:stop:step].
Example:
python
Copy code
Example:
python
Copy code
def sum_of_numbers(*args):
return sum(args)
The remove() method is used to remove the first occurrence of a specified element from a
list.
Example:
python
Copy code
my_list.remove(20)
re.match()
re.search()
re.findall()
re.sub()
re.split()
re.compile()
In Python, the wb mode opens a file in binary format for writing. The file is truncated to zero
length if it exists, and a new file is created if it does not.
python
Copy code
add_10 = lambda x: x + 10
print(add_10(5)) # Output: 15
A package is a way of organizing related Python modules into a directory hierarchy. A package
usually contains an __init__.py file to differentiate it from a normal directory.
Example:
Copy code
mypackage/
__init__.py
module1.py
module2.py
python
Copy code
def hello():
python
Copy code
python
Copy code
a = (1, 2, 3)
b = (4, 5, 6)
zipped = zip(a, b)
Copy code
python
Copy code
my_tuple = (1, 2, 2, 3)
print(my_tuple.count(2)) # Output: 2
python
Copy code
my_tuple = (1, 2, 3)
print(my_tuple.index(2)) # Output: 1
An anonymous function in Python is a function that is defined without a name, using the
lambda keyword.
Example:
python
Copy code
add = lambda x, y: x + y
i) While Loop: A while loop repeatedly executes a block of code as long as the condition is
True.
python
Copy code
i=1
while i < 5:
print(i)
i += 1
ii) For Loop: A for loop is used to iterate over a sequence (like a list, tuple, or string).
python
Copy code
for i in range(5):
print(i)
b) Write a program to raise a user-defined exception to check if age is less than 18.
python
Copy code
class AgeException(Exception):
pass
def check_age(age):
else:
print("Age is valid")
try:
check_age(15)
except AgeException as e:
print(e)
c) Python program to check that a string contains only a certain set of characters (a-z, A-Z, 0-
9).
python
Copy code
import re
def is_allowed_string(string):
pattern = re.compile(r'^[a-zA-Z0-9]+$')
return bool(pattern.match(string))
Python program to extract year, month, date, and time using Lambda:
python
Copy code
now = datetime.now()
A dry run refers to manually going through the code without actually executing it in the
Python interpreter. You simulate the flow of the program, tracing the values of variables and
the behavior of control structures (like loops and conditions), to understand the logic and
find any issues or errors before running the program.
Selection statements are used to control the flow of a program by making decisions. In
Python, the main selection statement is the if-elif-else construct, which allows a program to
execute certain blocks of code based on specific conditions being true or false.
Required arguments are the arguments that must be passed to a function when it is called. If
you define a function with certain parameters and those parameters do not have default
values, Python will raise an error if the corresponding arguments are not provided.
For example:
python
Copy code
return a + b
time.sleep(seconds): Pauses the execution of the program for the specified number of
seconds.
python
Copy code
import time
time.time(): Returns the current time in seconds since the Epoch (usually January 1, 1970,
00:00:00 UTC).
python
Copy code
current_time = time.time()
Text files: These files store data in human-readable form using characters. Common
extensions are .txt, .csv, etc.
Binary files: These files store data in binary (0s and 1s), typically used for non-text data like
images, audio, etc. Common extensions include .jpg, .png, .exe, etc.
seek(): Changes the position of the file pointer to a specific location in the file.
python
Copy code
python
Copy code
python
Copy code
try:
# Code that may raise an exception
x = 10 / 0
except ZeroDivisionError:
python
Copy code
my_list = [1, 2, 3]
my_list.append(4) # [1, 2, 3, 4]
python
Copy code
my_list = [3, 1, 4, 2]
my_list.sort() # [1, 2, 3, 4]
In Python, backward indexing refers to indexing from the end of the string using negative
indices. The last character of the string is at index -1, the second-last at -2, and so on.
python
Copy code
my_string = "Python"
e) Define identifiers.
Identifiers are names used to identify variables, functions, classes, modules, and other
objects in Python. Identifiers must start with a letter (A-Z or a-z) or an underscore (_), followed
by letters, digits (0-9), or underscores. Python keywords cannot be used as identifiers.
python
Copy code
if b == 0:
return a
else:
return gcd(b, a % b)
# Example usage
python
Copy code
def even_length_words(sentence):
words = sentence.split()
if len(word) % 2 == 0:
print(word)
# Example usage
even_length_words(sentence)
Easy to learn: Python has a simple syntax that is easy to understand and write.
Versatile: Python can be used for web development, data science, automation, machine
learning, etc.
Large Standard Library: It comes with a vast library of modules and packages.
Cross-Platform: Python runs on different operating systems like Windows, Mac, and Linux.
Community Support: Python has a huge community, providing a wealth of resources and
third-party tools.
Mutability:
Syntax:
Performance:
A dry run refers to manually going through the code without actually executing it in the
Python interpreter. You simulate the flow of the program, tracing the values of variables and
the behavior of control structures (like loops and conditions), to understand the logic and
find any issues or errors before running the program.
b) What is the purpose of selection statements in Python?
Selection statements are used to control the flow of a program by making decisions. In
Python, the main selection statement is the if-elif-else construct, which allows a program to
execute certain blocks of code based on specific conditions being true or false.
Required arguments are the arguments that must be passed to a function when it is called. If
you define a function with certain parameters and those parameters do not have default
values, Python will raise an error if the corresponding arguments are not provided.
For example:
python
Copy code
return a + b
time.sleep(seconds): Pauses the execution of the program for the specified number of
seconds.
python
Copy code
import time
time.time(): Returns the current time in seconds since the Epoch (usually January 1, 1970,
00:00:00 UTC).
python
Copy code
current_time = time.time()
print(current_time) # Prints the current timestamp
Text files: These files store data in human-readable form using characters. Common
extensions are .txt, .csv, etc.
Binary files: These files store data in binary (0s and 1s), typically used for non-text data like
images, audio, etc. Common extensions include .jpg, .png, .exe, etc.
seek(): Changes the position of the file pointer to a specific location in the file.
python
Copy code
python
Copy code
python
Copy code
try:
x = 10 / 0
except ZeroDivisionError:
python
Copy code
my_list = [1, 2, 3]
my_list.append(4) # [1, 2, 3, 4]
python
Copy code
my_list = [3, 1, 4, 2]
my_list.sort() # [1, 2, 3, 4]
In Python, backward indexing refers to indexing from the end of the string using negative
indices. The last character of the string is at index -1, the second-last at -2, and so on.
python
Copy code
my_string = "Python"
e) Define identifiers.
Identifiers are names used to identify variables, functions, classes, modules, and other
objects in Python. Identifiers must start with a letter (A-Z or a-z) or an underscore (_), followed
by letters, digits (0-9), or underscores. Python keywords cannot be used as identifiers.
b) Python Program to find GCD of a number using recursion:
python
Copy code
if b == 0:
return a
else:
return gcd(b, a % b)
# Example usage
python
Copy code
def even_length_words(sentence):
words = sentence.split()
if len(word) % 2 == 0:
print(word)
# Example usage
even_length_words(sentence)
Easy to learn: Python has a simple syntax that is easy to understand and write.
Versatile: Python can be used for web development, data science, automation, machine
learning, etc.
Large Standard Library: It comes with a vast library of modules and packages.
Cross-Platform: Python runs on different operating systems like Windows, Mac, and Linux.
Community Support: Python has a huge community, providing a wealth of resources and
third-party tools.
Mutability:
Syntax:
Performance: