Python Programming Aug 2022
Python Programming Aug 2022
|''|''|||''|'''|||'|
Code No: R201225 R20 SET - 2
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
2. **High-level Language:**
Python abstracts many low-level details, providing a more user-friendly experience. This means developers
can focus on the logic of their code rather than worrying about system-specific implementations.
3. **Interpreted Language:**
Python is an interpreted language, meaning that code is executed line-by-line rather than being compiled into
machine code. This allows for quicker development and easier debugging.
4. **Dynamic Typing:**
Python uses dynamic typing, where variables are not bound to a specific data type during declaration. The
data type is inferred at runtime, providing flexibility but requiring careful attention to variable assignments.
7. **Cross-platform Compatibility:**
Python code can run on different platforms (Windows, macOS, Linux) without modification, making it a
highly portable language.
|''|''|||''|'''|||'|
Code No: R201225 R20 SET - 3
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
In addition to the standard library, Python has an extensive ecosystem of third-party libraries and packages.
These open-source contributions extend Python's capabilities for specific domains such as data science
(NumPy, Pandas), web development (Django, Flask), and machine learning (TensorFlow, PyTorch).
Overall, these features make Python a versatile, user-friendly, and powerful programming language, suitable
for a wide range of applications and skill levels.
1b )What is a Conditional statement in Python programming? Give the syntax of various Conditional
structures available in Python programming.
In Python programming, a conditional statement allows the execution of different code blocks based on the
evaluation of certain conditions. It helps control the flow of the program, enabling you to make decisions
based on whether a condition is true or false.
1. **if statement:**
The `if` statement is used to execute a block of code if a given condition is true.
Syntax:
```python
if condition:
|''|''|||''|'''|||'|
Code No: R201225 R20 SET - 4
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
# code to be executed if the condition is true
```
Example:
```python
x = 10
if x > 5:
print("x is greater than 5")
```
2. **if-else statement:**
The `if-else` statement allows you to execute one block of code when the condition is true and another block
when the condition is false.
Syntax:
```python
if condition:
# code to be executed if the condition is true
else:
# code to be executed if the condition is false
```
Example:
```python
x=7
if x > 10:
print("x is greater than 10")
else:
print("x is not greater than 10")
```
3. **if-elif-else statement:**
The `if-elif-else` statement lets you evaluate multiple conditions and execute different code blocks based on
which condition is true first. It is useful when you have more than two possible outcomes.
Syntax:
```python
if condition1:
# code to be executed if condition1 is true
elif condition2:
# code to be executed if condition2 is true
else:
# code to be executed if both condition1 and condition2 are false
```
Example:
|''|''|||''|'''|||'|
Code No: R201225 R20 SET - 5
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
```python
x=5
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but not greater than 10")
else:
print("x is not greater than 5")
```
4. **Nested if statements:**
You can also nest conditional statements, which means having one if statement inside another.
Syntax:
```python
if condition1:
# code to be executed if condition1 is true
if condition2:
# code to be executed if both condition1 and condition2 are true
else:
# code to be executed if condition1 is true, but condition2 is false
else:
# code to be executed if condition1 is false
```
Example:
```python
x = 15
if x > 10:
if x > 20:
print("x is greater than 20")
else:
print("x is greater than 10 but not greater than 20")
else:
print("x is not greater than 10")
```
These conditional structures are fundamental for controlling the flow of your Python programs based on
different conditions and situations.
2 a) How to access the characters in Python String? Write a Python program to demonstrate it
In Python, you can access individual characters in a string using indexing. String indexing starts from 0, where the
first character has an index of 0, the second character has an index of 1, and so on. You can also use negative
indexing to access characters from the end of the string, where -1 represents the last character.
|''|''|||''|'''|||'|
Code No: R201225 R20 SET - 6
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
```python
# Define a sample string
my_string = "Hello, Python!"
Output:
```
First character: H
Second character: e
Last character: !
Substring 1: Python
Substring 2: Hello
Substring 3: Python!
```
In the program above, we defined a sample string `my_string` and accessed its characters using both positive and
negative indexing. We also demonstrated slicing to extract substrings from the original string.
Keep in mind that strings in Python are immutable, meaning you cannot change individual characters once the
string is created. However, you can create new strings by concatenating or manipulating existing ones.
```python
# Logical Operators: and, or, not
|''|''|||''|'''|||'|
Code No: R201225 R20 SET - 7
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
def logical_operators_demo(a, b):
print("Logical Operators Demo:")
print(f"a = {a}, b = {b}")
print("a and b:", a and b)
print("a or b:", a or b)
print("not a:", not a)
print("not b:", not b)
print()
print("my_list:", my_list)
print("3 in my_list:", 3 in my_list)
print("6 in my_list:", 6 in my_list)
print("3 not in my_list:", 3 not in my_list)
print("6 not in my_list:", 6 not in my_list)
print()
if __name__ == "__main__":
# Logical Operators
logical_operators_demo(True, False)
# Membership Operators
membership_operators_demo()
# Identity Operators
a = [1, 2, 3]
b=a
c = [1, 2, 3]
identity_operators_demo(a, b)
identity_operators_demo(a, c)
```
|''|''|||''|'''|||'|
Code No: R201225 R20 SET - 8
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
Output:
```
Logical Operators Demo:
a = True, b = False
a and b: False
a or b: True
not a: False
not b: True
In the program above, we have three functions to demonstrate the usage of different operators:
1. `logical_operators_demo(a, b)`: This function demonstrates the logical operators `and`, `or`, and `not`.
2. `membership_operators_demo()`: This function demonstrates the membership operators `in` and `not in` with a
sample list.
3. `identity_operators_demo(x, y)`: This function demonstrates the identity operators `is` and `is not` with
different objects.
Each section of the program provides sample inputs and shows the results of applying the corresponding
operators.
3 a) Write the syntax of various Loop statements supported by Python programming and explain their
execution behavior with neat flow diagrams.
In Python, there are two main types of loop statements: `for` loop and `while` loop. These loops allow you to
|''|''|||''|'''|||'|
Code No: R201225 R20 SET - 9
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
execute a block of code repeatedly based on certain conditions. Let's look at the syntax and execution behavior of
both loop statements along with flow diagrams.
1. **For Loop:**
The `for` loop is used when you know the number of iterations or want to iterate over elements in a sequence (like a
list, tuple, string, etc.).
Syntax:
```python
for variable in sequence:
# code to be executed for each iteration
```
Flow Diagram:
```
+--------------------------------------------------+
| Initialize |
| |
| +--------------------------------------+----+
| | Is there any more | |
| +------> element in sequence? YES |
| | | | |
| | | +--------------------------+ |
| | | | | |
| | | v | |
| | | Execute | |
| | | code block | |
| | | | | |
| | | v | |
| | | +--------------------------+ |
| | | | |
| | | +---------------------------+ | |
| | | | | | |
| | +--------+ | | |
| | | | | |
| +---------------+ | | |
| | | | |
+---------------------+---------------------------+ | |
| |
+------------------------------------------+ |
| |
v |
Continue |
Execution |
(Next Iteration) |
| |
|''|''|||''|'''|||'|
Code No: R201225 R20 SET -
10
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
v |
+-----------------------------------------------+
```
2. **While Loop:**
The `while` loop is used when you want to repeat a block of code as long as a given condition is true.
Syntax:
```python
while condition:
# code to be executed repeatedly while condition is true
```
Flow Diagram:
```
+--------------------------------------------------+
| Initialize |
| |
| +--------------------------------------+----+
| | Is condition true? | |
| | | |
| +------> +--------------------------+ | |
| | | | | | |
| | | v | | |
| | | Execute | | |
| | | code block | | |
| | | | | | |
| | | v | | |
| | | +--------------------------+ | |
| | | | |
| | | +------------------------------+ | |
| | | | | | |
| | +-->| Is condition still true? | | |
| | | | | |
| | +------------------------------+ | |
| | | |
| +----------------------------------------------+ |
| |
+--------------------------------------------------------+
```
In the flow diagrams, the loop execution starts by checking the condition (for `for` loop, it checks for elements in
the sequence, and for `while` loop, it checks the given condition). If the condition is true, the code block inside the
loop is executed. After executing the code block, the loop goes back to check the condition again.
For the `for` loop, the process repeats until there are no more elements in the sequence. For the `while` loop, the
|''|''|||''|'''|||'|
Code No: R201225 R20 SET -
11
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
process continues as long as the condition remains true. When the condition becomes false, the loop exits, and the
program continues with the rest of the code.
It's essential to make sure that the loop eventually terminates, as an infinite loop (where the condition never
becomes false) can lead to program freezing or crashing. You can use break or other control statements inside the
loop to exit it when necessary.
Encryption is the process of converting plaintext (human-readable data) into ciphertext (encrypted data), making it
unreadable without the appropriate decryption key. Decryption is the reverse process of converting ciphertext back
into plaintext using the decryption key. Python provides various cryptographic libraries that can be used for
encryption and decryption. One of the commonly used libraries is `cryptography`.
Here's an example of how to encrypt and decrypt strings using the `cryptography` library in Python:
First, make sure you have the `cryptography` library installed. If you don't have it, you can install it using `pip`:
```bash
pip install cryptography
```
```python
from cryptography.fernet import Fernet
def generate_key():
return Fernet.generate_key()
if __name__ == "__main__":
# Generate a random encryption key
key = generate_key()
Output:
```
Original String: This is a secret message!
Encrypted String: b'...'
Decrypted String: This is a secret message!
```
In this example, we first import the `Fernet` class from the `cryptography.fernet` module, which provides a
symmetric encryption algorithm (AES). We then define three functions:
1. `generate_key()`: This function generates a random encryption key using the `Fernet.generate_key()` method.
2. `encrypt_string(key, plaintext)`: This function takes the encryption key and plaintext string as input, and it
encrypts the plaintext using the `Fernet.encrypt()` method.
3. `decrypt_string(key, ciphertext)`: This function takes the encryption key and ciphertext as input and decrypts the
ciphertext back into plaintext using the `Fernet.decrypt()` method.
In the `main` part of the program, we generate a random key, encrypt a sample string, and then decrypt it back to its
original form. The encryption and decryption are done using the same key, ensuring the security and integrity of the
data.
4 a) Write a Python program to demonstrate the usage of common Python String methods.
Here's a Python program that demonstrates the usage of common string methods:
```python
def common_string_methods_demo(input_string):
print("Original String:", input_string)
# String length
print("Length of the string:", len(input_string))
if __name__ == "__main__":
input_string = "Hello, Python!"
common_string_methods_demo(input_string)
```
Output:
```
|''|''|||''|'''|||'|
Code No: R201225 R20 SET -
14
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
Original String: Hello, Python!
Length of the string: 15
Uppercase: HELLO, PYTHON!
Lowercase: hello, python!
Capitalized: Hello, python!
Starts with 'Hello': True
Ends with 'Python!': True
Occurrences of 'l' in the string: 2
Replace 'Hello' with 'Hi': Hi, Python!
Index of 'Python': 7
Split list: ['Hello', 'Python!']
Joined string: Hello-Python!
Is alphanumeric? False
Is alphabetic? False
Is numeric? False
Is whitespace? False
```
In the `main` part of the program, we call the `common_string_methods_demo()` function with a sample input
string "Hello, Python!" to showcase the usage of these methods.
4 b) Develop a Python program to display the Fibonacci series between 0 and 100.
Sure! The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones,
usually starting with 0 and 1. Let's develop a Python program to display the Fibonacci series between 0 and 100:
|''|''|||''|'''|||'|
Code No: R201225 R20 SET -
15
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
```python
def fibonacci_series(limit):
# Initialize the first two numbers of the series
a, b = 0, 1
if __name__ == "__main__":
upper_limit = 100
print("Fibonacci series up to 100:")
fibonacci_series(upper_limit)
```
Output:
```
Fibonacci series up to 100:
0 1 1 2 3 5 8 13 21 34 55 89
```
In this program, we define a function called `fibonacci_series(limit)` that takes a limit as input and prints the
Fibonacci series up to that limit. We start with the first two numbers of the series, 0 and 1, and use a while loop to
generate and print the rest of the series until the next number exceeds the given limit.
The `a` and `b` variables hold the last two numbers of the series, and the `c` variable represents the next number to
be printed. We continuously calculate the next number `c` by adding the last two numbers (`a` and `b`), and then
update `a` and `b` to move to the next iteration.
The loop continues until the next number `c` exceeds the specified limit. At that point, the loop breaks, and the
program stops generating numbers in the Fibonacci series.
5 a) List out various Python List Built-in methods and write a program to demonstrate their usage.
Python provides several built-in methods for lists, which allow you to manipulate and work with lists effectively.
Here's a list of some common built-in methods for lists and a Python program that demonstrates their usage:
|''|''|||''|'''|||'|
Code No: R201225 R20 SET -
16
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
1. `append(x)`: Adds an element `x` to the end of the list.
2. `extend(iterable)`: Extends the list by appending elements from the iterable.
3. `insert(i, x)`: Inserts element `x` at index `i`.
4. `remove(x)`: Removes the first occurrence of element `x`.
5. `pop(i)`: Removes and returns the element at index `i`.
6. `index(x)`: Returns the index of the first occurrence of element `x`.
7. `count(x)`: Returns the number of occurrences of element `x`.
8. `sort()`: Sorts the list in ascending order.
9. `reverse()`: Reverses the elements of the list in-place.
10. `clear()`: Removes all elements from the list.
Now, let's write a Python program to demonstrate the usage of these list methods:
```python
def demonstrate_list_methods():
# Create an empty list
my_list = []
|''|''|||''|'''|||'|
Code No: R201225 R20 SET -
17
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
# Count the occurrences of an element
count_of_30 = my_list.count(30)
print("Occurrences of 30:", count_of_30)
if __name__ == "__main__":
demonstrate_list_methods()
```
Output:
```
After appending elements: [10, 20, 30]
After extending the list: [10, 20, 30, 40, 50]
After inserting 25 at index 2: [10, 20, 25, 30, 40, 50]
After removing 20: [10, 25, 30, 40, 50]
Popped element: 30
After popping element at index 3: [10, 25, 40, 50]
Index of 30: 2
Occurrences of 30: 1
Sorted list: [10, 25, 40, 50]
Reversed list: [50, 40, 25, 10]
After clearing the list: []
```
In the program above, we define a function called `demonstrate_list_methods()` that demonstrates the usage of
various list methods. We start with an empty list (`my_list`) and sequentially apply each method to show how the
list changes after each operation. The output displays the list after each method call.
5 b) Write a Python function to print the even numbers from a given list.
Here's a Python function that takes a list as input and prints only the even numbers from that list:
```python
def print_even_numbers(input_list):
|''|''|||''|'''|||'|
Code No: R201225 R20 SET -
18
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
even_numbers = [num for num in input_list if num % 2 == 0]
print("Even numbers:", even_numbers)
if __name__ == "__main__":
# Example list
numbers_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print_even_numbers(numbers_list)
```
Output:
```
Even numbers: [2, 4, 6, 8, 10]
```
In this program, we define a function called `print_even_numbers(input_list)` that takes a list (`input_list`) as input.
We use a list comprehension to filter out only the even numbers from the input list by checking if the number is
divisible by 2 (i.e., `num % 2 == 0`). The resulting even numbers are stored in the `even_numbers` list, which is
then printed to the console.
In the example, we call the `print_even_numbers()` function with a sample list `numbers_list` containing numbers
from 1 to 10. The function prints the even numbers from that list as output.
In Python, a nested dictionary is a dictionary that contains other dictionaries as values. You can access the elements
of a nested dictionary by chaining the keys together using multiple square brackets.
Here's a Python program that demonstrates how to access the elements of a nested dictionary:
```python
def access_nested_dict(nested_dict, keys_list):
current_dict = nested_dict
return current_dict
if __name__ == "__main__":
# Example nested dictionary
|''|''|||''|'''|||'|
Code No: R201225 R20 SET -
19
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
nested_dict = {
"first_level": {
"second_level": {
"third_level": "Hello, Python!"
}
},
"other_data": "This is some other data."
}
Output:
```
Element value: Hello, Python!
```
In this program, we define a function called `access_nested_dict(nested_dict, keys_list)` that takes a nested
dictionary `nested_dict` and a list of keys `keys_list` as input. The function traverses through the keys list and
navigates through the nested dictionaries to access the desired element.
In the example, we have a nested dictionary called `nested_dict`, and we want to access the element with the keys
`["first_level", "second_level", "third_level"]`, which has the value "Hello, Python!". The function
`access_nested_dict()` is called with the nested dictionary and the keys list, and it returns the element's value. The
program then prints the value to the console.
6 b) What are Python modules? Explain the steps to import specific attributes from a module into the
current Namespace with appropriate code snippets.
In Python, a module is a file containing Python definitions and statements. It can include functions, classes, and
variables that can be used in other Python programs. Modules are used to organize code and make it more reusable.
Python provides a wide range of built-in modules that you can use directly, as well as the ability to create your own
custom modules.
Here's how you can import specific attributes (functions, classes, variables, etc.) from a module into the current
namespace using `import` and `from` statements:
|''|''|||''|'''|||'|
Code No: R201225 R20 SET -
20
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
1. **Importing a Module:**
To import a module, you use the `import` statement followed by the name of the module. After importing, you can
access the attributes of the module using the dot notation (`module_name.attribute_name`).
```python
# Example: Importing the math module
import math
```python
# Example: Importing specific attributes from the math module
from math import sqrt, pi
```python
# Example: Using an alias for the math module
import math as m
By importing specific attributes from a module, you can avoid name conflicts with existing variables in your
current namespace and make your code more readable and concise.
It's important to note that when you use `from module_name import *`, you import all attributes from the module
into the current namespace. However, it's generally considered a bad practice because it can lead to name clashes
and make code maintenance difficult. It's recommended to import only the specific attributes you need, as shown in
the examples above.
|''|''|||''|'''|||'|
Code No: R201225 R20 SET -
21
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
In Python, the `read()`, `readline()`, and `readlines()` functions are used to read data from files. They are methods
of file objects and can be used after opening a file in read mode (`'r'`). Let's explain the prototypes and behaviors of
these functions:
1. **`read(size=-1)`**:
- Prototype: `file.read(size=-1)`
- Description: This method reads data from the file and returns it as a string. If the `size` argument is not
provided, or if `size` is negative, it reads the entire content of the file. If `size` is specified, it reads at most `size`
bytes from the file.
- Parameters:
- `size` (optional): The number of bytes to read from the file. Default is `-1` (read the entire file).
- Returns: A string containing the read data.
```python
# Example of read() function
with open('example.txt', 'r') as file:
content = file.read()
print(content)
```
2. **`readline(size=-1)`**:
- Prototype: `file.readline(size=-1)`
- Description: This method reads a single line from the file and returns it as a string. If the `size` argument is not
provided, or if `size` is negative, it reads the entire line. If `size` is specified, it reads at most `size` bytes from the
line.
- Parameters:
- `size` (optional): The number of bytes to read from the line. Default is `-1` (read the entire line).
- Returns: A string containing the read line.
```python
# Example of readline() function
with open('example.txt', 'r') as file:
line = file.readline()
print(line)
```
3. **`readlines(hint=-1)`**:
- Prototype: `file.readlines(hint=-1)`
- Description: This method reads all lines from the file and returns them as a list of strings. If the `hint` argument
is not provided, or if `hint` is negative, it reads all lines from the file. If `hint` is specified, it reads at most `hint`
bytes from the file.
- Parameters:
|''|''|||''|'''|||'|
Code No: R201225 R20 SET -
22
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
- `hint` (optional): The number of bytes to read from the file. Default is `-1` (read all lines).
- Returns: A list of strings, where each string represents a line from the file.
```python
# Example of readlines() function
with open('example.txt', 'r') as file:
lines = file.readlines()
print(lines)
```
In the examples above, assume that the file `example.txt` contains the following lines:
```
Hello, this is line 1.
This is line 2.
And this is line 3.
```
The `read()` function would read the entire content of the file as a single string, `readline()` would read the first line
as a string, and `readlines()` would read all lines and return them as a list of strings.
7 b) Write about Class Inheritance and demonstrate the usage of issubclass() and isinstance() methods in
Python.
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a subclass
or derived class) to inherit attributes and behaviors from another class (called a superclass or base class). The
subclass can extend or modify the functionality of the superclass while reusing its existing features. Inheritance
promotes code reusability and helps create a hierarchical relationship between classes.
In Python, a class can inherit from another class by specifying the superclass name in parentheses after the subclass
name during class definition. The syntax for class inheritance is as follows:
```python
class Superclass:
# Superclass attributes and methods
class Subclass(Superclass):
# Subclass attributes and methods
```
The `Subclass` inherits all the attributes and methods from the `Superclass`, and you can override methods or add
new ones in the `Subclass`.
1. `issubclass(class, classinfo)`: This function checks whether a class (`class`) is a subclass of another class
(`classinfo`). It returns `True` if `class` is a subclass of `classinfo`, and `False` otherwise.
2. `isinstance(object, classinfo)`: This function checks whether an object (`object`) is an instance of a specified
class (`classinfo`). It returns `True` if `object` is an instance of `classinfo`, and `False` otherwise.
```python
class Animal:
def __init__(self, species):
self.species = species
def make_sound(self):
print("Animal sound!")
class Dog(Animal):
def __init__(self, breed):
super().__init__("Dog")
self.breed = breed
def make_sound(self):
print("Woof!")
if __name__ == "__main__":
# Check subclass relationship
print(issubclass(Dog, Animal)) # Output: True
In the example above, we have a `Superclass` called `Animal` and a `Subclass` called `Dog`. The `Dog` class
inherits from the `Animal` class.
The `issubclass(Dog, Animal)` function returns `True` because `Dog` is a subclass of `Animal`.
The `isinstance(my_dog, Dog)` function returns `True` because `my_dog` is an instance of the `Dog` class.
Similarly, `isinstance(my_dog, Animal)` returns `True` because `my_dog` is also an instance of the `Animal` class.
|''|''|||''|'''|||'|
Code No: R201225 R20 SET -
24
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
This is possible because `Dog` inherits from `Animal`, making `my_dog` an instance of both classes.
8 a) How do you manipulate a file pointer in Python? Explain with a sample program.
In Python, you can manipulate the file pointer to control the current position for reading or writing data in a file.
The file pointer represents the current position within the file, and you can move it to a specific location using
various methods provided by file objects.
1. `seek(offset, whence)`: Moves the file pointer to the specified `offset` position relative to the `whence` argument.
Let's demonstrate how to manipulate the file pointer with a sample program:
```python
def file_pointer_manipulation_demo():
# Writing data to a file
with open('sample_file.txt', 'w') as file:
file.write("Hello, World!\nThis is line 2.\nAnd this is line 3.\n")
# Reading data from the file and manipulating the file pointer
with open('sample_file.txt', 'r') as file:
# Read the first line and print it
first_line = file.readline()
print("First Line:", first_line)
if __name__ == "__main__":
file_pointer_manipulation_demo()
```
Output:
```
First Line: Hello, World!
Current Position: 32
```
In this program, we demonstrate file pointer manipulation with the file `'sample_file.txt'`. We first write some
content to the file. Then, we open the file in read mode and use the `readline()` and `read()` methods to read data
from the file.
We use the `seek()` method to move the file pointer to specific positions in the file. The first `seek(0)` moves the
pointer to the beginning of the file, and the second `seek(18)` moves it to the beginning of line 2. After each file
pointer manipulation, we use the `readline()` or `read()` methods to read data from the file starting from the current
position.
Finally, we use the `tell()` method to get the current position of the file pointer and print it. In this example, the
current position is 32, which is the number of characters read so far.
Yes, Python supports operator overloading. Operator overloading allows you to define custom behavior for
standard Python operators (+, -, *, /, etc.) when used with objects of user-defined classes. This feature enables you
to make your objects behave like built-in data types, giving you more flexibility and control over their behavior.
In Python, operator overloading is achieved by defining special methods (also known as magic methods or dunder
methods) in the class definition. These methods start and end with double underscores (`__`) and have predefined
names for each operator.
For example, if you want to define custom behavior for the addition operator (`+`) when used with instances of
your class, you can define the `__add__()` method in your class. Similarly, you can define other methods such as
`__sub__()`, `__mul__()`, `__div__()`, etc., for other operators.
|''|''|||''|'''|||'|
Code No: R201225 R20 SET -
26
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
1. **Consistency and Familiarity:** Python's support for operator overloading allows user-defined classes to
behave similarly to built-in data types. For example, by overloading the `+` operator, you can concatenate strings or
add custom objects in a way that is consistent with the behavior of built-in types like strings and numbers.
2. **Code Readability and Expressiveness:** Operator overloading enhances code readability and expressiveness.
By using familiar operators with user-defined objects, you can write more intuitive and concise code, making your
programs easier to understand and maintain.
3. **Customization and Flexibility:** Operator overloading gives developers the ability to customize the behavior
of their objects. You can define your own rules for performing arithmetic, comparisons, and other operations on
your objects, providing greater flexibility and control over their usage.
4. **Built-in Function Support:** Many built-in functions and libraries in Python use operator overloading. For
example, the `sorted()` function can sort a list of objects if the class defines the `__lt__()` method for the less-than
operator (`<`).
5. **Integration with Core Features:** Python's support for operator overloading is integrated into the core
language and its object-oriented model. This makes it easier to work with custom classes in a way that feels natural
and consistent with the rest of the language.
Overall, operator overloading is a powerful feature that makes Python a versatile and expressive language for
working with custom objects and data types. It promotes code reusability, readability, and provides a way to create
more intuitive and user-friendly interfaces for your classes.
9 a) How to create, raise and handle user defined exceptions in Python? Illustrate with a Python program.
In Python, you can create, raise, and handle user-defined exceptions to handle specific error conditions or situations
in your code. User-defined exceptions allow you to define custom error classes that provide more meaningful
information about the cause of the exception.
Here's how you can create, raise, and handle user-defined exceptions in Python:
To create a user-defined exception, you need to define a new class that inherits from the `Exception` class or one of
its subclasses. You can add additional attributes or methods to the custom exception class to provide more context
about the error.
```python
# Step 1: Creating a User-Defined Exception
class MyCustomException(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
```
You can raise the user-defined exception using the `raise` statement. When a specific condition in your code is not
|''|''|||''|'''|||'|
Code No: R201225 R20 SET -
27
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
met, you can raise the custom exception to indicate the error.
```python
# Step 2: Raising the User-Defined Exception
def division_with_exception(a, b):
if b == 0:
raise MyCustomException("Division by zero is not allowed.")
return a / b
```
You can handle the user-defined exception using a `try`-`except` block. When the raised exception matches the
specified custom exception, the code inside the `except` block is executed.
```python
# Step 3: Handling the User-Defined Exception
try:
result = division_with_exception(10, 0)
except MyCustomException as e:
print("Exception:", e.message)
else:
print("Result:", result)
```
Here's the complete Python program that demonstrates the creation, raising, and handling of a user-defined
exception:
```python
# Step 1: Creating a User-Defined Exception
class MyCustomException(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
Output:
```
Exception: Division by zero is not allowed.
```
In the above program, we define a user-defined exception `MyCustomException` by inheriting from the
`Exception` class. We add an `__init__()` method to provide a custom error message for the exception.
Then, we define a function `division_with_exception(a, b)` that raises the `MyCustomException` when the `b`
value is zero (division by zero error). Finally, we use a `try`-`except` block to handle the exception and print the
custom error message when the exception is raised.
10 a) Give the syntax to create Radiobutton widget. And write a Python program to create Radiobuttons for
selecting the Gender(Male, Female, Transgender) on the same canvas._
The syntax to create a `Radiobutton` widget in Python using the Tkinter library is as follows:
```python
radiobutton = Radiobutton(parent, options...)
```
Where:
- `parent`: The parent widget or container where the `Radiobutton` will be placed.
- `options...`: The various options that can be specified for the `Radiobutton`. Some common options include `text`,
`variable`, `value`, `command`, etc.
Now, let's write a Python program to create `Radiobuttons` for selecting the gender (Male, Female, Transgender)
on the same canvas using Tkinter:
```python
import tkinter as tk
def show_selected_gender():
selected_gender = gender_var.get()
gender_label.config(text=f"Selected Gender: {selected_gender}")
In this program, we use the Tkinter library to create a simple GUI window with three `Radiobuttons` for gender
selection: Male, Female, and Transgender. We also create a label to display the selected gender.
The `gender_var` is a `StringVar` variable used to store the selected gender. The `show_selected_gender()` function
is called when any of the `Radiobuttons` are selected, and it updates the label with the selected gender.
The `pack()` method is used to place the `Radiobuttons` and the label in the main application window. The
`anchor=tk.W` option aligns the `Radiobuttons` and label to the left (west) of the window.
When you run the program, you can select one of the genders using the `Radiobuttons`, and the label will display
the selected gender.
10 b) What type of programming is Scratch? What are the different kinds of Scratch blocks?
Scratch is a visual programming language designed for beginners, especially children, to learn programming
concepts in a fun and interactive way. It is widely used for educational purposes and aims to teach computational
thinking and problem-solving skills through creative and playful programming.
Scratch allows users to create projects by dragging and snapping together graphical blocks that represent different
programming commands and actions. The blocks are combined to form scripts that control characters (sprites) on
the screen and define their behavior and interactions.
|''|''|||''|'''|||'|
Code No: R201225 R20 SET -
30
I B. Tech II Semester Regular/Supplementary Examinations, August- 2022
PYTHON PROGRAMMING
(Com. To CSE, IT, CSE-AI&ML,CSE-AI, CSE-DS, CSE-AI&DS, AI&DS )
Time: 3 hours Max. Marks: 70
Different kinds of Scratch blocks include:
1. **Motion Blocks:** These blocks control the movement and positioning of sprites on the screen. They include
blocks like "Move 10 steps," "Turn 15 degrees," "Go to random position," etc.
2. **Looks Blocks:** These blocks control the appearance and visual effects of sprites. They include blocks like
"Say," "Show," "Hide," "Change costume," etc.
3. **Sound Blocks:** These blocks control sounds and audio effects in the project. They include blocks like "Play
sound," "Stop all sounds," "Set volume," etc.
4. **Events Blocks:** These blocks trigger actions based on events or user interactions. They include blocks like
"When green flag clicked," "When key pressed," "When sprite clicked," etc.
5. **Control Blocks:** These blocks control the flow of the program and include loops and conditional statements.
They include blocks like "Repeat," "Forever," "If-Else," "Wait," etc.
6. **Sensing Blocks:** These blocks allow sprites to interact with their environment and respond to various
conditions. They include blocks like "Touching color," "Ask and wait," "Mouse X position," etc.
7. **Operators Blocks:** These blocks perform mathematical and logical operations. They include blocks like
"Add," "Subtract," "Multiply," "Less than," "And," "Or," etc.
8. **Variables Blocks:** These blocks are used to create and manipulate variables to store and retrieve data during
program execution. They include blocks like "Set variable," "Change variable," "Show variable," etc.
9. **Custom Blocks:** Scratch also allows users to create their own custom blocks by grouping a set of commands
together. This feature promotes code reusability and abstraction.
Scratch's visual interface, colorful blocks, and interactive environment make it a powerful tool for introducing
programming concepts to beginners and encouraging creativity in programming projects.
|''|''|||''|'''|||'|