Python Imp 1
Python Imp 1
Page |1
Python IMP Question and Answers
Page |2
Python IMP Question and Answers
• Web Scraping: Libraries like Beautiful Soup and Selenium can scrape data from
websites.
Example: Collecting pricing data from e-commerce sites for market analysis.
• Task Automation: Using tools like Python's schedule or cron integration to automate
periodic tasks.
Example: Sending daily reports via email.
4. Write a program to calculate the grade of students with the help of conditional
statements.
Page |3
Python IMP Question and Answers
Program
Output
Page |4
Python IMP Question and Answers
Page |5
Python IMP Question and Answers
Page |6
Python IMP Question and Answers
A structure where a tuple exclusively contains other tuples, often used for organizing
related groups of data.
7. Packed and Unpacked Tuples
Packing refers to combining multiple values into a tuple, while unpacking extracts
these values into separate variables.
8. Homogeneous Tuple
A tuple where all elements are of the same data type, typically used when working
with uniform datasets.
Tuples are immutable, which makes them reliable for fixed collections of data and
ensures data integrity.
Output
Page |7
Python IMP Question and Answers
Page |8
Python IMP Question and Answers
Page |9
Python IMP Question and Answers
Program:
# Function definition
def greet(name):
"""This function greets the person passed as an argument."""
print(f"Hello, {name}! Welcome!")
# Function call
greet("Rajashri")
P a g e | 10
Python IMP Question and Answers
print("Sum:", result)
Output:
makefile
Hello, Rajashri!
Sum: 8
import math
result = math.sqrt(16)
print(result) # Output: 4.0
Here, the math module is used to perform mathematical operations.
12. Describe various types of file modes in detail.
In Python, file modes are used to specify the actions that can be performed on a file when it is
opened. These modes are passed as arguments to the open() function. Here are the various
types of file modes in detail:
1. 'r' (Read Mode)
• Purpose: Opens the file for reading.
• Behavior: The file pointer is placed at the beginning of the file.
• Error Handling: If the file does not exist, it raises a FileNotFoundError.
• Use Case: Use when you only need to read data from the file and the file already
exists.
2. 'w' (Write Mode)
• Purpose: Opens the file for writing.
• Behavior: If the file already exists, its contents are truncated (erased) before writing.
If the file does not exist, a new empty file is created.
• Error Handling: If the file is not writable or there are permission issues, it raises an
OSError.
• Use Case: Use when you want to create a new file or overwrite an existing file.
3. 'x' (Exclusive Creation Mode)
• Purpose: Opens the file for exclusive creation.
• Behavior: If the file already exists, it raises a FileExistsError.
• Error Handling: It prevents overwriting an existing file.
• Use Case: Use when you want to create a new file but only if the file does not already
exist.
4. 'a' (Append Mode)
• Purpose: Opens the file for appending.
• Behavior: The file pointer is placed at the end of the file. If the file does not exist, it
creates a new file.
P a g e | 11
Python IMP Question and Answers
• Error Handling: It does not raise an error if the file already exists.
• Use Case: Use when you want to add new data to an existing file without modifying
the existing contents.
5. 'b' (Binary Mode)
• Purpose: Specifies that the file should be opened in binary mode.
• Behavior: It works in conjunction with other modes ('rb', 'wb', etc.) and reads or
writes the file in binary format rather than text format.
• Use Case: Use when working with binary files, such as images, audio, or other non-
text files.
6. 't' (Text Mode)
• Purpose: Specifies that the file should be opened in text mode.
• Behavior: This is the default mode for file operations in Python. It reads and writes
data in text format (character encoding is applied).
• Use Case: Use when working with text files. This is the default mode and typically
does not need to be specified.
7. 'r+' (Read and Write Mode)
• Purpose: Opens the file for both reading and writing.
• Behavior: The file pointer is placed at the beginning of the file. If the file does not
exist, it raises a FileNotFoundError.
• Use Case: Use when you want to read from and write to the same file.
8. 'w+' (Write and Read Mode)
• Purpose: Opens the file for both writing and reading.
• Behavior: If the file exists, it truncates the file (erases its contents) before writing. If
the file does not exist, it creates a new file.
• Use Case: Use when you want to both read from and write to a file and are okay with
losing the existing contents of the file.
9. 'a+' (Append and Read Mode)
• Purpose: Opens the file for both appending and reading.
• Behavior: The file pointer is placed at the end of the file for appending, and the file
can also be read. If the file does not exist, it creates a new file.
• Use Case: Use when you need to both read from and append to a file.
10. 'x+' (Exclusive Creation and Read Mode)
• Purpose: Opens the file for both reading and writing, but only if the file does not
already exist.
• Behavior: It raises a FileExistsError if the file already exists.
• Use Case: Use when you need to create a new file for both reading and writing but
want to avoid overwriting any existing file.
P a g e | 12
Python IMP Question and Answers
These modes can be combined in various ways to suit specific file operation needs.
Understanding these modes helps in managing file I/O operations more efficiently and avoids
unintended file loss or corruption.
13. Define exception handling explain with the help of example
Exception handling is a mechanism in programming that allows developers to manage
runtime errors or exceptional conditions in a program. It prevents the program from crashing
and provides a way to gracefully handle errors.
Key Concepts of Exception Handling:
• Try Block: Contains code that might raise an exception.
• Except Block: Handles the exception if it occurs.
• Finally Block (optional): Contains code that is always executed, regardless of whether
an exception occurred.
• Raise Statement: Used to explicitly trigger an exception.
Why Exception Handling?
• Prevents abrupt termination of the program.
• Helps identify and manage specific errors.
• Improves program reliability and robustness.
P a g e | 13
Python IMP Question and Answers
P a g e | 14
Python IMP Question and Answers
P a g e | 15
Python IMP Question and Answers
y = 2.5 # Float
P a g e | 16
Python IMP Question and Answers
# Integer to Float
num = 10
num_float = float(num)
print(num_float) # Output: 10.0
# Float to Integer
pi = 3.14
pi_int = int(pi)
print(pi_int) # Output: 3
# Integer to String
age = 25
age_str = str(age)
print(age_str) # Output: '25'
# List to Tuple
numbers = [1, 2, 3]
numbers_tuple = tuple(numbers)
print(numbers_tuple) # Output: (1, 2, 3)
20. Write a basic program in python that can cover the basic syntax of python.
P a g e | 17
Python IMP Question and Answers
P a g e | 18
Python IMP Question and Answers
27. Write a program to show the current working directory and List of directories in
python.
P a g e | 19
Python IMP Question and Answers
P a g e | 20
Python IMP Question and Answers
32. Explain the concept of Local and Global variables with example.
1. Global Variables
Definition:
• A global variable is declared outside any function, block, or class.
• It is accessible throughout the program, including inside functions (unless shadowed
by a local variable).
Scope:
• The scope of a global variable is the entire program.
Lifetime:
• Global variables exist as long as the program runs and are destroyed only when the
program terminates.
Characteristics:
• Accessible from any part of the program.
• Can be read directly inside a function.
• To modify a global variable inside a function, the global keyword is required.
2. Local Variables
Definition:
• A local variable is declared inside a function or block and can only be used within that
specific function or block.
Scope:
• The scope of a local variable is limited to the function or block where it is defined.
Lifetime:
• A local variable exists only during the execution of the function or block. Once the
function or block execution is complete, the variable is destroyed.
Characteristics:
• Cannot be accessed outside the function or block.
P a g e | 21
Python IMP Question and Answers
• Takes precedence over global variables if a local variable with the same name is
defined within the function.
33. Explain regular expression match function with the help of example.
Regular Expression match() Function in Python
The match() function in Python is a part of the re module and is used to check if a regular
expression (pattern) matches at the beginning of a string.
Key Points
Purpose:
• The match() function checks if the given pattern matches from the start of the string.
• It is suitable for scenarios where you need to ensure that the string begins with a
specific pattern.
Behavior:
• If the pattern is found at the beginning of the string, it returns a Match object.
• If no match is found, it returns None.
Case Sensitivity:
• By default, match() is case-sensitive, but you can use flags like re.IGNORECASE to
make it case-insensitive.
Return Value:
When a match is found, the Match object provides details like:
• .group() – The actual matched text.
• .start() – The starting index of the match.
• .end() – The ending index of the match.
When no match is found, None is returned.
Syntax:
re.match(pattern, string, flags=0)
pattern: The regular expression to be matched.
string: The input string to be checked.
flags (optional): Modifiers like re.IGNORECASE, re.MULTILINE, etc., to alter the matching
behavior.
Features of match()
Focuses on Start of String:
Unlike search(), which can find the pattern anywhere in the string, match() only works at the
beginning.
Supports Groups:
P a g e | 22
Python IMP Question and Answers
You can use capturing groups in the pattern to extract specific parts of the match.
Efficient for Validation:
Ideal for use cases like validating strings with specific prefixes (e.g., checking if a string
starts with "http").
34. Write a program to demonstrate the use of try, except, else and finally bock.
P a g e | 23
Python IMP Question and Answers
P a g e | 24
Python IMP Question and Answers
Customizable:
You can change the displayed options dynamically or set a default value.
Syntax
from tkinter import ttk
combobox = ttk.Combobox(parent, values=[list_of_values])
Parameters:
• parent: The parent container (e.g., a root window or frame).
• values: A list of predefined options displayed in the dropdown.
Methods
• get():
Retrieves the currently selected or entered value in the ComboBox.
• set(value):
Sets the initial/default value for the ComboBox.
• bind(event, handler):
Binds an event (e.g., selection change) to a function to handle user interaction
36. Explain Combo box widget with the help of example.
38. Write a program to print a table of a number taken by user using looping
statements.
P a g e | 25
Python IMP Question and Answers
P a g e | 26
Python IMP Question and Answers
P a g e | 27
Python IMP Question and Answers
P a g e | 28
Python IMP Question and Answers
P a g e | 29