0% found this document useful (0 votes)
2 views

Python

The document provides an overview of various Python programming concepts, including comments, string methods, functions like range() and index(), exception handling, file operations, and data structures such as lists and dictionaries. It also covers advanced topics like lambda functions, packages, and regular expressions. Additionally, it includes examples and explanations for each concept to aid understanding.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python

The document provides an overview of various Python programming concepts, including comments, string methods, functions like range() and index(), exception handling, file operations, and data structures such as lists and dictionaries. It also covers advanced topics like lambda functions, packages, and regular expressions. Additionally, it includes examples and explanations for each concept to aid understanding.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

IMP__

a) How are comments written in 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

# This is a single-line comment

b) Give the use of index() in string.

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

text = "hello world"

index_position = text.index("world") # Returns 6

c) Explain the range() function and its parameters.

The range() function generates a sequence of numbers. It can take up to three parameters:

start: The starting value (optional, defaults to 0).

stop: The ending value (exclusive).

step: The increment (optional, defaults to 1).

python

Copy code

range(5) # [0, 1, 2, 3, 4]

range(2, 10) # [2, 3, 4, 5, 6, 7, 8, 9]

range(1, 10, 2) # [1, 3, 5, 7, 9]

d) How to create a void function in Python?


A void function is a function that doesn't return a value. In Python, you define it with def and
omit the return statement.

python

Copy code

def print_message():

print("This is a void function")

g) What does the following functions return - clock() and gmtime()?

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

print(time.gmtime()) # Example: time.struct_time(tm_year=2024, tm_mon=10, tm_mday=10,


...)

h) List the syntax for handling exceptions.

The syntax for handling exceptions in Python is done using try, except, and optionally finally.

python

Copy code

try:

# code that may raise an exception

except ExceptionType:

# code to handle the exception

finally:

# optional block that runs whether an exception occurred or not

i) List any two functions in math module.


math.sqrt(x): Returns the square root of x.

math.factorial(x): Returns the factorial of x.

j) Explain the function enumerate().

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

fruits = ['apple', 'banana', 'cherry']

for index, fruit in enumerate(fruits):

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.

read(): Reads the entire content of the file as a single string.

python

Copy code

with open('file.txt', 'r') as file:

content = file.read()

print(content)

readline(): Reads a single line from the file.

python

Copy code

with open('file.txt', 'r') as file:

line = file.readline()
print(line)

b) What are the usage of dictionary copy(), get(), items(), and keys() methods?

copy(): Returns a shallow copy of the dictionary.

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.

keys(): Returns a view object displaying the keys in the dictionary.

python

Copy code

my_dict = {'a': 1, 'b': 2}

print(my_dict.copy()) # {'a': 1, 'b': 2}

print(my_dict.get('a')) # 1

print(my_dict.items()) # dict_items([('a', 1), ('b', 2)])

print(my_dict.keys()) # dict_keys(['a', 'b'])

c) Explain union and intersection with example.

Union: Combines all elements from both sets, excluding duplicates.

Intersection: Includes only elements present in both sets.

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}

d) Explain the following statements:

if: Executes a block of code if a condition is true.

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

break: Exits a loop prematurely.

python

Copy code

for i in range(5):

if i == 3:

break # exits the loop when i is 3

continue: Skips the current iteration and proceeds to the next one.

python

Copy code

for i in range(5):

if i == 3:

continue # skips when i is 3

print(i)

e) List features of Python.

Easy to read and write: Python has simple and clean syntax.
Dynamically typed: No need to declare variable types explicitly.

Interpreted: Code is executed line by line.

Cross-platform: Runs on multiple operating systems.

b) Write a program to display power of 2 up to a given number using an anonymous function.

python

Copy code

# Using lambda function to calculate power of 2

N=5

power_of_2 = list(map(lambda x: 2 ** x, range(N+1)))

for i, power in enumerate(power_of_2):

print(f"2 raised to {i} is {power}")

a) Write a python program to count vowels and consonants in a string.

python

Copy code

def count_vowels_consonants(string):

vowels = "aeiouAEIOU"

v_count = c_count = 0

for char in string:

if char.isalpha():

if char in vowels:

v_count += 1

else:

c_count += 1

return v_count, c_count


string = "hello"

v, c = count_vowels_consonants(string)

print(f"Vowels: {v}, Consonants: {c}")

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

for char in string:

if char.isupper():

upper += 1

elif char.islower():

lower += 1

return upper, lower

string = "Hello World"

u, l = count_upper_lower(string)

print(f"Uppercase letters: {u}, Lowercase letters: {l}")

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.

b) Code to print the elements of the list:

python

Copy code
my_list = [10, 20, 30, 40, 50]

for element in my_list:

print(element)

c) What is a slice operator?

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

my_list = [10, 20, 30, 40, 50]

print(my_list[1:4]) # Output: [20, 30, 40]

d) What is a variable-length argument?

A variable-length argument allows you to pass a varying number of arguments to a function.


In Python, it is done using *args for non-keyword arguments and **kwargs for keyword
arguments.

Example:

python

Copy code

def sum_of_numbers(*args):

return sum(args)

print(sum_of_numbers(10, 20, 30)) # Output: 60

f) Explain the remove() method.

The remove() method is used to remove the first occurrence of a specified element from a
list.

Example:
python

Copy code

my_list = [10, 20, 30, 40, 20]

my_list.remove(20)

print(my_list) # Output: [10, 30, 40, 20]

i) List the methods of the re package.

Some common methods in the re (regular expression) package are:

re.match()

re.search()

re.findall()

re.sub()

re.split()

re.compile()

j) What is wb mode in file?

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.

g) Write a lambda function to add 10 to a given integer:

python

Copy code

add_10 = lambda x: x + 10

print(add_10(5)) # Output: 15

a) What is a package? Explain with example how to create a package.

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:

Create a directory structure:


markdown

Copy code

mypackage/

__init__.py

module1.py

module2.py

In module1.py, you can define:

python

Copy code

def hello():

print("Hello from module1")

You can import the package like this:

python

Copy code

from mypackage import module1

module1.hello() # Output: Hello from module1

b) Usage of tuples: zip(), tuple(), count(), and index() functions.

zip(): Combines two or more sequences into tuples.

python

Copy code

a = (1, 2, 3)

b = (4, 5, 6)

zipped = zip(a, b)

print(list(zipped)) # Output: [(1, 4), (2, 5), (3, 6)]

tuple(): Converts an iterable into a tuple.


python

Copy code

my_tuple = tuple([1, 2, 3])

print(my_tuple) # Output: (1, 2, 3)

count(): Returns the number of occurrences of a value in a tuple.

python

Copy code

my_tuple = (1, 2, 2, 3)

print(my_tuple.count(2)) # Output: 2

index(): Returns the index of the first occurrence of a value.

python

Copy code

my_tuple = (1, 2, 3)

print(my_tuple.index(2)) # Output: 1

c) What is an anonymous function? How to create it? Explain with example.

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

print(add(3, 5)) # Output: 8

d) Explain the following loops with example.

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):

if age < 18:

raise AgeException("Age must be at least 18!")

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))

print(is_allowed_string("Hello123")) # Output: True

print(is_allowed_string("Hello@123")) # Output: False

Python program to extract year, month, date, and time using Lambda:

python

Copy code

from datetime import datetime

now = datetime.now()

get_year = lambda dt: dt.year

get_month = lambda dt: dt.month

get_day = lambda dt: dt.day

get_time = lambda dt: dt.strftime("%H:%M:%S")

print(get_year(now)) # Output: (current year)


print(get_month(now)) # Output: (current month)

print(get_day(now)) # Output: (current day)

print(get_time(now)) # Output: (current time in HH:MM:SS format)

a) What is a dry run in Python?

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.

g) What are required arguments in a function?

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

def add(a, b):

return a + b

# Calling the function with the required arguments

result = add(5, 10) # Works fine

h) Explain any 2 functions in the time module.

time.sleep(seconds): Pauses the execution of the program for the specified number of
seconds.

python

Copy code
import time

time.sleep(2) # Pauses the program for 2 seconds

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

i) What are the types of files in Python?

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.

j) Write the use of seek & tell function.

seek(): Changes the position of the file pointer to a specific location in the file.

python

Copy code

file.seek(0) # Move the file pointer to the beginning of the file

tell(): Returns the current position of the file pointer.

python

Copy code

position = file.tell() # Returns the current position of the file pointer

a) How to handle exceptions in Python?

Exceptions in Python are handled using the try-except block:

python

Copy code

try:
# Code that may raise an exception

x = 10 / 0

except ZeroDivisionError:

# Code to handle the exception

print("You can't divide by zero!")

b) Explain any 2 metacharacters used in regular expression.

^ (caret): Matches the start of a string.

Example: ^abc will match any string starting with "abc".

$ (dollar): Matches the end of a string.

Example: abc$ will match any string ending with "abc".

c) Explain any 2 built-in list functions.

append(): Adds an element to the end of a list.

python

Copy code

my_list = [1, 2, 3]

my_list.append(4) # [1, 2, 3, 4]

sort(): Sorts the elements of a list in ascending order (by default).

python

Copy code

my_list = [3, 1, 4, 2]

my_list.sort() # [1, 2, 3, 4]

d) Explain backward indexing in strings.

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"

print(my_string[-1]) # Output: 'n'

print(my_string[-2]) # Output: 'o'

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

def gcd(a, b):

if b == 0:

return a

else:

return gcd(b, a % b)

# Example usage

print(gcd(60, 48)) # Output: 12

c) Python Program to print even-length words in a string:

python

Copy code

def even_length_words(sentence):

words = sentence.split()

for word in words:

if len(word) % 2 == 0:

print(word)
# Example usage

sentence = "Python is an amazing programming language"

even_length_words(sentence)

a) What are the advantages of Python?

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.

b) Differences between Lists & Tuples:

Mutability:

Lists: Mutable (can be changed after creation).

Tuples: Immutable (cannot be changed after creation).

Syntax:

Lists: Defined using square brackets [].

Tuples: Defined using parentheses ().

Performance:

Lists: Slower as they are mutable.

Tuples: Faster due to immutability.

a) What is a dry run in Python?

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.

g) What are required arguments in a function?

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

def add(a, b):

return a + b

# Calling the function with the required arguments

result = add(5, 10) # Works fine

h) Explain any 2 functions in the time module.

time.sleep(seconds): Pauses the execution of the program for the specified number of
seconds.

python

Copy code

import time

time.sleep(2) # Pauses the program for 2 seconds

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

i) What are the types of files in Python?

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.

j) Write the use of seek & tell function.

seek(): Changes the position of the file pointer to a specific location in the file.

python

Copy code

file.seek(0) # Move the file pointer to the beginning of the file

tell(): Returns the current position of the file pointer.

python

Copy code

position = file.tell() # Returns the current position of the file pointer

a) How to handle exceptions in Python?

Exceptions in Python are handled using the try-except block:

python

Copy code

try:

# Code that may raise an exception

x = 10 / 0

except ZeroDivisionError:

# Code to handle the exception

print("You can't divide by zero!")

b) Explain any 2 metacharacters used in regular expression.


^ (caret): Matches the start of a string.

Example: ^abc will match any string starting with "abc".

$ (dollar): Matches the end of a string.

Example: abc$ will match any string ending with "abc".

c) Explain any 2 built-in list functions.

append(): Adds an element to the end of a list.

python

Copy code

my_list = [1, 2, 3]

my_list.append(4) # [1, 2, 3, 4]

sort(): Sorts the elements of a list in ascending order (by default).

python

Copy code

my_list = [3, 1, 4, 2]

my_list.sort() # [1, 2, 3, 4]

d) Explain backward indexing in strings.

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"

print(my_string[-1]) # Output: 'n'

print(my_string[-2]) # Output: 'o'

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

def gcd(a, b):

if b == 0:

return a

else:

return gcd(b, a % b)

# Example usage

print(gcd(60, 48)) # Output: 12

c) Python Program to print even-length words in a string:

python

Copy code

def even_length_words(sentence):

words = sentence.split()

for word in words:

if len(word) % 2 == 0:

print(word)

# Example usage

sentence = "Python is an amazing programming language"

even_length_words(sentence)

a) What are the advantages of Python?

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.

b) Differences between Lists & Tuples:

Mutability:

Lists: Mutable (can be changed after creation).

Tuples: Immutable (cannot be changed after creation).

Syntax:

Lists: Defined using square brackets [].

Tuples: Defined using parentheses ().

Performance:

Lists: Slower as they are mutable.

Tuples: Faster due to immutability.

You might also like