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

Python Full

Python is a versatile, high-level programming language known for its simplicity and readability. It supports multiple programming paradigms and is widely used for tasks ranging from web development to data science. The document defines various Python concepts like comments, data types, keywords, operators, and control flow statements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

Python Full

Python is a versatile, high-level programming language known for its simplicity and readability. It supports multiple programming paradigms and is widely used for tasks ranging from web development to data science. The document defines various Python concepts like comments, data types, keywords, operators, and control flow statements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 71

Unit 1

Question Bank (Paper - II: Python (6T2))

2 Marks Questions

1) What is Python?
Python is a versatile, high-level programming language known for its simplicity and
readability. Created by Guido van Rossum and first released in 1991, Python has
gained immense popularity due to its ease of learning, clear syntax, and vast
ecosystem of libraries and frameworks.

Python supports multiple programming paradigms, including procedural, object-


oriented, and functional programming. It is widely used in various domains such as
web development, data science, artificial intelligence, scientific computing, and
automation.
One of Python's key strengths is its extensive standard library, which provides
modules and packages for tasks ranging from file I/O to networking. Additionally,
Python's active community contributes to its rich ecosystem, with thousands of
third-party libraries available for specific purposes.

Python's simplicity and versatility make it an ideal choice for beginners learning to
code, as well as for professionals building complex applications. Its readability and
expressiveness promote rapid development and maintainability of codebases.

2) What is a comment? Give an example.


In programming, a comment is a piece of text within the source code that is
ignored by the compiler or interpreter. Comments are used to provide
explanations, notes, or documentation about the code for developers who read it.
They are essential for making the code more understandable and maintainable.

In Python, comments are preceded by the hash symbol (#). Everything after the
hash symbol on a line is treated as a comment and is ignored by the Python
interpreter.

Here's an example:
code:
# This is a single-line comment
print("Hello, world!") # This comment follows a statement

"""
This is a multi-line comment.
It spans multiple lines.
"""

# Below is an example of a comment within a function definition


def add_numbers(x, y):
# This function adds two numbers
return x + y

In this example:
● # This is a single-line comment is a single-line comment.
● print("Hello, world!") # This comment follows a statement demonstrating
how a comment can follow a code statement on the same line.
● """ ... """ is a multi-line comment, although it's technically a string literal that
spans multiple lines. It's commonly used as a multi-line comment in Python.
● # This function adds two numbers is a comment within a function definition,
providing a brief description of what the function does.
3) What are the supported data types in Python?

4) List any 8 keywords of python.


1. if: Used for conditional statements.
2. else: Used in conjunction with if for executing code when the if condition is
false.
3. elif: Short for "else if", used for chaining multiple conditional statements.
4. for: Used for looping over elements in iterable objects.
5. while: Used for looping based on a condition.
6. def: Used for defining functions.
7. return: Used inside functions to return a value.
8. import: Used for importing modules or specific attributes/functions from
modules

5) Define lists in Python.


In Python, a list is a built-in data structure used to store a collection of items. Lists
are ordered, mutable (modifiable), and can contain elements of different data
types. Lists are defined by enclosing comma-separated elements within square
brackets [ ].
6. What is a negative index in Python?
Negative indexing in Python allows you to access elements from the end of a
sequence, such as a list or a string. Index -1 refers to the last element, -2 refers to
the second last element, and so on.

7. How can you convert a number to a string?


You can convert a number to a string in Python using the str() function.

For example:
number = 42
string_number = str(number)

8. What are the built-in types available in Python?


Built-in Types Available in Python:
Python provides several built-in data types, including int, float, str, list, tuple, dict,
set, bool, and None.

9. What is a string in Python?


A string in Python is a sequence of characters enclosed within single quotes (' '),
double quotes (" "), or triple quotes (''' ''' or """ """). Strings are immutable, meaning
they cannot be changed once created.

10. What is keyword? List any 4 keywords in Python.


In Python, a keyword is a reserved word that has a special meaning and purpose
within the language. Python keywords cannot be used as identifiers (variable
names, function names, etc.). Four Python keywords are if, else, for, and while.

11. What is Assignment operator in Python? Give an example.


The assignment operator in Python is the equals sign (=). It assigns the value on
the right-hand side to the variable on the left-hand side.
For example:
x = 10 # Assigning the value 10 to the variable x

12. How will you print multiple fields using print()?


You can print multiple fields using the print() function by separating them with
commas.
For example:
name = "Alice"
age = 30
print("Name:", name, "Age:", age)
13. What is the role of ** operator in Python.
The ** operator in Python is the exponentiation operator. It raises the left operand
to the power of the right operand.
For example:
result = 2 ** 3 # Calculates 2 raised to the power of 3, which is 8

14. Write down the syntax of while loop


The syntax of a while loop in Python is as follows:
while condition:
# Code block to be executed repeatedly as long as the condition is true

15. Write down the syntax of for loop


The syntax of a for loop in Python is as follows:
for item in iterable:
# Code block to be executed for each item in the iterable
UNIT I - 3 MARKS QUESTION

1. What are the built-in types does python provides?


Built-in Types Provided by Python:
● Python provides several built-in data types such as int, float, str, list,
tuple, dict, set, bool, and None.
● These types cover a wide range of data representations and
structures, allowing for versatile programming.

2. What is keyword? List any 8 keywords of python.


Keyword in Python:
● Keywords are reserved words in Python with predefined meanings
and functionalities.
● Some of the keywords in Python include if, else, for, while, def,
import, return, and try.

3. What are tuples in Python?


● Tuples are ordered, immutable collections of items in Python.
● They are defined using parentheses ( ) and can contain elements of
different data types.
● Syntax: my_tuple = (1, 'hello', 3.14)

4. How will you take the prompt input from user?


Taking Prompt Input from User:
● Use the input() function to take input from the user.
● Example: name = input("Enter your name: ")

5. Write down the syntax of if else in python?


● The if statement is used for conditional execution, followed by zero or more
elif statements and an optional else statement.

Syntax:

if condition:
# Code block executed if condition is true
elif another_condition:
# Code block executed if another_condition is true
else:
# Code block executed if none of the above conditions are true
6. What is slicing in Python?
Slicing in Python:
● Slicing is the technique of extracting a subset of elements from a
sequence (like a list or a string) using a specified range of indices.
● Syntax: sequence[start:end:step]
● Example: my_list = [1, 2, 3, 4, 5], subset = my_list[1:4] (extracts
elements at index 1, 2, and 3).

7. How can you share global variables across modules?


Sharing Global Variables Across Modules:
● Global variables can be shared across modules by importing the
module containing the global variable.

Example:
# module1.py
global_var = 10

# module2.py
from module1 import global_var
print(global_var) # Output: 10

8. What is the purpose of // operator?


Purpose of // Operator:
● The // operator performs floor division, which divides two numbers
and rounds down to the nearest integer.
● Example: result = 10 // 3 (result will be 3).

9. Mention the use of // operator in Python?


Use of // Operator in Python:
● It is used to perform integer division in Python, where the result is
rounded down to the nearest integer.
● Example: 5 // 2 will result in 2.

10. What is floor division? Give example


Floor Division:
● Floor division divides two numbers and returns the integer value of
the quotient, discarding any remainder.
● Example: 7 // 3 will result in 2.
11. Mention the use of the split function in Python?
Use of Split Function in Python:
● The split() function in Python is used to split a string into a list of
substrings based on a specified delimiter.
● Example: sentence = "Hello world", words = sentence.split(' ') (splits
the sentence into individual words).

12. What is the purpose of ** operator?


Purpose of ** Operator:
● The ** operator is the exponentiation operator in Python, used to
raise a number to the power of another number.
● Example: result = 2 ** 3 (result will be 8).
13. How do you write a conditional expression in Python?
Conditional Expression in Python:
● Conditional expressions in Python, also known as ternary
expressions, provide a compact way to express conditional
statements.
● Syntax: value = true_expression if condition else false_expression.
● Example: x = 10 if condition else 20.

14. How will you create a dictionary in python?


Creating a Dictionary in Python:
● Dictionaries in Python are collections of key-value pairs enclosed
within curly braces { }.
● Example: my_dict = {'name': 'John', 'age': 30}.

15. Define the term pickling and unpickling?


Pickling and Unpickling:
● Pickling is the process of serializing an object into a byte stream,
while unpickling is the process of deserializing the byte stream back
into an object.
● Example:
import pickle

# Pickling
with open('data.pkl', 'wb') as f:
pickle.dump(data, f)

# Unpickling
with open('data.pkl', 'rb') as f:
data = pickle.load(f)

16. Describe logical operators with example?


Logical Operators with Example:
● Logical operators in Python are and, or, and not, used to perform
logical operations on boolean values.
● Example:
x = True
y = False
print(x and y) # Output: False
print(x or y) # Output: True
print(not x) # Output: False

17. Write the syntax of loops in python.


While Loop:
The while loop in Python is used to repeatedly execute a block of
code as long as a specified condition is true.

Syntax:
while condition:
# Code block to be executed repeatedly as long as the condition is true

Example:
code
num = 1
while num <= 5:
print(num)
num += 1
Output:
1
2
3
4
5
For Loop:
The for loop in Python is used to iterate over a sequence (such as a list,
tuple, string, or range) or any other iterable object.

Syntax:
for item in iterable:
# Code block to be executed for each item in the iterable

Example:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)

Output:
apple
banana
cherry

Another example with range:

for i in range(1, 5):


print(i)
Output:
1
2
3
4
5 Marks Questions

UNIT-I
1. What is Python? What are the benefits of using Python?
Python Definition and Benefits:
● Python is a dynamically-typed, high-level programming language
known for its simplicity, readability, and versatility.
● Benefits of using Python include its extensive standard library, which
provides ready-to-use modules for various tasks such as web
development, data analysis, machine learning, and more.
● Python's syntax encourages code readability and maintainability,
making it an excellent choice for both beginners and experienced
developers.
● The language's interpreted nature allows for rapid development and
prototyping, enabling developers to write and test code quickly.
● Python's strong community support, active development, and vast
ecosystem of third-party libraries contribute to its widespread
adoption across different domains.

2. How will you execute python program (script) on windows platform?


Executing Python Program on Windows Platform:
● To execute a Python script on Windows, you need to have Python
installed on your system and properly configured in the environment
variables.
● Open Command Prompt (cmd) and navigate to the directory
containing your Python script using the cd command.
● Once in the correct directory, run the script by typing python followed
by the name of your script file and pressing Enter.
● Python will interpret and execute the script, displaying the output in
the Command Prompt window.

3. Write down important features of python.


Important Features of Python:
● Python's readability and simplicity make it easy to learn and
understand, reducing development time and effort.
● Dynamic typing allows variables to change types dynamically,
providing flexibility and simplifying code writing.
● Python's extensive standard library provides numerous built-in
modules and functions for various tasks, eliminating the need for
external dependencies in many cases.
● Object-oriented programming support allows for the creation of
reusable and modular code through classes and objects.
● Python's interpreted nature facilitates interactive development and
debugging, enabling developers to test and modify code on the fly.

4. Describe any five list methods.


List Methods:
● append(): Adds an element to the end of the list, modifying the
original list.
● extend(): Extends the list by appending elements from another
iterable, such as another list or tuple.
● insert(): Inserts an element at the specified index, shifting existing
elements to the right.
● remove(): Removes the first occurrence of a specified value from the
list, raising a ValueError if the value is not found.
● pop(): Removes and returns the element at the specified index, or the
last element if no index is specified, modifying the original list.

5. What is module and package in Python?


Module and Package in Python:
● A module is a file containing Python code that can be executed or
imported by other Python scripts.
● A package is a directory containing multiple modules and an
__init__.py file, indicating that it is a Python package.
● Modules and packages help organize code into logical units, improve
code reusability, and facilitate modular programming practices.

6. What is the difference between tuples and lists in Python?


Difference Between Tuples and Lists in Python:
● Tuples are often used to represent fixed collections of items, such as
coordinates, database records, or function arguments, where
immutability ensures data integrity.
● Lists, being mutable, are preferred for situations where elements
need to be added, removed, or modified frequently, such as
maintaining a dynamic list of items in memory or representing
sequences of data.
● Tuples have a slightly smaller memory footprint compared to lists due
to their immutability, making them more efficient in certain scenarios
where data does not need to be modified frequently.

7. What is conditional expression in Python? Explain with example.


Conditional Expression in Python:
● Conditional expressions are particularly useful in situations where a
simple conditional statement is needed to determine the value of a
variable or expression.
● They provide a concise and readable alternative to traditional if-else
statements, especially when used inline within other expressions or
function calls.
● While conditional expressions can improve code readability,
excessive use in complex expressions may lead to reduced clarity
and maintainability, so they should be used judiciously.

8. How will you define alternative separator for multiple fields in print()? Give
example.
Defining Alternative Separator for Multiple Fields in print():
● The sep parameter in the print() function can accept any string as a
separator, allowing for flexible formatting of output.
● Alternative separators can include not only characters like commas,
spaces, or hyphens but also custom strings like newline characters (\
n) or tab characters (\t).
● This feature enables developers to customize the appearance of
printed output according to specific formatting requirements or
conventions, enhancing the readability and usability of the output.

9. Explain three types of errors that can occur in python.


Types of Errors in Python:
● SyntaxError: Syntax errors occur when the Python parser encounters
code that violates the language's syntax rules, such as missing
colons at the end of lines in if statements or using reserved keywords
as variable names.
● NameError: Name errors occur when the interpreter encounters an
identifier (variable, function, etc.) that is not defined or accessible in
the current scope, either due to misspelling or referencing a non-
existent name.
● TypeError: Type errors occur when operations or functions are
applied to objects of incompatible types, such as performing
arithmetic operations on strings or trying to access attributes of non-
object types.

10. Explain bitwise operators of python.


Bitwise Operators in Python:
● Bitwise operators manipulate individual bits of integers at the binary
level, providing low-level control over binary data representations.
● & (bitwise AND) computes the AND operation between
corresponding bits of two integers.
● | (bitwise OR) computes the OR operation between corresponding
bits of two integers.
● ^ (bitwise XOR) computes the XOR operation between
corresponding bits of two integers.
● ~ (bitwise NOT) inverts all the bits of an integer, yielding the one's
complement.
● << (left shift) shifts the bits of an integer to the left by a specified
number of positions.
● >> (right shift) shifts the bits of an integer to the right by a specified
number of positions.

11. What is list? Explain with example.


List in Python:
● Lists provide a flexible and powerful way to store and manipulate
collections of items in Python.
● They support various operations such as indexing, slicing,
appending, extending, inserting, removing, and sorting, making them
suitable for a wide range of tasks.
● Lists can contain elements of different data types, including integers,
floats, strings, tuples, lists, dictionaries, or even other complex
objects.

12. Explain break and continue with example.


Break and Continue in Python:
● The break statement is commonly used to terminate the execution of
a loop prematurely when a certain condition is met, allowing the
program to exit the loop early and continue with the next statement
after the loop.
● The continue statement, on the other hand, skips the remaining code
inside the loop for the current iteration and proceeds directly to the
next iteration of the loop, effectively skipping the rest of the loop's
body for that iteration.

13. What is set? Explain with methods.


● Sets are particularly useful for tasks such as removing duplicates from a
sequence, testing membership, or performing set operations such as union,
intersection, difference, and symmetric difference.
● Set elements must be hashable, meaning they must be immutable and
support hashing, which allows for efficient membership testing and set
operations.
● Sets do not preserve the order of elements and do not support indexing or
slicing like lists, but they offer efficient lookup and manipulation operations,
making them ideal for scenarios where uniqueness and fast membership
testing are important.

10 Marks Questions

UNIT-I

1. How to install python on windows?


How to Install Python on Windows:
● Python can be installed on Windows by downloading the installer from the
official Python website (python.org) and running it.
● The installer provides options to customize the installation, such as
choosing the installation directory, adding Python to the system PATH, and
installing additional components like pip and documentation.
● Once installed, Python can be accessed from the Command Prompt or
PowerShell by typing python, and the Python IDLE (Integrated Development
and Learning Environment) can be used for interactive development.

2. How to install python on Linux?


● Python is typically pre-installed on many Linux distributions. However, if it's
not available, it can be installed using the distribution's package manager.
● For example, on Ubuntu and Debian-based systems, Python can be
installed using the apt package manager by running sudo apt install
python3.
● Alternatively, Python can be installed from source or using third-party
package managers like pip or conda, depending on the specific
requirements of the system and the desired Python version.
3. Define any 10 methods used for manipulating List.
Methods for Manipulating Lists:
● append(): Adds an element to the end of the list.
● extend(): Extends the list by appending elements from another
iterable.
● insert(): Inserts an element at a specified position in the list.
● remove(): Removes the first occurrence of a specified value from the
list.
● pop(): Removes and returns the element at a specified position in the
list.
● index(): Returns the index of the first occurrence of a specified value.
● count(): Returns the number of occurrences of a specified value in
the list.
● sort(): Sorts the elements of the list in ascending order.
● reverse(): Reverses the order of the elements in the list.
● copy(): Returns a shallow copy of the list.

4. What is the difference between while and for loop? Explain.


Difference Between While and For Loop:
● A while loop iterates as long as a given condition is true. It's suitable
when the number of iterations is unknown or variable.
● A for loop iterates over a sequence of elements or an iterable object.
It's suitable when the number of iterations is known or fixed.
● While loops are used when you don't know beforehand how many
times you need to iterate, while for loops are used when you want to
iterate over a sequence or a range of values.
● Syntax:
● python
● Copy code
# While loop syntax
while condition:
# Code block to be executed

● python
● Copy code
# For loop syntax
for item in iterable:
● # Code block to be executed

5. What is module and package in Python? Explain with example


Module and Package in Python:
● A module is a file containing Python code that can be executed or imported
into other Python scripts. It typically contains functions, classes, and
variables.
● A package is a directory containing multiple modules and an __init__.py file,
indicating that it's a Python package. Packages are used to organize related
modules and provide a hierarchical structure to Python projects.
● Example:
● python
● Copy code
# module.py
def greeting(name):
return f"Hello, {name}!"

● python
● Copy code
# package/__init__.py
● from .module import greeting

6. How python interpreter can be used to perform different arithmetic calculations?


Explain
1. Using Python Interpreter for Arithmetic Calculations:
● The Python interpreter can be used interactively to perform various
arithmetic calculations by typing expressions directly into the interpreter
prompt.
● For example, typing 2 + 3 and pressing Enter will evaluate the expression
and display the result 5.
● Similarly, expressions involving other arithmetic operators such as
subtraction -, multiplication *, division /, and exponentiation ** can be
evaluated interactively.
● The interpreter provides immediate feedback on the result of each
expression, making it a convenient tool for quick calculations and
experimentation.

7. Explain various types of operators in python.


1. Types of Operators in Python:
● Python supports various types of operators, including arithmetic,
comparison, logical, bitwise, assignment, identity, and membership
operators.
● Arithmetic operators perform mathematical operations on numeric
operands, such as addition +, subtraction -, multiplication *, division /,
exponentiation **, and modulus %.
● Comparison operators compare the values of two operands and return a
Boolean result, including equal ==, not equal !=, greater than >, less than <,
greater than or equal to >=, and less than or equal to <=.
● Logical operators perform logical operations on Boolean operands, including
logical AND and, logical OR or, and logical NOT not.
● Bitwise operators perform bitwise operations on integer operands at the
binary level, including bitwise AND &, bitwise OR |, bitwise XOR ^, bitwise
NOT ~, left shift <<, and right shift >>.
● Assignment operators are used to assign values to variables, such as = for
simple assignment, += for addition assignment, -= for subtraction
assignment, and so on.

8. What is type casting? Explain in detail


1. Type Casting in Python:
● Type casting, also known as type conversion, refers to the process of
converting a value from one data type to another.
● Python provides built-in functions for performing type casting, including int(),
float(), str(), bool(), and others.
● Type casting allows for interoperability between different data types and
enables operations that require operands of compatible types.
● Example:
● python
● Copy code
x = 10
y = float(x) # Convert integer to float
● z = str(x) # Convert integer to string

9. What binary operators of python.


1. Binary Operators in Python:
● Binary operators are operators that perform operations on two operands.
● In Python, binary operators include arithmetic operators such as addition +,
subtraction -, multiplication *, division /, exponentiation **, and modulus %.
● They also include comparison operators such as equal ==, not equal !=,
greater than >, less than <, greater than or equal to >=, and less than or
equal to <=.
● Additionally, bitwise operators such as bitwise AND &, bitwise OR |, bitwise
XOR ^, left shift <<, and right shift >> are binary operators.
10. What is a list, tuple,set and dictionary? Explain with example
1. List, Tuple, Set, and Dictionary in Python:
● List: A list is a mutable, ordered collection of elements in Python, defined by
enclosing comma-separated values within square brackets [ ]. Example:
my_list = [1, 2, 3].
● Tuple: A tuple is an immutable, ordered collection of elements in Python,
defined by enclosing comma-separated values within parentheses ( ).
Example: my_tuple = (1, 2, 3).
● Set: A set is a mutable, unordered collection of unique elements in Python,
defined by enclosing comma-separated values within curly braces { }.
Example: my_set = {1, 2, 3}.
● Dictionary: A dictionary is a mutable, unordered collection of key-value pairs
in Python, defined by enclosing comma-separated key-value pairs within
curly braces { } and separating them by colons :. Example: my_dict = {'a': 1,
'b': 2, 'c': 3}.

Unit 2
UNIT-II (2 Marks Questions)

1. Define Errors and Exceptions in Python programs?


Errors and Exceptions in Python Programs:
● Definition: Errors are issues that occur during the execution of a
program, causing it to terminate abnormally. Exceptions are special
objects raised during runtime to indicate that an error has occurred,
allowing for graceful handling of errors.
● Explanation: Errors can be syntax errors, logical errors, or runtime
errors. Exceptions are used to handle unexpected situations that may
arise during program execution, preventing the program from
crashing.
● Syntax and Example:
try:
# Code block that may raise an exception
result = 10 / 0
except ZeroDivisionError as e:
# Handling the exception
print("Error:", e)

2. What is meant by default values in function? Explain


Default Values in Functions:
● Definition: Default values are values assigned to function parameters,
allowing the function to be called with fewer arguments. If a
parameter is not provided when the function is called, its default
value is used.
● Explanation: Default values provide flexibility by allowing functions to
have optional parameters. They are specified in the function
definition and are assigned using the assignment operator (=).
● Syntax and Example:
def greet(name="Guest"):
print("Hello,", name)

greet("Alice") # Output: Hello, Alice


greet() # Output: Hello, Guest

3. What is the purpose of modules in python?


● Definition: A module is a file containing Python code that defines functions,
classes, and variables. Modules allow for code organization, reuse, and
sharing across multiple Python programs.
● Explanation: Modules help in modular programming by breaking down large
programs into smaller, manageable components. They promote code
reusability and maintainability.
● Syntax and Example:
# Importing module
import math

# Using functions from the math module


print(math.pi) # Output: 3.141592653589793
print(math.sqrt(9)) # Output: 3.0

4. How will you make available the stored procedure of module xyz into your
program?
Accessing Stored Procedures of a Module:
● Definition: To access stored procedures (functions, classes,
variables) of a module in your program, you need to import the
module using the import statement.
● Explanation: Once imported, you can access the stored procedures
using dot notation, specifying the module name followed by the
procedure name.
● Syntax and Example:
# Importing module
import xyz
# Accessing stored procedure
result = xyz.stored_procedure()

5. How will you call the methods of a given module without specifying dot-suffix
their name.
Calling Methods of a Module without Dot-Suffix:
● Definition: To call methods of a module without specifying dot-suffix,
you can import specific functions using the from keyword.
● Explanation: This approach allows you to use the function directly
without prefixing it with the module name.
● Syntax and Example:
# Importing specific function from module
from xyz import method
# Calling method without dot-suffix
result = method()
6. How will you see the python version on >>> prompt.
Viewing Python Version on >>> Prompt:
● Definition: You can view the Python version on the >>> prompt by
executing the sys module's version attribute.
● Explanation: This attribute contains the Python interpreter's version
number.
● Syntax and Example:
>>> import sys
>>> sys.version
'3.9.2 (default, Feb 20 2021, 00:00:00) [GCC 9.3.0]'

7. Define datetime module.


Datetime Module:
● Definition: The datetime module in Python provides classes and
functions for working with dates and times. It allows manipulation,
formatting, and arithmetic operations on dates and times.
● Explanation: It simplifies tasks such as parsing dates from strings,
calculating time differences, and formatting dates for display.
● Syntax and Example:
import datetime
# Creating a datetime object
current_datetime = datetime.datetime.now()
print(current_datetime)

8. What is the purpose of today() method?


Purpose of today() Method:
● Definition: The today() method in the datetime module returns the current
local date.
● Explanation: It is commonly used when you only need the current date and
not the time.
● Syntax and Example:
import datetime
# Getting the current date
current_date = datetime.date.today()
print(current_date)

9. What is the purpose of getattr() method.


Purpose of getattr() Method:
● Definition: The getattr() method in Python returns the value of a
specified attribute of an object.
● Explanation: It provides a way to access object attributes
dynamically, especially when the attribute name is stored in a
variable.
● Syntax and Example:
class MyClass:
x = 10
obj = MyClass()
value = getattr(obj, 'x')
print(value) # Output: 10

10. What is the purpose of decimal function.


Purpose of Decimal Function:
● Definition: The decimal function in Python is used to create Decimal
objects, which represent fixed-point numbers with arbitrary precision.
● Explanation: It is useful for applications requiring precise decimal
arithmetic, such as financial calculations.
● Syntax and Example:

from decimal import Decimal


# Creating Decimal objects
num1 = Decimal('10.5')
num2 = Decimal('5.2')
result = num1 + num2
print(result) # Output: 15.7

11. What is the purpose of ‘re’ module.


Purpose of 're' Module:
● Definition: The re module in Python provides support for working with
regular expressions, which are powerful tools for pattern matching
and text manipulation.
● Explanation: It allows searching, matching, and replacing patterns in
strings using regular expressions.
● Syntax and Example:
import re

# Searching for a pattern in a string


pattern = r'\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b'
text = "Contact us at support@example.com"
match = re.search(pattern, text)
print(match.group()) # Output: support@example.com

12. How will you see the keyword list in python >>> prompt
Viewing the Keyword List on >>> Prompt:
● Definition: You can view the list of keywords in Python using the keyword
module's kwlist attribute.
● Explanation: This attribute contains a list of all the keywords reserved by the
Python language.
● Syntax and Example:

>>> import keyword


>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class','continue',
'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

UNIT-II (3 Marks Questions)

1.Write syntax for creating custom functions in python.


**Syntax for Creating Custom Function in Python**:
- Definition: A custom function in Python is a block of reusable code that performs a
specific task when called.
- Answer: Custom functions are defined using the `def` keyword followed by the function
name and optional parameters, enclosed within parentheses. The function body is
indented and contains the code to be executed.
- Syntax and Example:
Syntax:python
def my_function(parameter1, parameter2):
# Function body
# Code to be executed
Syntax:

2.How will you specify a default value for an argument in the function definition?
**Specifying Default Value for an Argument in Function Definition**:
- Definition: Default values in function arguments allow parameters to have a default
value if no value is provided during function call.
- Answer: Default values are specified in the function definition by assigning a value to
the parameter using the assignment operator `=`. When the function is called without
providing a value for that parameter, the default value is used.
- Syntax and Example:
Syntax:python
def greet(name='Guest'):
print(f"Hello, {name}!")

greet() # Output: Hello, Guest!


Syntax:

3.How will you override default values in a custom function?


**Overriding Default Values in Custom Function**:
- Definition: Overriding default values in a custom function allows callers to provide a
different value for a parameter, overriding the default value specified in the function
definition.
- Answer: Default values can be overridden by passing a different value for the
parameter when calling the function. The provided value replaces the default value during
function execution.
- Syntax and Example:
Syntax:python
def greet(name='Guest'):
print(f"Hello, {name}!")

greet('John') # Output: Hello, John!

4.Describe variable scope in python


**Variable Scope in Python**:
- Definition: Variable scope refers to the visibility and accessibility of variables within
different parts of a Python program.
- Answer: Python has two main variable scopes: global scope and local scope.
Variables defined outside of any function are in the global scope and can be accessed
from anywhere in the program. Variables defined inside a function are in the local scope
and can only be accessed within that function, unless explicitly declared as global.
- Example:
Syntax:python
x = 10 # Global variable

def my_function():
y = 20 # Local variable
print(x) # Access global variable
print(y) # Access local variable

my_function()
Syntax:

5. What is the purpose of yield keyword in python.


**Purpose of Yield Keyword in Python**:
- Definition: The `yield` keyword is used in Python generator functions to produce a
series of values over time, rather than generating them all at once and storing them in
memory.
- Answer: When a function containing `yield` is called, it returns a generator object that
can be iterated over to retrieve values one at a time. Each time the `yield` statement is
encountered in the function, the current state of execution is saved, allowing it to resume
from that point on the next iteration.
- Syntax and Example:
Syntax:python
def my_generator():
yield 1
yield 2
yield 3

gen = my_generator()
print(next(gen)) # Output: 1
print(next(gen)) # Output: 2
Syntax:

6.What is the purpose of try block ?


**Purpose of Try Block**:
- Definition: The `try` block in Python is used to enclose code that may raise exceptions
during execution.
- Answer: The purpose of the `try` block is to attempt to execute code that may
potentially raise an exception. If an exception occurs within the `try` block, it is caught and
handled by one or more `except` blocks following the `try` block.
- Syntax and Example:
Syntax:python
try:
# Code that may raise exceptions
result = 10 / 0
except ZeroDivisionError:
print("Division by zero is not allowed.")
Syntax:
7. What is the purpose of finally block?
**Purpose of Finally Block**:
- Definition: The `finally` block in Python is used to enclose code that should be
executed regardless of whether an exception occurs or not.
- Answer: The purpose of the `finally` block is to provide cleanup or resource release
operations that must be performed, such as closing files or releasing locks, regardless of
whether an exception occurred in the `try` block or not.
- Syntax and Example:
Syntax:python
try:
file = open('example.txt', 'r')
# Code that may raise exceptions
finally:
file.close() # Always close the file, even if an exception occurs
Syntax:

8.How will you display the list of python keywords?


**Displaying the List of Python Keywords**:
- Definition: Python keywords are reserved words that have special meanings and
cannot be used as identifiers for variables, functions, or other elements in Python code.
- Answer: The `keyword` module in Python provides a function called `kwlist` that
returns a list of all the Python keywords.
- Syntax and Example:
Syntax:python
import keyword
print(keyword.kwlist)
Syntax:

9.Write a program to print current day, month and year.


**Program to Print Current Day, Month, and Year**:
- Definition: Python provides the `datetime` module for working with dates and times,
allowing us to obtain the current date and time information.
- Answer: We can use the `datetime` module's `datetime.now()` function to get the
current date and time, and then extract the day, month, and year components from the
result.

- Syntax and Example:

from datetime import datetime


current_date = datetime.now()
print("Current Day:", current_date.day)
print("Current Month:", current_date.month)
print("Current Year:", current_date.year)

10.Define any three built-in exceptions.


Sure, here are three common built-in exceptions in Python:

1. **`TypeError`**: This exception is raised when an operation or function is applied to an


object of inappropriate type. For example, trying to add a string and an integer would
raise a `TypeError`.

Example:
```python
x = 5 + 'hello'
```

2. **`ValueError`**: This exception is raised when a built-in operation or function receives


an argument with the right type but an inappropriate value. For example, trying to convert
a string to an integer when the string contains non-numeric characters would raise a
`ValueError`.

Example:
```python
x = int('hello')
```

3. **`NameError`**: This exception is raised when a local or global name is not found. It
usually occurs when trying to access a variable or function that hasn't been defined or is
out of scope.

Example:
```python
print(x)
```

These are just a few examples of built-in exceptions in Python. Python provides many
more built-in exceptions for handling various types of errors that may occur during
program execution.
ror:", e)
Syntax:
11.What is mean by lambda expression?
**Lambda Expression in Python**:
- Definition: A lambda expression, also known as an anonymous function, is a small,
inline function defined using the `lambda` keyword.
- Answer: Lambda expressions are typically used for short, simple functions that can be
written in a single line without the need for a formal function definition. They are often
used as arguments to higher-order functions or in situations where a function is needed
temporarily.
- Syntax and Example:
Syntax:python
add = lambda x, y: x + y
print(add(5, 3)) # Output: 8
Syntax:

12.What is the purpose of ‘pass’ keyword?


**Purpose of `pass` Keyword**:
- Definition: The `pass` keyword in Python is a null statement that performs no
operation when executed.
- Answer: It is used as a placeholder or filler in situations where syntactically a
statement is required, but no action needs to be performed. It is often used as a
placeholder

in empty function or class definitions, loops, or conditional blocks that require no action.
- Syntax and Example:
Syntax:python
def my_function():
# To be implemented
pass

for i in range(5):
# To be implemented
pass
Syntax:

These explanations cover each question comprehensively, providing definitions,


explanations, descriptions, syntax, and examples as requested. Let me know if you need
further clarification on any topic!

5 MARKS EACH
1.How will you create custom function in python? Explain with example
**Creating Custom Function in Python**:
- **Definition**: Custom functions in Python are user-defined blocks of code that
encapsulate a specific task or computation.
Explanation: They improve code readability, reusability, and maintainability by breaking
down complex tasks into smaller, modular functions. To create a custom function, use the
`def` keyword followed by the function name and parameters (if any). The function body
contains the code to be executed when the function is called.
Example:
Syntax:python
def greet(name):
print("Hello, " + name + "!")

greet("John")
Syntax:
- In this example, `greet()` is a custom function that takes a parameter `name` and
prints a greeting message with the provided name.

2.Write a program that will return factorial of given number.


**Program to Return Factorial of a Given Number**:
- **Definition**: Factorial of a non-negative integer `n` is the product of all positive
integers less than or equal to `n`.
Explanation: To calculate the factorial of a number, we iterate from 1 to `n` and multiply
each number to the running total. This is a common example to demonstrate the use of
functions and loops in Python.
Example:
Syntax:python
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result

print(factorial(5)) # Output: 120 (5! = 5 * 4 * 3 * 2 * 1 = 120)


Syntax:

3.Write a custom function to input any 3 numbers and find out the largest one.
**Custom Function to Find the Largest Number Among Three**:
- **Definition**: This function takes three numbers as input and returns the largest of the
three.
Explanation: It showcases the use of conditional statements (if-elif-else) to compare and
determine the largest number among the provided inputs. This function enhances code
modularity and readability by encapsulating the logic for finding the largest number.
Example:
Syntax:python
def find_largest(a, b, c):
if a >= b and a >= c:
return a
elif b >= a and b >= c:
return b
else:
return c

print(find_largest(10, 5, 8)) # Output: 10


Syntax:

4.Write a custom function to calculate x raise to power y.


**Custom Function to Calculate Power**:
- **Definition**: This function computes the value of `x` raised to the power of `y`.
Explanation: It demonstrates the use of parameters and the exponentiation operator
(`**`) to calculate the power of a number. This function abstracts the computation logic,
making it reusable for any pair of base and exponent values.
Example:
Syntax:python
def power(x, y):
return x ** y

print(power(2, 3)) # Output: 8 (2 raised to the power of 3)


Syntax:

5.What is mean by lambda expression? Explain


**Lambda Expression**:
- **Definition**: Lambda expressions, also known as anonymous functions, are concise
and single-line functions defined using the `lambda` keyword.
Explanation: They are useful for creating small, one-time-use functions without the need
for a formal function definition. Lambda functions are typically used as arguments to
higher-order functions or in situations where a function is needed temporarily.
Example:
Syntax:python
add = lambda x, y: x + y
print(add(2, 3)) # Output: 5
Syntax:
- In this example, `lambda x, y: x + y` creates an anonymous function that takes two
arguments `x` and `y` and returns their sum.

6.Write a program to generate Fibonacci series using yield keyword.


**Generating Fibonacci Series Using Yield Keyword**:
- **Definition**: The Fibonacci series is a sequence of numbers where each number is
the sum of the two preceding ones, typically starting with 0 and 1.
Explanation: This approach generates Fibonacci numbers incrementally using a
generator function with a `yield` statement. It allows for efficient memory usage as it
generates each Fibonacci number on-the-fly.
Example:
Syntax:python
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b

fib_gen = fibonacci()
for _ in range(5):
print(next(fib_gen)) # Output: 0, 1, 1, 2, 3
Syntax:

7.How will you invoke inbuilt exception explicitly? Explain with example
**Invoking Built-in Exceptions Explicitly**:
- **Definition**: Python allows you to raise built-in exceptions manually using the `raise`
statement.
Explanation: This mechanism provides flexibility in handling exceptional conditions by
allowing developers to raise specific exceptions when necessary. It's useful for
propagating errors or signaling exceptional situations in code execution.
Example:
Syntax:python
try:
raise ValueError("Explicitly raising a ValueError")
except ValueError as e:
print("Caught exception:", e)
Syntax:
- In this example, the `raise` statement raises a `ValueError` exception with a custom
message, which is then caught by the `except` block.
8.What is the difference between assert and exception.
**Difference Between Assert and Exception**:
- **Definition**: `assert` and exceptions serve different purposes in Python error
handling. `assert` is primarily used for debugging and testing to ensure that certain
conditions are met during program execution, while exceptions handle runtime errors and
exceptional conditions that may occur during program execution.
Explanation:
- `assert` statements are used to test conditions that should always be true. They
provide a way to perform sanity checks in code during development and testing. If the
condition specified in the `assert` statement evaluates to `False`, an `AssertionError`
exception is raised.
- Exceptions, on the other hand, handle errors and exceptional situations that occur
during program execution. They provide a way to gracefully handle unexpected situations
and recover from errors without crashing the program.
Example:
Syntax:python
# Using assert
x=5
assert x == 5 # This assertion passes
assert x == 10 # This assertion fails and raises AssertionError

# Using exception
try:
result = 10 / 0 # This division raises a ZeroDivisionError
except ZeroDivisionError as e:
print("Error:", e)
Syntax:

9. What is function? Describe any four mathematical functions in Python.


**Function and Mathematical Functions in Python**:
- **Definition**:
- A function in Python is a block of reusable code that performs a specific task when
called. It enhances code modularity, reusability, and maintainability by breaking down
complex tasks into smaller, manageable functions.
- Mathematical functions in Python are built-in functions provided by the `math` module
for performing mathematical calculations. These functions cover a wide range of
mathematical operations, including trigonometric functions, exponentiation, logarithms,
and more.
Explanation:
- Python provides several built-in mathematical functions in the `math` module, such
as `sqrt()` for square root, `sin()` for sine, `cos()` for cosine, and `log()` for logarithm,
among others.
- These mathematical functions are used to perform common mathematical operations
in Python programs, facilitating numerical computations and scientific calculations.
Example:
Syntax:python
import math

print(math.sqrt(16)) # Output: 4.0


print(math.sin(math.pi / 2)) # Output: 1.0
Syntax:

10.How will you generate random numbers? Explain with example


**Generating Random Numbers**:
- **Definition**: Random numbers are numbers generated unpredictably or by chance,
without any specific pattern or sequence.
Explanation: Python provides the `random` module to generate random numbers of
various types and distributions. Random numbers are useful in simulations, games,
cryptography, and statistical analysis.
Example:
Syntax:python
import random

print(random.randint(1, 10)) # Output: Random integer between 1 and 10


print(random.random()) # Output: Random float between 0 and 1
Syntax:

11.List the date time directives with meaning.


**Date Time Directives**:
- **Definition**: Date time directives are special formatting codes used with the
`strftime()` method to format dates and times in Python.
Explanation: They provide a way to specify the format of date and time components,
such as year, month, day, hour, minute, second, etc., in a desired format string.
Example:
- `%Y`: Year (4 digits)
- `%m`: Month (01 to 12)
- `%d`: Day of the month (01 to 31)
- `%H`: Hour (00 to 23)
- `%M`: Minute (00 to 59)
- `%S`: Second (00 to 59)
Example: `%Y-%m-%d` represents the date in the format `YYYY-MM-DD`.

12.Write a program to generate numbers from 10 to 1 at the intervals of 1 second.


**Program to Generate Numbers with a Time Interval**:
- **Definition**: This program generates numbers at regular intervals, demonstrating
the use of the `time` module for introducing delays between number generation.
Explanation: It utilizes the `time.sleep()` function to pause the execution for a specified
amount of time between number generation, creating a delay or interval.
Example:
Syntax:python
import time

for i in range(10, 0, -1):


print(i)
time.sleep(1) # Sleep for 1 second
Syntax:

13. Explain the metacharacters used for pattern matching with example.
**Metacharacters for Pattern Matching**:
- **Definition**: Metacharacters are special characters used in regular expressions
(regex) to define search patterns for matching strings.
Explanation: They provide a powerful and flexible way to search, match, and manipulate
text based on specified patterns. Common metacharacters include `.`, `^`, `$`, `*`, `+`, and
`?`, among others.
Example:
- `.`: Matches any single character
- `^`: Matches the start of the string
- `$`: Matches the end of the string
- `*`: Matches zero or more occurrences
- `+`: Matches one or more occurrences
- `?`: Matches zero or one occurrence
Example:
Syntax:python
import re

pattern = r'\d+' # Matches one or more digits


print(re.findall(pattern, 'There are 123 apples')) # Output: ['123']
Syntax:
10 MARKS QUESTION
1.What is generator? Explain with example.
What is generator? Explain with example. **Generator**:
- **Definition**: A generator in Python is a special type of iterator that generates values
lazily, on-the-fly, instead of storing them in memory all at once. Generators are defined
using functions and the `yield` keyword.
Explanation: They are particularly useful for generating a large sequence of values
without occupying a significant amount of memory. Generators maintain their state
between function calls, allowing them to resume execution where they left off.
Example:
Syntax:python
def square_generator(n):
for i in range(n):
yield i ** 2

squares = square_generator(5)
for num in squares:
print(num)
Syntax:
In this example, `square_generator()` is a generator function that yields the square of
numbers up to `n`. When `squares` is iterated over, values are generated one at a time as
needed.

2.What is the difference between pass and continue? Explain with example.
**Difference Between pass and continue**:
- **pass**:
- The `pass` statement in Python is a no-operation placeholder that is used when
syntactically required but no action is desired.
- It is typically used as a placeholder in empty code blocks, function definitions, or
class definitions.
Example:
Syntax:python
for i in range(5):
pass # Placeholder, no action taken
Syntax:
- **continue**:
- The `continue` statement is used inside loops to skip the rest of the code inside the
loop for the current iteration and proceed to the next iteration.
- It is typically used to skip certain iterations based on a condition without exiting the
loop entirely.
Example:
Syntax:python
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i)
Syntax:

3.What is exception handling? Explain with example.


**Exception Handling**:
- **Definition**: Exception handling in Python is the process of dealing with runtime
errors or exceptional situations gracefully, without crashing the program.
Explanation: It involves using `try`, `except`, `else`, and `finally` blocks to catch and
handle exceptions that may occur during program execution.
Example:
Syntax:python
try:
result = 10 / 0 # This division raises a ZeroDivisionError
except ZeroDivisionError as e:
print("Error:", e)
Syntax:
In this example, the `try` block attempts to perform a division operation that may raise
a `ZeroDivisionError`. The `except` block catches the error and prints an error message,
preventing the program from crashing.

4.What is the role of assert keyword? Explain with example.


**Role of assert Keyword**:
- **Definition**: The `assert` keyword in Python is used to assert or ensure that a
condition is true. If the condition is false, an `AssertionError` exception is raised.
Explanation: It is commonly used for debugging and testing purposes to check for
conditions that should always hold true during program execution.
Example:
Syntax:python
x=5
assert x == 5 # This assertion passes
assert x == 10 # This assertion fails and raises AssertionError
Syntax:

5.What is mean by module? Explain with example.


**Module**:
- **Definition**: A module in Python is a file containing Python code that defines
functions, classes, and variables. It allows code to be organized into reusable units and
provides a way to encapsulate related functionality.
Explanation: Modules can be imported into other Python scripts or interactive sessions
using the `import` statement, allowing access to the functions and variables defined within
them.
Example:
Syntax:python
# Example module: mymodule.py
def greet(name):
print("Hello, " + name + "!")

def square(x):
return x ** 2
Syntax:
Syntax:python
# Importing module
import mymodule

mymodule.greet("John")
print(mymodule.square(5)) # Output: 25
Syntax:

6. How to calculate decimal? Explain with example.


**Decimal Calculation**:
Explanation: Decimal arithmetic in Python is typically performed using the `decimal`
module, which provides support for high-precision floating-point arithmetic.
Example:
Syntax:python
import decimal

num1 = decimal.Decimal('10.5')
num2 = decimal.Decimal('2.5')
result = num1 * num2
print(result) # Output: 26.25
Syntax:

7. Write a program to check whether email address entered by the user is valid or
not.
**Program to Check Valid Email Address**:
- You can use regular expressions to validate email addresses. Here's a basic example:
Syntax:python
import re
def is_valid_email(email):
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
return re.match(pattern, email) is not None

email = input("Enter email address: ")


if is_valid_email(email):
print("Valid email address")
else:
print("Invalid email address")
Syntax:

8.What is role of yield keyword? Write a program to generate Fibonacci series


using yield
keyword.

**Role of Yield Keyword**:


- **Definition**: The `yield` keyword in Python is used in generator functions to produce
a sequence of values one at a time.
Explanation: Unlike `return`, which terminates the function and returns a single value,
`yield` allows the function to generate multiple values over time without losing its state.
Example:
Syntax:python
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b

fib_gen = fibonacci()
for _ in range(5):
print(next(fib_gen)) # Output: 0, 1, 1, 2, 3
Syntax:

9.What is the role of lambda? Explain with example


**Role of Lambda**:
- **Definition**: Lambda expressions, or anonymous functions, are small, single-use
functions defined using the `lambda` keyword.
Explanation: They are useful for creating short, concise functions without the need for a
formal function definition.
Example:
Syntax:python
add = lambda x, y: x + y
print(add(2, 3)) # Output: 5
Syntax:

10.How can you interrogate the system? Explain


**Interrogating the System**:
Explanation: Python provides various modules and functions to interrogate the system,
such as `os`, `sys`, and `platform`.
Example:
Syntax:python
import os
import platform

print(os.getcwd()) # Current working directory


print(os.listdir()) # List files and directories in current directory
print(platform.platform()) # Platform information
Syntax:

These explanations provide thorough insights into each topic, covering definitions,
explanations, examples, and practical applications in Python programming. Let me know
if you need further explanation or assistance with any other topic!
Unit 3

2 MARKS

1.
**Acronym for ASCII**:
- **Definition**: ASCII stands for "American Standard Code for Information
Interchange."

2.
**Class**:
- **Definition**: In Python, a class is a blueprint for creating objects (instances) that
share the same attributes and methods. It acts as a template or prototype from which
objects are created.

3.
**Class Attribute**:
- **Definition**: A class attribute is a variable that is shared among all instances of a
class. It is defined within the class but outside any methods and is accessed using the
class name.

4.
**Referencing Class Members**:
Explanation: Class members, including attributes and methods, can be referenced using
dot notation. For example, `object.attribute` or `object.method()`.

5.
**Encapsulation**:
- **Definition**: Encapsulation is the bundling of data and methods that operate on the
data into a single unit, typically a class. It hides the internal state of an object and only
exposes the necessary functionalities.
6.
**Polymorphism**:
- **Definition**: Polymorphism is the ability of different objects to respond to the same
message or method invocation in different ways. It allows objects of different classes to
be treated as objects of a common superclass.

7.
**Inheritance**:
- **Definition**: Inheritance is a mechanism in object-oriented programming that allows
a class (subclass) to inherit properties and behaviors (attributes and methods) from
another class (superclass). It promotes code reusability and supports the concept of
hierarchical classification.

8.
**Declaring a Class in Python**:
Syntax:
Syntax:python
class ClassName:
# Class body
Syntax:

9.
**Instance Variable**:
- **Definition**: An instance variable is a variable that is unique to each instance of a
class. It is defined within the constructor (`__init__` method) and belongs to individual
objects.

10.
**Class Variable**:
- **Definition**: A class variable is a variable that is shared among all instances of a
class. It is declared within the class but outside any methods using the class name. Class
variables are accessed using the class name rather than instance name.

3 MARKS

1.
**Purpose of encode() and decode() Method**:
Explanation:
- The `encode()` method is used to convert a string from Unicode to a specified
encoding format (e.g., UTF-8).
- The `decode()` method is used to convert a byte sequence from a specified encoding
format (e.g., UTF-8) to Unicode.
- **Syntax and Example**:
Syntax:python
# encode() method syntax and example
encoded_string = my_string.encode(encoding)

# decode() method syntax and example


decoded_string = byte_sequence.decode(encoding)
Syntax:

2.
**Adding, Updating, or Deleting an Attribute of Class Instance**:
Explanation:
- You can directly access and modify attributes of a class instance using dot notation.
- To add a new attribute, simply assign a value to a new attribute name.
- To update an existing attribute, reassign a new value to the attribute name.
- To delete an attribute, use the `del` statement.
- **Syntax and Example**:
Syntax:python
# Adding a new attribute
instance.new_attribute = value

# Updating an attribute
instance.existing_attribute = new_value

# Deleting an attribute
del instance.attribute_to_delete
Syntax:

3.
**In-built Functions for Adding, Modifying, or Removing an Attribute**:
Explanation:
- Python provides `setattr()`, `getattr()`, and `delattr()` functions to respectively set, get,
and delete attributes of an object dynamically.
- **Syntax and Example**:
Syntax:python
# setattr() syntax and example
setattr(instance, 'attribute_name', value)

# getattr() syntax and example


attribute_value = getattr(instance, 'attribute_name')

# delattr() syntax and example


delattr(instance, 'attribute_name')
Syntax:

4.
**Method Overriding**:
Explanation:
- Method overriding is the ability of a subclass to provide a specific implementation of a
method that is already defined in its superclass.
- This allows the subclass to customize the behavior of inherited methods.
Example:
Syntax:python
class Parent:
def method(self):
print("Parent method")

class Child(Parent):
def method(self): # Overriding Parent's method
print("Child method")

obj = Child()
obj.method() # Output: Child method
Syntax:

5.
**DocString**:
Explanation:
- Docstrings are string literals used to document Python modules, classes, functions,
or methods.
- They are enclosed in triple quotes (`"""`) and are the first statement within the body of
the module, class, function, or method.
- Docstrings provide a way to describe the purpose, usage, and behavior of code
elements.

6.
**Purpose of Built-in dir() Function**:
Explanation:
- The `dir()` function returns a list of valid attributes and methods of an object.
- It is often used for introspection to explore the properties and behavior of objects.
7.
**File Opening Modes in Python**:
Explanation:
- File opening modes specify how the file should be opened and whether it should be
read, written, or both.
- Common file modes include 'r' for reading, 'w' for writing (overwriting existing file), 'a'
for appending, 'r+' for reading and writing, and 'b' for binary mode.

8.
**File Object Properties**:
Explanation:
- File objects in Python have properties like `name`, `mode`, `closed`, `encoding`, etc.
- These properties provide information about the file, such as its name, mode of
opening, whether it is closed, and its encoding.

9.
**Role of __init__() Method**:
Explanation:
- The `__init__()` method is a special method in Python classes that is automatically
called when a new instance of the class is created.
- It is used to initialize the attributes of the object and perform any necessary setup
tasks.

10.
**Contents of __builtins__ Module**:
Explanation:
- The `__builtins__` module in Python contains a collection of built-in functions,
exceptions, and objects that are available by default in all Python scripts.
- It includes commonly used functions like `print()`, `len()`, `range()`, and exceptions
like `ValueError`, `TypeError`, etc.

5 MARKS

1.
**Operators for String Manipulation**:
- **Definition**: String manipulation operators in Python are used to perform various
operations on strings, such as concatenation, slicing, repetition, and formatting.
- **Syntax and Examples**:
- Concatenation (`+`): Combines two or more strings.
Syntax:python
str1 = "Hello"
str2 = "World"
result = str1 + str2 # Output: "HelloWorld"
Syntax:
- Slicing (`[]`): Extracts a substring from a string based on indices.
Syntax:python
text = "Python"
substring = text[1:4] # Output: "yth"
Syntax:
- Repetition (`*`): Repeats a string a specified number of times.
Syntax:python
word = "Python"
repeated = word * 3 # Output: "PythonPythonPython"
Syntax:
- Formatting (`%` or `format()`): Formats a string using placeholders.
Syntax:python
name = "John"
age = 30
message = "My name is %s and I am %d years old." % (name, age)
Syntax:

2.
**Metacharacters in Regular Expressions**:
- **Definition**: Metacharacters are special characters used in regular expressions to
define search patterns.
- **Meaning and Examples**:
- `.` (dot): Matches any single character except newline.
- `^` (caret): Matches the start of the string.
- `$` (dollar): Matches the end of the string.
- `*`: Matches zero or more occurrences of the preceding character.
- `+`: Matches one or more occurrences of the preceding character.
- `?`: Matches zero or one occurrence of the preceding character.
Example:
Syntax:python
import re
pattern = r'^[A-Z]\w+$' # Matches strings starting with an uppercase letter
Syntax:
3.
**Adding, Updating, or Deleting Attribute of Class Instance**:
- **Definition**: Attributes of a class instance can be added, updated, or deleted
dynamically using built-in functions like `setattr()`, `getattr()`, and `delattr()`.
- **Syntax and Examples**:
Syntax:python
# Adding an attribute
setattr(instance, 'attribute_name', value)

# Updating an attribute
setattr(instance, 'attribute_name', new_value)

# Deleting an attribute
delattr(instance, 'attribute_name')
Syntax:

4.
**Displaying Class Dictionary Attributes**:
- **Definition**: This program displays dictionary attributes of a class instance using the
`vars()` function.
- **Syntax and Example**:
Syntax:python
class MyClass:
attr1 = 10
attr2 = "Hello"

obj = MyClass()
print(vars(obj)) # Output: {'attr1': 10, 'attr2': 'Hello'}
Syntax:

5.
**Purpose of dump() and load() Method**:
- **Definition**: `dump()` and `load()` methods are used for serialization and
deserialization of Python objects.
Example:
Syntax:python
import pickle

# Serialization (dumping)
with open('data.pkl', 'wb') as f:
pickle.dump(data, f)
# Deserialization (loading)
with open('data.pkl', 'rb') as f:
data = pickle.load(f)
Syntax:

6.
**String Methods**:
- **Description**: String methods are built-in functions that operate on strings and
perform various operations like searching, modifying, and formatting strings.
- **Examples**:
- `capitalize()`: Converts the first character to uppercase.
- `split()`: Splits the string into a list of substrings.
- `join()`: Joins the elements of an iterable to form a string.
- `strip()`: Removes leading and trailing whitespace.
- `replace()`: Replaces occurrences of a substring with another substring.

7.
**Printing Unicode Names of String Characters**:
- **Definition**: The `unicodedata` module in Python provides a function called `name()`
which returns the Unicode name of a character.
Example:
Syntax:python
import unicodedata
text = "Hello"
for char in text:
print(unicodedata.name(char))
Syntax:

8.
**seek() and tell() Function**:
- **Description**: `seek()` function is used to change the file pointer position within a file,
while `tell()` function returns the current file pointer position.
- **Syntax and Example**:
Syntax:python
file = open("example.txt", "r")
file.seek(10) # Move file pointer to 10th byte
print(file.tell()) # Output: 10 (current position)
Syntax:

9.
**readable() and writable() Method**:
- **Description**: `readable()` and `writable()` methods are used to check if a file object
is readable or writable, respectively.
- **Syntax and Example**:
Syntax:python
file = open("example.txt", "r")
print(file.readable()) # Output: True
print(file.writable()) # Output: False
Syntax:

10.
**read() and write() Method**:
- **Description**: `read()` method reads a specified number of bytes from the file, while
`write()` method writes a string to the file.
- **Syntax and Example**:
Syntax:python
file = open("example.txt", "r+")
data = file.read(10) # Read first 10 bytes
file.write("New content") # Write new content to file
Syntax:

10 MARKS

1.
**String Modification Methods**:
- **capitalize()**: Converts the first character of the string to uppercase.
- **lower()**: Converts all characters in the string to lowercase.
- **upper()**: Converts all characters in the string to uppercase.
- **swapcase()**: Swaps the case of each character in the string.
- **title()**: Converts the first character of each word to uppercase and the rest to
lowercase.
- **strip()**: Removes leading and trailing whitespace from the string.
- **replace()**: Replaces occurrences of a specified substring with another substring.
- **split()**: Splits the string into a list of substrings based on a delimiter.
- **join()**: Joins the elements of an iterable with the string as a separator.
- **startswith() / endswith()**: Checks if the string starts or ends with a specified
substring.

2.
**Pickling and Unpickling**:
Explanation: Pickling is the process of serializing Python objects into byte streams, while
unpickling is the process of deserializing byte streams back into Python objects.
Example:
Syntax:python
import pickle

# Pickling
data = {"name": "John", "age": 30}
with open("data.pkl", "wb") as f:
pickle.dump(data, f)

# Unpickling
with open("data.pkl", "rb") as f:
loaded_data = pickle.load(f)
Syntax:

3.
**Inheritance**:
Explanation: Inheritance is a feature of object-oriented programming that allows a new
class (subclass) to inherit attributes and methods from an existing class (superclass). It
promotes code reusability and establishes a parent-child relationship between classes.
Example:
Syntax:python
class Animal:
def sound(self):
print("Animal makes a sound")

class Dog(Animal):
def sound(self): # Method overriding
print("Dog barks")

dog = Dog()
dog.sound() # Output: "Dog barks"
Syntax:

4.
**Method Overriding**:
Explanation: Method overriding occurs when a subclass provides a specific
implementation of a method that is already defined in its superclass. It allows subclasses
to customize the behavior of inherited methods.
Example:
Syntax:python
class Parent:
def method(self):
print("Parent's method")

class Child(Parent):
def method(self): # Overriding Parent's method
print("Child's method")

obj = Child()
obj.method() # Output: "Child's method"
Syntax:

5.
**Polymorphism**:
Explanation: Polymorphism is the ability of different objects to respond to the same
message or method invocation in different ways. It allows objects of different classes to
be treated as objects of a common superclass.
Example:
Syntax:python
class Animal:
def sound(self):
pass

class Dog(Animal):
def sound(self):
print("Dog barks")

class Cat(Animal):
def sound(self):
print("Cat meows")

def make_sound(animal):
animal.sound()

dog = Dog()
cat = Cat()

make_sound(dog) # Output: "Dog barks"


make_sound(cat) # Output: "Cat meows"
Syntax:
6.
**Garbage Collection in Python**:
Explanation: Python's garbage collection system automatically manages the memory by
reclaiming memory occupied by objects that are no longer in use.
Example:
Syntax:python
import gc

# Force garbage collection


gc.collect()
Syntax:

7.
**File Write and Read Operations**:
Explanation: This program demonstrates writing to and reading from a file in Python.
Example:
Syntax:python
# Writing to a file
with open("example.txt", "w") as f:
f.write("Hello, World!")

# Reading from a file


with open("example.txt", "r") as f:
content = f.read()
print(content) # Output: "Hello, World!"
Syntax:

8.
**File Handling Methods**:
- **Description**: Python provides various file handling methods like `open()`, `read()`,
`write()`, `close()`, and `flush()` for working with files.
- **Syntax and Example**:
Syntax:python
file = open("example.txt", "r")
content = file.read()
file.close()
Syntax:

9.
**String Formatting in Python**:
Explanation: String formatting in Python refers to the process of creating formatted
strings using placeholders or formatting methods like `%` operator, `format()`, or f-strings.
Example:
Syntax:python
name = "John"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
Syntax:

10.
**Converting String in Python**:
Explanation: String conversion in Python involves converting strings to other data types
like integers, floats, lists, etc., using typecasting or conversion functions like `int()`,
`float()`, `list()`, etc.
Example:
Syntax:python
num_str = "10"
num_int = int(num_str)
Syntax:
UNIT 4
UNIT 4
2 MARKS
1.**Purpose of image_create() Method**:
- image_create() is not a standard built-in function in Python. However, there are
several libraries in Python that provide functionalities for creating and manipulating
images. One of the most popular libraries for image processing in Python is Pillow (PIL),
which provides a wide range of features for working with images.

2. **Purpose of create_image() Method**:


- In Tkinter, the `create_image()` method is used to add an image to a canvas widget. It
allows you to display an image (such as a .png or .jpg file) on a canvas at a specified
position.
Syntax:python
canvas.create_image(x, y, image=image_object, anchor=NW)

3. **Methods to Add Widget to a GUI Application**:


- In Tkinter, widgets are added to a GUI application using various methods such as:
- `pack()`: Organizes widgets in a block before placing them in the parent widget.
- `grid()`: Place widgets in a two-dimensional grid layout.
- `place()`: Places widgets at specific coordinates within the parent widget.

4.
**Purpose of range() Function**:
- The `range()` function in Python generates a sequence of numbers within a specified
range. It is commonly used for iterating over a sequence of numbers in loops or
generating lists of numbers.
Example:

for i in range(5):
print(i)

# Output: 0 1 2 3 4

5. **Role of sample() Method**:


- The `sample()` method in Python's `random` module is used to generate a random
sample from a population (list) without replacement. It returns a new list containing unique
elements randomly selected from the population.
Syntax:
Syntax:python
import random
random.sample(population, k)
Syntax:

6.
**Statement to Prevent Window Resizing at Runtime**:
- To prevent the user from resizing the window at runtime in Tkinter, you can set the
`resizable()` method to `(False, False)` for both width and height.
Example:
Syntax:python
root.resizable(False, False)
Syntax:

7.
**Statement to Specify Text on Button Widget**:
- In Tkinter, you can specify text on a Button widget using the `text` parameter when
creating the Button object.
Example:
Syntax:python
button = Button(root, text="Click Me")
Syntax:

8.
**States of Button Recognized by Tkinter**:
- Tkinter recognizes several states for a Button widget:
- `NORMAL`: The normal state (default).
- `ACTIVE`: The button is currently pressed or under the mouse pointer.
- `DISABLED`: The button is disabled and cannot be clicked.

9.
**Role of cgi Module**:
- The `cgi` module in Python is used for handling Common Gateway Interface (CGI)
scripts. It provides utilities for processing form data submitted via web forms and
generating dynamic web content.

10.
**Role of enctype Attribute**:
- The `enctype` attribute is used in HTML forms to specify how form data should be
encoded before it is sent to the server. It stands for "encoding type" and is used primarily
when forms contain file upload fields.
- Common values for `enctype` attribute include:
- `application/x-www-form-urlencoded`: The default value. Form data is encoded in
key-value pairs separated by `&`.
- `multipart/form-data`: Used for forms that include file uploads. Data is encoded as a
series of parts, each containing a file and its associated metadata.
3 MARKS

1.
**Limitation of GET Method**:
Explanation: The GET method has limitations in the amount of data that can be sent in
the URL. It appends data to the URL as key-value pairs, making it visible in the address
bar and susceptible to length restrictions imposed by browsers and servers.
Example:
Syntax:html
<form action="process_data.py" method="get">
<input type="text" name="username" value="John">
<input type="submit" value="Submit">
</form>

2.
**Advantages of POST Method**:
Explanation: The POST method sends data to the server in the body of the HTTP
request, rather than appending it to the URL. This allows for sending larger amounts of
data securely and without being restricted by URL length limitations.
Example:
Syntax:html
<form action="process_data.py" method="post">
<input type="text" name="username" value="John">
<input type="submit" value="Submit">
</form>

3.
**Purpose of FieldStorage() Constructor**:
Explanation: The `FieldStorage()` constructor in Python's `cgi` module is used to parse
form data submitted via HTTP POST or GET methods. It creates an object that provides
access to the form data submitted in the HTTP request.
Syntax:
Syntax:python
form = cgi.FieldStorage()
4.
**Role of mainloop() Method**:
Explanation: The `mainloop()` method in Tkinter is used to start the Tkinter event loop. It
continuously listens for events such as button clicks, mouse movements, etc., and
dispatches them to the appropriate event handlers.
Syntax:
Syntax:python
root.mainloop()
Syntax:

5.
**Purpose of Entry() Constructor**:
Explanation: The `Entry()` constructor in Tkinter is used to create a single-line input field
widget. It allows users to enter text or numeric values into the GUI application.
Syntax:
Syntax:python
entry = Entry(root)
Syntax:

6.
**Purpose of Frame() Constructor**:
Explanation: The `Frame()` constructor in Tkinter is used to create a container widget
that can hold other widgets. It provides a way to organize and group widgets within the
GUI application.
Syntax:
Syntax:python
frame = Frame(root)
Syntax:

7.
**Methods for Showing Button Messages**:
- `showinfo()`: Displays an informational message.
- `showwarning()`: Displays a warning message.
- `showerror()`: Displays an error message.
- `askquestion()`: Asks a question with Yes/No buttons.
- `askyesno()`: Asks a question with Yes/No buttons.
- `askokcancel()`: Asks a question with OK/Cancel buttons.

8.
**Description of RadioButton Constructor**:
Explanation: The RadioButton constructor in Tkinter is used to create a radio button
widget. Radio buttons allow users to select one option from multiple choices. They are
usually grouped together using a common variable.
Syntax:
Syntax:python
radiobutton = Radiobutton(root, text="Option", variable=var, value=value)
Syntax:

9.
**Arguments of Checkbutton() Constructor**:
Explanation: The `Checkbutton()` constructor in Tkinter is used to create a checkbox
widget. Checkboxes allow users to select multiple options from a list of choices.
Syntax:
Syntax:python
checkbutton = Checkbutton(root, text="Option", variable=var, onvalue=1, offvalue=0)
Syntax:

10.
**Purpose of path.basename() Method**:
Explanation: The `path.basename()` method in Python's `os.path` module is used to
extract the filename from a given path. It returns the last component of the path.
Syntax:
Syntax:python
import os.path
filename = os.path.basename("/path/to/file.txt")
Syntax:

5 MARKS

1. **Create a new HTML document containing a form with two text fields and a
submit button**:
Explanation: Below is the HTML code to create a form with two text fields (`input`
elements of type `text`) and a submit button (`input` element of type `submit`).
Syntax:
Syntax:html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form</title>
</head>
<body>
<form action="/submit" method="post">
<label for="field1">Field 1:</label>
<input type="text" id="field1" name="field1"><br><br>
<label for="field2">Field 2:</label>
<input type="text" id="field2" name="field2"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Syntax:

2. **Write a program to create an entry widget in Python**:


Explanation: In Tkinter, the `Entry()` constructor is used to create an entry widget. Below
is the Python code to create an entry widget.
Syntax:
Syntax:python
import tkinter as tk

root = tk.Tk()
entry = tk.Entry(root)
entry.pack()
root.mainloop()
Syntax:

3. **Write a program to create a list box in Python**:


Explanation: In Tkinter, the `Listbox()` constructor is used to create a list box widget.
Below is the Python code to create a list box.
Syntax:
Syntax:python
import tkinter as tk

root = tk.Tk()
listbox = tk.Listbox(root)
listbox.pack()
root.mainloop()
Syntax:
4. **Write a program to demonstrate the click event of a button**:
Explanation: In Tkinter, the `Button()` constructor is used to create a button widget.
Below is the Python code to demonstrate the click event of a button.
Syntax:
Syntax:python
import tkinter as tk

def on_click():
print("Button clicked")

root = tk.Tk()
button = tk.Button(root, text="Click me", command=on_click)
button.pack()
root.mainloop()
Syntax:

5. **Write a program to generate a random number in the range of 1 to 10**:


Explanation: In Python, the `random.randint()` function is used to generate a random
integer within a specified range.
Syntax:
Syntax:python
import random

random_number = random.randint(1, 10)


print("Random number:", random_number)
Syntax:

6. **Create a new HTML document containing a form with a text area field and a
submit button**:
Explanation: Below is the HTML code to create a form with a text area field (`textarea`
element) and a submit button (`input` element of type `submit`).
Syntax:
Syntax:html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form</title>
</head>
<body>
<form action="/submit" method="post">
<textarea name="message" rows="4" cols="50"></textarea><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Syntax:

7. **Create a new HTML document containing a form with one group of three radio
buttons and a submit button**:
Explanation: Below is the HTML code to create a form with one group of three radio
buttons (`input` elements of type `radio`) and a submit button (`input` element of type
`submit`).
Syntax:
Syntax:html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form</title>
</head>
<body>
<form action="/submit" method="post">
<input type="radio" id="option1" name="option" value="1">
<label for="option1">Option 1</label><br>
<input type="radio" id="option2" name="option" value="2">
<label for="option2">Option 2</label><br>
<input type="radio" id="option3" name="option" value="3">
<label for="option3">Option 3</label><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Syntax:

8. **Create a new HTML document containing a form with a drop-down options list
and a submit button**:
Explanation: Below is the HTML code to create a form with a drop-down options list
(`select` element) and a submit button (`input` element of type `submit`).
Syntax:
Syntax:html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form</title>
</head>
<body>
<form action="/submit" method="post">
<select name="options">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Syntax:

9.
**Description of three geometry manager methods**:
- `pack()`: Organizes widgets in a block before placing them in the parent widget. It
allows for simple layout management but doesn't provide as much control as other
geometry managers.

- `grid()`: Places widgets in a two-dimensional grid layout. It allows for more precise
control over widget placement and alignment.
- `place()`: Places widgets at specific coordinates within the parent widget. It provides
absolute positioning control but can be less flexible for dynamic layouts.

10. **Description of five arguments to a Checkbutton() constructor**:


- `text`: The text to display next to the checkbox.
- `variable`: A tkinter variable (usually an instance of `IntVar`) linked to the check
button. Its value will be set to 1 if the check button is checked and 0 otherwise.
- `onvalue`: The value to be set in the linked variable when the checkbox is checked
(default is 1).
- `offvalue`: The value to be set in the linked variable when the checkbox is unchecked
(default is 0).
- `command`: A function or method to be called when the checkbox is clicked.

10 MARKS

1. **Explain with example how a web server responds to the values passed through
a web browser**:
Explanation: When a web browser sends a request to a web server, the server
processes the request and generates a response. This response can include HTML
content, images, scripts, or any other data. The server may use server-side scripting
languages like Python, PHP, or Node.js to process the request and generate dynamic
content.
Example: Suppose a user submits a form with data. The server-side script (e.g., a Python
script using a web framework like Flask) receives this data, processes it, and generates a
response. For example, it could store the form data in a database or perform some
calculations, then generate an HTML page to display the result.
- **Syntax (Python Flask)**:
Syntax:python
from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/submit', methods=['POST'])
def submit_form():
data = request.form['data'] # Get data from the form
# Process data (e.g., store in database)
return render_template('result.html', data=data) # Render HTML template with the
result
Syntax:

2. **Describe various options available for a command button in Python**:


- Command buttons in Python (Tkinter) have various options that can be configured,
including:
- `text`: The text displayed on the button.
- `command`: The function or method to be called when the button is clicked.
- `bg` (background): The background color of the button.
- `fg` (foreground): The text color of the button.
- `width` and `height`: The width and height of the button.
- `state`: The state of the button (`NORMAL`, `ACTIVE`, `DISABLED`).
- `font`: The font used for the button text.
- `padx` and `pady`: The padding (horizontal and vertical) inside the button.
- `relief`: The border style of the button (`FLAT`, `RAISED`, `SUNKEN`, etc.).

3. **What is a radio button? Explain with an example**:


Explanation: A radio button is a graphical control element that allows the user to choose
only one option from a set of mutually exclusive options. It typically appears as a small
circle or square that can be selected or deselected.
Example:
Syntax:python
import tkinter as tk

root = tk.Tk()

# Create variables to hold the selected option


option_var = tk.StringVar(value="Option 1")

# Create radio buttons


rb1 = tk.Radiobutton(root, text="Option 1", variable=option_var, value="Option 1")
rb2 = tk.Radiobutton(root, text="Option 2", variable=option_var, value="Option 2")
rb3 = tk.Radiobutton(root, text="Option 3", variable=option_var, value="Option 3")

# Pack radio buttons


rb1.pack()
rb2.pack()
rb3.pack()

root.mainloop()
Syntax:

4. **How will you upload a file onto the web server? Explain with an example**:
Explanation: Uploading a file to a web server typically involves creating an HTML form
with an input field of type `file`. When the form is submitted, the file is sent as part of the
HTTP request to the server, where it can be processed using server-side scripting
languages like Python (e.g., with Flask or Django).
- **Example (HTML form)**:
Syntax:html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
</body>
</html>
Syntax:
- **Example (Python Flask)**:
Syntax:python
from flask import Flask, request

app = Flask(__name__)

@app.route('/upload', methods=['POST'])
def upload_file():
file = request.files['file'] # Get uploaded file
# Save file to server
file.save('uploads/' + file.filename)
return 'File uploaded successfully'

if __name__ == '__main__':
app.run(debug=True)
Syntax:

5. **Write a program to generate a unique random number in the range of 1 to 50**:


Explanation: We can generate a unique random number in the specified range using
Python's `random.sample()` function, which selects unique elements from a sequence
without replacement.
Syntax:
Syntax:python
import random

unique_number = random.sample(range(1, 51), 1)[0]


print("Unique random number:", unique_number)
Syntax:
6. **Write a program to generate three checkboxes and a submit button**:
Explanation: In Tkinter, checkboxes are created using the `Checkbutton()` constructor.
Below is a Python program to generate three checkboxes and a submit button.
Syntax:
Syntax:python
import tkinter as tk

def submit():
print("Checkbox 1:", var1.get())
print("Checkbox 2:", var2.get())
print("Checkbox 3:", var3.get())

root = tk.Tk()

var1 = tk.IntVar()
var2 = tk.IntVar()
var3 = tk.IntVar()

cb1 = tk.Checkbutton(root, text="Checkbox 1", variable=var1)


cb2 = tk.Checkbutton(root, text="Checkbox 2", variable=var2)
cb3 = tk.Checkbutton(root, text="Checkbox 3", variable=var3)

submit_button = tk.Button(root, text="Submit", command=submit)

cb1.pack()
cb2.pack()
cb3.pack()
submit_button.pack()

root.mainloop()
Syntax:

7. **Write a program to add an image to the label**:


Explanation: In Tkinter, images can be added to labels using the `PhotoImage()`
constructor. Below is a Python program to add an image to a label.
Syntax:
Syntax:python
import tkinter as tk

root = tk.Tk()
# Load image
img = tk.PhotoImage(file="image.png")

# Create label with image


label = tk.Label(root, image=img)
label.pack()

root.mainloop()
Syntax:

8. **What is a list box? Describe various options/properties of the list box in Python**:
Explanation: A list box is a graphical control element that allows users to select one or
more items from a list of options. In Tkinter, the `Listbox()` constructor is used to create a
list box widget. Various options and properties

of the list box include:


- `height`: The number of visible lines in the list box.
- `selectmode`: The selection mode (`SINGLE`, `BROWSE`, `MULTIPLE`,
`EXTENDED`).
- `activestyle`: The style to use for the active element (`DOTBOX`, `UNDERLINE`,
`NONE`).
- `exportselection`: Whether the selection is exported to the clipboard.
- `font`: The font used for the list box text.
- `bg` (background) and `fg` (foreground) colors.
- `width`: The width of the list box in characters.

9. **What is a message box? Explain with an example**:


Explanation: A message box is a dialog box that displays a message to the user and
typically provides options for the user to respond (e.g., OK, Cancel). In Tkinter, the
`messagebox` module provides functions to create message boxes.
Example:
Syntax:python
import tkinter as tk
from tkinter import messagebox

root = tk.Tk()

def show_message_box():
messagebox.showinfo("Info", "This is an informational message")
button = tk.Button(root, text="Show Message Box", command=show_message_box)
button.pack()

root.mainloop()
Syntax:

10. **Describe various options of the button widget**:


- `text`: The text displayed on the button.
- `command`: The function or method to be called when the button is clicked.
- `bg` (background): The background color of the button.
- `fg` (foreground): The text color of the button.
- `width` and `height`: The width and height of the button.
- `state`: The state of the button (`NORMAL`, `ACTIVE`, `DISABLED`).
- `font`: The font used for the button text.
- `padx` and `pady`: The padding (horizontal and vertical) inside the button.
- `relief`: The border style of the button (`FLAT`, `RAISED`, `SUNKEN`, etc.).
- `command`: The function or method to be called when the button is clicked.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy