0% found this document useful (0 votes)
27 views9 pages

Types of Type Conversion in Python

The document discusses Python programming concepts like dry run, selection statements, type conversion, the pass statement, functions like enumerate() and extend(), exception handling, regular expressions, built-in list functions, string indexing, and identifiers. It also includes examples of Armstrong number checking, using lambda for anonymous functions, filtering words by length, handling zero division errors, and calculating GCD recursively.

Uploaded by

fakescout007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views9 pages

Types of Type Conversion in Python

The document discusses Python programming concepts like dry run, selection statements, type conversion, the pass statement, functions like enumerate() and extend(), exception handling, regular expressions, built-in list functions, string indexing, and identifiers. It also includes examples of Armstrong number checking, using lambda for anonymous functions, filtering words by length, handling zero division errors, and calculating GCD recursively.

Uploaded by

fakescout007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

🐍

Python
1 Marks Questions
a) What is dry run in Python?
Answer:

A dry run in Python refers to the process of mentally or manually simulating


the execution of a piece of code without actually running it on a computer. It
is a technique used by programmers to understand and analyze the flow of
the program, identify potential errors, and verify the logic without the need for
actual execution. During a dry run, variables and their values are tracked
step by step, and the program's behavior is traced without executing the
code on a computer.

b) Give the purpose of selection statements in Python.


Answer:

Selection statements in Python, such as if , elif (else if), and else , serve
the purpose of controlling the flow of a program based on certain conditions.
They allow the program to make decisions and execute different blocks of
code depending on whether a given condition is true or false. Selection
statements enable developers to implement conditional logic, making
programs more dynamic and responsive to different scenarios.

c) List the types of type conversion in Python.


Answer:

The types of type conversion in Python are:

1. Implicit Type Conversion (or Coercion): Automatically performed by


the interpreter.

2. Explicit Type Conversion (or Casting): Manually performed by the


programmer using functions like int() , float() , str() , etc.

Python 1
d) What is the use of the pass statement?
Answer:

The pass statement in Python is a no-operation statement. It serves as a


placeholder or a do-nothing statement when syntactically some code is
required, but no action is desired or necessary. It is often used as a
temporary placeholder during development to avoid syntax errors.

e) Explain the function enumerate() .


Answer:

The enumerate() function in Python is used to iterate over a sequence (such


as a list, tuple, or string) while keeping track of both the index and the
corresponding value of each item. It returns pairs of index and item as
tuples. This function is commonly used in for loops when you need both the
index and the value of each element.

f) Explain the extend method of a list.


Answer:

The extend() method in Python is used to append the elements of an


iterable (e.g., a list, tuple, or string) to the end of an existing list. It modifies
the original list by adding elements from the iterable.

g) What are required arguments in a function?


Answer:

Required arguments in a function are the parameters that must be passed


during a function call for it to execute successfully. They are mandatory, and
the number of arguments passed must match the number of parameters
defined in the function.

h) Explain any 2 functions in the time module.


Answer:

Two functions in the time module:

1. [Link](): Returns the current time in seconds since the epoch


(January 1, 1970, 00:00:00 UTC).

Python 2
2. : Suspends the execution of the current thread for the
[Link](seconds)

specified number of seconds.

i) What are the types of files in Python?


Answer:

The types of files in Python include:

1. Text Files ( 't' or default): Contain human-readable text and are


opened in text mode.

2. Binary Files ( 'b' ): Contain non-human-readable data (e.g., images,


executables) and are opened in binary mode.

j) Write the use of seek & tell functions.


Answer:

The seek(offset, whence) function is used to change the current file position
in a file, and the tell() function returns the current file position.

2 Marks Questions
a) How to handle exception in Python?
Answer:

Exception handling in Python is done using the try , except , else , and
finally blocks.

try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError as e:
# Handling specific exception
print(f"Error: {e}")
except Exception as e:
# Handling other exceptions
print(f"An error occurred: {e}")
else:
# Code to execute if no exception occurred

Python 3
print("No exception occurred.")
finally:
# Code that will be executed in any case
print("Finally block.")

b) Explain any 2 metacharacters used in regular expression.


Answer:

1. . (Dot): Matches any character except a newline ( \n ). For example, the


pattern a. would match "ab," "ac," etc.

2. (Asterisk): Matches zero or more occurrences of the preceding character


or group. For example, the pattern ab* would match "a," "ab," "abb," and so
on.

c) Explain any 2 built-in list functions.


Answer:

1. len() : Returns the number of elements in a list.

my_list = [1, 2, 3, 4, 5]
length = len(my_list) # Result: 5

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

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

d) Explain backward indexing in strings.


Answer:

Backward indexing in strings allows accessing characters from the end of the
string using negative indices. The last character has index 1 , the second-to-
last has index 2 , and so on.

Python 4
my_string = "Hello"
last_char = my_string[-1] # Result: 'o'
second_last_char = my_string[-2] # Result: 'l'

e) Define identifiers.
Answer:

Identifiers in Python are names given to variables, functions, classes,


modules, or any other entities in the code. They follow certain rules:

Must begin with a letter (a-z, A-Z) or an underscore ( _ ).

Subsequent characters can be letters, underscores, or digits (0-9).

Case-sensitive ( variable and Variable are different identifiers).

Cannot be a reserved word (keyword) in Python.

4 Marks Questions
a) Write a Python program to check if a given number is
Armstrong.

def is_armstrong(number):
num_str = str(number)
order = len(num_str)
sum_of_digits = sum(int(digit) ** order for digit in num_
return sum_of_digits == number

# Example usage:
num = 153
if is_armstrong(num):
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.")

Python 5
b) Write a Python program to display the power of 2 using an
anonymous function.

power_of_two = lambda x: 2 ** x

# Example usage:
exponent = 4
result = power_of_two(exponent)
print(f"2^{exponent} is {result}")

c) Write a Python program to print even-length words in a string.

def even_length_words(input_string):
words = input_string.split()
even_length_words_list = [word for word in words if len(wo
return even_length_words_list

# Example usage:
sentence = "This is a sample sentence for demonstration"
result = even_length_words(sentence)
print("Even-length words:", result)

4 Marks Questions
a) Write a Python program to check for Zero Division Error
Exception.

def divide_numbers(num1, num2):


try:
result = num1 / num2
print(f"The result of {num1} divided by {num2} is: {re
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")

Python 6
# Example usage:
divide_numbers(10, 2) # Normal division
divide_numbers(5, 0) # Division by zero error

b) Write a Python program to find the GCD of a number using


recursion.

def gcd_recursive(a, b):


if b == 0:
return a
else:
return gcd_recursive(b, a % b)

# Example usage:
num1 = 48
num2 = 18
result = gcd_recursive(num1, num2)
print(f"The GCD of {num1} and {num2} is: {result}")

c) Write a Python program to check if a given key already exists


in a dictionary.

def key_exists(dictionary, key):


return key in dictionary

# Example usage:
sample_dict = {'a': 1, 'b': 2, 'c': 3}
search_key = 'b'
if key_exists(sample_dict, search_key):
print(f"The key '{search_key}' exists in the dictionary."
else:
print(f"The key '{search_key}' does not exist in the dicti

Python 7
3 Marks Questions
a) Trace the output of the following code:

pythonCopy code
sum = 0
for i in range(12, 2, -2):
sum += i
print(sum)

Explanation:

The range(12, 2, -2) generates a sequence of numbers from 12 to 3 (exclusive)


with a step of -2.

The loop iterates over these numbers, and each value is added to the sum .

The print(sum) statement outputs the final sum.

Let's trace the loop:

Iteration 1: sum += 12 (sum is now 12)

Iteration 2: sum += 10 (sum is now 22)

Iteration 3: sum += 8 (sum is now 30)

Iteration 4: sum += 6 (sum is now 36)

Iteration 5: sum += 4 (sum is now 40)

Iteration 6: sum += 2 (sum is now 42)

So, the output of the code is 42 .

b) Trace the output of the following code:

pythonCopy code
count = 1
def doThis():
global count
for i in (1, 2, 3):
count += 1
doThis()

Python 8
print(count)

Explanation:

The function doThis is defined, which contains a for loop iterating over the
values (1, 2, 3).

The global variable count is incremented by 1 for each iteration in the loop.

The function doThis is then called.

After calling the function, the print(count) statement outputs the final value of
count .

Let's trace the code:

Inside doThis :

Iteration 1: count += 1 (count is now 2)

Iteration 2: count += 1 (count is now 3)

Iteration 3: count += 1 (count is now 4)

After calling doThis , the final value of count is 4.

So, the output of the code is 4 .

Python 9

Common questions

Powered by AI

The pass statement in Python is significant because it serves as a placeholder or a do-nothing statement that is syntactically necessary in certain places of the code, where the syntax requires a statement but no action is desired . This is particularly useful during development when the programmer is working on a larger piece of code and wants to leave a part of the code to be implemented later, avoiding syntax errors by using pass .

The seek() function is used to change the current file's position to a specified location, allowing for random access read/write operations within a file . This facilitates tasks such as skipping to specific parts of a file or updating data at a desired point without reading through all preceding content. The tell() function complements this by returning the current file position, which is crucial for tracking operation progress and managing file pointer locations accurately . Together, they enable precise navigation and manipulation of file contents, essential for effective data handling in applications with complex file processing needs .

Dry running a code segment is crucial because it allows programmers to mentally or manually simulate the execution of the code, tracing variables and logic step-by-step without actual execution on a computer . This process helps in identifying logic errors, understanding the program's flow, and verifying the intended behavior before running the code on a machine, potentially saving time and resources .

In Python regular expressions, the metacharacter '.' matches any single character except newline characters, making it versatile for pattern matching when the exact character is not critical. For example, the pattern 'a.' would match strings like "ab" and "ac" . The '*' metacharacter matches zero or more occurrences of the preceding element, allowing patterns to be flexible in matching varying numbers of repetitions. For example, 'ab*' would match "a", "ab", and "abb" . These metacharacters enable complex pattern constructs and powerful search functionalities in string operations .

The time.time() function returns the current time in seconds since the epoch, which can be used to track elapsed time for operations . On the other hand, time.sleep() pauses execution for a specified amount of time, allowing developers to manage task scheduling by inserting deliberate waits between operations based on time elapsed, ensuring tasks execute at desired intervals . Together, they enable precise management of task timing and control within programs .

Selection statements in Python, such as if, elif, and else, enhance the dynamic behavior of programs by allowing them to control the flow of execution based on conditions . These statements enable programs to execute different actions depending on whether a condition is true or false. For example, using "if temperature > 30: print('Hot day')" allows a program to react dynamically based on input conditions, like temperature values .

Backward indexing in strings allows accessing elements starting from the last character using negative indices, which provides flexibility in scenarios requiring reverse traversal or locating characters without knowing the string length . This technique simplifies accessing the tail end of strings, like extracting file extensions or suffixes. However, challenges include potential confusion due to negative indexing, requiring careful tracking to avoid off-by-one errors, especially in dynamically changing strings or during iterative operations . It necessitates a clear understanding of the index system to leverage its advantages efficiently without introducing logical bugs .

Text file mode in Python is used for reading and writing human-readable content, which is interpreted as strings, facilitating straightforward text processing tasks like reading from or writing to .txt files . Binary file mode, in contrast, reads and writes non-human-readable data, which is stored as bytes, making it ideal for handling tasks involving media files like images, audio, or executables where precision and byte-specific operations are crucial . These modes provide flexibility in file operations, optimizing storage and interpretation depending on data nature .

Implicit type conversion, or coercion, is performed automatically by the Python interpreter to align the types of operands when required . It typically occurs in operations where different data types are involved, like adding an integer to a float resulting in a float output. Explicit type conversion, or casting, is manually done by programmers using conversion functions like int(), float(), str(), etc., and is often used when specific conversion is needed to meet the logic requirements of the program, such as converting user input strings into numbers for arithmetic operations .

The enumerate() function is important because it allows iterating over sequences while maintaining both the index and the corresponding value of each item, which is especially useful when the index is also needed in computations or further processing . Unlike a regular for loop which only provides the elements, enumerate() enriches the loop by producing pairs of index and item as a tuple, facilitating more complex operations that depend on item positions in the sequence .

You might also like