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

Python Imp 1

Uploaded by

rishibhor326
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Python Imp 1

Uploaded by

rishibhor326
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Python IMP Question and Answers

1. Define Python and Explain its Characteristics.


Python is a high-level, interpreted, and versatile programming language created by Guido van
Rossum in 1991. It emphasizes code readability and simplicity, making it ideal for beginners
and experts alike.
Characteristics of Python:
1. Easy to Learn and Use: Simple syntax similar to English.
2. Interpreted Language: Executes line by line, eliminating the need for compilation.
3. Dynamically Typed: No need to declare variable types.
4. Platform-Independent: Code can run on different platforms without modification.
5. Extensive Libraries: Includes libraries like NumPy, Pandas, and TensorFlow.
6. Object-Oriented: Supports classes and objects for modular programming.
7. Automatic Memory Management: Handles memory allocation and garbage collection.
2. Write a basic program in python that can cover the basic syntax of python.
Program Output

Page |1
Python IMP Question and Answers

3. Describe the Applications of python with the help of examples.


1. Web Development
Python is extensively used for web development due to frameworks like Django, Flask, and
FastAPI, which simplify the process of building robust, secure, and scalable web
applications.
• Django: A full-stack framework that comes with built-in features like ORM, admin
interface, and authentication. It is ideal for large, data-driven websites.
• Example: Building an e-commerce platform or a blog system.
• Flask: A lightweight, minimalistic framework for developers who prefer flexibility.
• Example: Developing RESTful APIs for a social media application.
• FastAPI: A high-performance framework for creating APIs, especially useful in
microservices architecture.
2. Data Science
Python dominates the data science field due to libraries like:
• Pandas: Provides powerful tools for data manipulation and analysis.
Example: Cleaning and analyzing customer sales data to identify trends.
• NumPy: Efficient handling of numerical computations and large multi-dimensional
arrays.
Example: Performing matrix operations in financial modeling.
• Matplotlib & Seaborn: For data visualization, creating plots, and identifying patterns
in datasets.
Example: Visualizing market trends using histograms, scatter plots, and heatmaps.
3. AI and Machine Learning
Python's simplicity and rich ecosystem of libraries make it the preferred language for AI and
ML projects:
• TensorFlow and PyTorch: Popular frameworks for building neural networks and deep
learning models.
Example: Creating a sentiment analysis model to classify customer reviews.
• Scikit-learn: A go-to library for implementing classic ML algorithms like regression,
classification, and clustering.
Example: Predicting house prices based on historical data.
• Keras: High-level neural network API for rapid prototyping.
Example: Designing image recognition models.
4. Automation
Python excels in automating repetitive tasks, saving time and effort:
• Scripting: Automate file operations, data entry, or report generation.
Example: Writing a script to rename and organize thousands of files based on their
content or metadata.

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.

5. Define String, explain it with examples.


A string in programming is a sequence of characters, typically used to represent text. Strings
can include letters, numbers, symbols, and whitespace. Strings are usually enclosed in either
single quotes ('), double quotes ("), or triple quotes (''' or """) in most programming
languages.
Characteristics of Strings:
• Immutable: In many programming languages (e.g., Python, Java), strings cannot be
changed after they are created.
• Indexed: Each character in a string has a position (index) starting from 0.

Page |3
Python IMP Question and Answers

• Iterable: Strings can be traversed character by character using loops.

Program

Output

6. Define list, explain with examples.


A list is a data structure in Python that is used to store multiple items in a single variable. It is
one of the most versatile and commonly used data structures. Lists are ordered, mutable, and
can contain a mix of data types (e.g., integers, strings, other lists).
Characteristics of a List:
• Ordered: The items in a list have a defined order that will not change unless explicitly
done so.
• Mutable: Elements in a list can be changed after the list is created.
• Indexed: Each element in a list is accessible using an index, starting at 0.
• Dynamic: Lists can grow or shrink in size dynamically.
• Heterogeneous: Lists can store items of different data types.

Page |4
Python IMP Question and Answers

7.Describe the methods available in python list.


• append(): Adds an element to the end of the list.
• extend(): Appends elements from another iterable (like another list or tuple) to the
current list.
• insert(): Inserts an element at a specified index.
• remove(): Removes the first occurrence of a specified element from the list.
• pop(): Removes and returns the element at a specified index. If no index is specified,
removes the last element.
• clear(): Removes all elements from the list, leaving it empty.
• index(): Returns the index of the first occurrence of a specified element in the list.
• count(): Returns the number of times a specified element appears in the list.
• sort(): Sorts the list in ascending order by default. Can be customized to sort in
descending order or based on a specific key.

Page |5
Python IMP Question and Answers

• reverse(): Reverses the order of elements in the list.


• copy(): Returns a shallow copy of the list.
• del (not a method, but a keyword): Deletes elements or slices from a list. Can also
delete the entire list.
These methods provide functionality to manipulate, sort, and retrieve elements from
lists efficiently.
Program Output

8. Explain different types of tuples with the help of examples


Types of Tuples in Python
1. Empty Tuple
A tuple with no elements, used as a placeholder or for initializing.
2. Single-Element Tuple
A tuple containing only one element, distinguished by a trailing comma to avoid
confusion with parentheses.
3. Heterogeneous Tuple
A tuple containing elements of different data types, showcasing Python's flexibility.
4. Nested Tuple
A tuple containing other tuples or data structures as elements, useful for hierarchical
data representation.
5. Tuple with Mutable Elements
While tuples are immutable, they can include mutable objects like lists as their
elements, allowing limited modification.
6. Tuple of Tuples

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

9. Describe the techniques to create, update and delete dictionary element.


Techniques to Create, Update, and Delete Dictionary Elements
1. Creating a Dictionary
• Direct Assignment: Use curly braces {} to define key-value pairs, where each key is
unique, and the value can be any data type.
• Using dict() Function: Create a dictionary by passing keyword arguments or a
sequence of key-value pairs in tuple format.
• Empty Dictionary: Create an empty dictionary using {} or dict().
2. Updating a Dictionary
• Add New Key-Value Pair: Assign a value to a new key using square brackets ([]).
• Modify Existing Key-Value Pair: Reassign a new value to an existing key.
• Using update() Method: Add or modify multiple key-value pairs simultaneously by
passing another dictionary or iterable of key-value pairs.
3. Deleting Dictionary Elements
• Using del Statement: Delete a specific key-value pair by specifying the key.
• Using pop() Method: Remove a specific key and retrieve its associated value.
• Using popitem() Method: Remove and return the last inserted key-value pair (from
Python 3.7+).
• Using clear() Method: Remove all elements, leaving the dictionary empty

Page |8
Python IMP Question and Answers

10. Define function, explain with example


A function in programming is a block of reusable code that performs a specific task.
Functions help in organizing code, making it more readable, and avoiding repetition.
Functions can take inputs, called parameters, and may return a value after processing.
Key Components of a Function:
• Function Definition: The block where the function is defined.
• Function Call: Invoking or executing the function to perform its task.
• Parameters (Optional): Inputs passed to the function.
• Return Value (Optional): The result produced by the function.

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

Output: Hello! Rajashri Welcome


11. Explain Module with the help of example.
In Python, a module is a file that contains Python definitions and statements. A module can
contain functions, classes, and variables, and you can include runnable code in it as well.
Modules allow you to organize your Python code in a more readable and manageable way.
How to Use a Module:
You can use built-in Python modules (like math, os, random, etc.) or create your own custom
modules.
Example:
Creating a Module:
First, create a file named mymodule.py with the following content:
# mymodule.py
def greet(name):
return f"Hello, {name}!"
def add(a, b):
return a + b
Using the Module:
Now, in another Python file, you can import and use the module mymodule.py.
# main.py
import mymodule
# Using the greet function from the module
print(mymodule.greet("Rajashri"))
# Using the add function from the module
result = mymodule.add(5, 3)

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.

14. Describe regular expression (re) module in detail.


The re module in Python provides support for working with regular expressions (regex), a
powerful tool for pattern matching and string manipulation. Regular expressions allow you to
search for, match, and manipulate text efficiently using patterns.
Key Concepts in the re Module:
• Pattern Matching:
Regular expressions are patterns used to match strings or portions of strings.
These patterns can include special characters and sequences for advanced matching.
• Functions in the re Module:

P a g e | 13
Python IMP Question and Answers

9. re.match(): Determines if the pattern matches the beginning of the string.


10. re.search(): Searches the string for the first occurrence of the pattern.
11. re.findall(): Returns all occurrences of the pattern as a list.
12. re.finditer(): Returns an iterator yielding match objects for all matches.
13. re.sub(): Replaces occurrences of the pattern with a specified string.
14. re.split(): Splits the string by the occurrences of the pattern.
15. re.compile(): Compiles a regular expression into a reusable object.
• Match Objects:
Returned by functions like re.match() and re.search().
Provide details about the match, such as the matched string, start and end positions, etc.
15. Write a python code for following operation: Change Directory Making new
directory Renaming directory

P a g e | 14
Python IMP Question and Answers

16. Write a program to draw oval, line and rectangle on canvas.

17. Explain SimpleDialog module with the help of example.


The tkinter.simpledialog module in Python provides a way to create simple dialog boxes for
user input. It includes predefined dialogs for basic tasks like asking for a string, an integer, or
a floating-point number. This module is particularly useful when you need to quickly capture
user input without designing a custom form.
Common Functions in simpledialog:
• askstring(title, prompt):
Prompts the user to input a string.
• askinteger(title, prompt):
Prompts the user to input an integer.
• askfloat(title, prompt):
Prompts the user to input a floating-point number.

P a g e | 15
Python IMP Question and Answers

18. Explain any four Advantages of GUI programming.


GUI (Graphical User Interface) programming provides numerous benefits for developers and
users alike. Here are four key advantages:
1. User-Friendly Interaction
GUIs are intuitive and visually engaging, making software easier to use even for non-
technical users. Elements like buttons, menus, and icons allow users to interact with
applications without needing to understand complex commands.
2. Faster Learning Curve
GUIs reduce the learning curve for new users as they can rely on visual cues and
explore functionalities through familiar elements like dropdowns, toolbars, and dialog
boxes. This accessibility makes software adoption smoother.
3. Enhanced Productivity
With visual tools and drag-and-drop features, GUIs make tasks quicker to perform
compared to typing repetitive or complex commands. This speed boosts productivity
for both users and developers.
4. Consistency and Error Reduction
GUIs promote standardization by following consistent design patterns across
applications. This uniformity minimizes user errors, as predictable behavior helps
users understand functionalities across similar interfaces.
These advantages make GUI programming essential for creating modern, user-friendly
applications.
19. Define a Python and Explain Type Conversion in detail.
Definition of Python
Python is a high-level, interpreted, and general-purpose programming language known for its
simplicity and readability. It supports multiple programming paradigms, including object-
oriented, procedural, and functional programming. Python is widely used for web
development, data analysis, artificial intelligence, machine learning, scripting, and more.
Type Conversion in Python
Type conversion in Python refers to converting one data type into another. Python provides
two types of type conversions:
Implicit Type Conversion
Python automatically converts a smaller data type to a larger one without user intervention.
This usually happens during operations where the operands have mixed types, ensuring no
loss of data.
x=5 # Integer

y = 2.5 # Float

result = x + y # Integer + Float

print(result) # Output: 7.5 (converted to float)

print(type(result)) # Output: <class 'float'>

P a g e | 16
Python IMP Question and Answers

2. Explicit Type Conversion (Type Casting)


The user explicitly converts one data type to another using Python’s built-in functions. This
requires the programmer’s intervention and is used when the implicit conversion is not
sufficient or desired.
Built-in Functions for Explicit Conversion:
• int(): Converts to an integer.
• float(): Converts to a float.
• str(): Converts to a string.
• list(): Converts to a list.
• tuple(): Converts to a tuple.
• dict(): Converts to a dictionary.
• set(): Converts to a set.

# 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

22. Write a program to demonstrate the looping statements available in python.

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

29. Explain Anonymous function with the help of example.


Anonymous Function in Python
An anonymous function is a function without a name. In Python, these functions are defined
using the lambda keyword and are often referred to as lambda functions. They are typically
used for short, simple operations that can be written in a single line.
Key Features:
• No Name: Unlike regular functions defined with def, lambda functions don’t have a
name.
• Single Expression: They can only consist of a single expression, which is evaluated
and returned.
• Inline Use: Ideal for situations where a small function is required temporarily, such as
in functional programming with map(), filter(), and reduce().
• Multiple Arguments: Can take any number of arguments but must have only one
expression.
Syntax:
lambda arguments: expression
lambda: The keyword to define the function.
arguments: The input parameters (can be zero or more).
expression: The logic of the function, which is evaluated and returned.
Usage:
• Higher-Order Functions: Commonly used in functions like map(), filter(), and
reduce() to define small operations.
• Sorting: Used with functions like sorted() to provide custom sorting criteria.
• Throwaway Functions: Useful when a function is needed temporarily without the
need to formally define it.
Limitations:
• Limited Functionality: Can only handle a single expression; no complex logic or
statements are allowed.
• Readability: Overuse can make code harder to read compared to named functions.
• Lambda functions are a powerful tool for specific use cases but are not a replacement
for regular functions. Use them when simplicity and brevity are needed.
30. Write a program to read and write .txt file in python.

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.

35. Write a program to use textbox, label and button widget

P a g e | 23
Python IMP Question and Answers

36. Explain Combo box widget with the help of example.


A ComboBox is a widget in the ttk module of Tkinter that combines a text entry field with a
dropdown list of predefined values. It allows users to select an item from the dropdown or,
optionally, type in a custom value.
Features of ComboBox:
Dropdown List:
Displays a list of predefined values for users to choose from.
Editable/Non-Editable:
By default, users can type custom values in the ComboBox.
It can be configured to restrict input to the predefined list.
Interactive:
Allows dynamic handling of user selection using events or functions.

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

40. Explain Lambda function with the help of example


A lambda function in Python is a small, anonymous function that can have any number of
input parameters but only one expression. It is defined using the lambda keyword, and unlike
regular functions, it doesn't require a function name. The result of the expression is
automatically returned.
Syntax of Lambda Function
lambda arguments: expression
arguments: These are the parameters passed to the lambda function.
expression: A single expression whose result is returned by the function. The expression can
be any valid Python expression.
Key Characteristics of Lambda Functions:
• Anonymous: Lambda functions are unnamed, meaning they don't require a name to be
defined.
• Single Expression: Lambda functions are limited to a single expression. They cannot
contain statements or multiple expressions.
• Implicit Return: The expression is evaluated, and the result is automatically returned.
No need for a return keyword.
When to Use Lambda Functions:
Lambda functions are typically used when you need a small function for a short period of
time and do not want to formally define it using the def keyword. They are particularly useful
in situations where you need to pass a function as an argument to higher-order functions like
map(), filter(), and sorted().
Common Use Cases for Lambda Functions:
• Sorting Data:
You can use lambda functions to specify the key by which to sort data (e.g., a list of
tuples or dictionaries).
• Functional Programming:

P a g e | 26
Python IMP Question and Answers

Lambda functions are commonly used in functional programming techniques, where


functions are passed as arguments to other functions.
• Single-use Functions:
When you need a quick function for a short task without the overhead of defining a
separate named function.
Advantages of Lambda Functions:
• Conciseness: Lambda functions provide a more concise way to define simple
functions, especially when they are used in places like map(), filter(), and sorted().
• Readability: For small tasks, lambda functions can make the code more readable by
eliminating the need for a full function definition.
• Limitations of Lambda Functions:
• Single Expression: Lambda functions can only contain a single expression, limiting
their ability to perform complex tasks.
• Less Readable for Complex Operations: While simple lambda functions are concise,
complex operations inside a lambda can make the code harder to read and understand.
Lambda functions are a powerful feature of Python that allows for creating small, throwaway
functions in a single line. They are especially useful when working with higher-order
functions and operations that require a simple, temporary function.
42. Write a program to demonstrate the user defined exception in python.

43. Write a program to demonstrate event handling in python.

P a g e | 27
Python IMP Question and Answers

45. Explain any five widgets from Tkinter library.


1. Label Widget
The Label widget in Tkinter is used to display text or images. It is often used to provide
information to users, such as instructions, titles, or simple messages. Labels cannot be
interacted with by the user, and they are generally used for presenting static content.
Key Attributes:
• text: The text displayed in the label.
• font: The font style of the text.
• bg (background), fg (foreground): Colors for the background and text.
2. Button Widget
The Button widget creates a clickable button that performs an action when clicked. Buttons
are typically used to trigger events such as form submissions or executing a function.
Key Attributes:
• text: The label displayed on the button.
• command: The function that is called when the button is clicked.
• bg, fg: Background and foreground colors of the button.
3. Entry Widget
The Entry widget is used for accepting a single line of input from the user. It is commonly
used for text fields in forms such as names, emails, and passwords.
Key Attributes:

P a g e | 28
Python IMP Question and Answers

• textvariable: A variable that is linked to the widget to track changes.


• show: Used to hide characters (e.g., for password fields).
• state: Defines whether the entry widget is in a normal, disabled, or readonly state.
4. Text Widget
The Text widget is used for multi-line text input or display. It allows users to enter or view
large chunks of text, and is ideal for tasks like writing or editing paragraphs, notes, or other
detailed content.
Key Attributes:
• height and width: Control the size of the text box.
• wrap: Controls how text is wrapped within the widget.
5. Checkbutton Widget
The Checkbutton widget creates a checkbox, allowing users to make a binary choice, such as
selecting an option or agreeing to terms. It can be checked or unchecked, and multiple
checkboxes can be used to allow users to select more than one option.
Key Attributes:
• variable: Links the checkbox to a Tkinter variable (like IntVar or StringVar).
• onvalue and offvalue: Define the values when the checkbox is checked or unchecked.
• command: The function called when the checkbox state changes.
These five widgets — Label, Button, Entry, Text, and Checkbutton — are fundamental
components of a Tkinter-based GUI and are used for displaying content, accepting user input,
and interacting with the application.

P a g e | 29

You might also like