Python Full
Python Full
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'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.
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.
"""
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?
For example:
number = 42
string_number = str(number)
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).
Example:
# module1.py
global_var = 10
# module2.py
from module1 import global_var
print(global_var) # Output: 10
# Pickling
with open('data.pkl', 'wb') as f:
pickle.dump(data, f)
# Unpickling
with open('data.pkl', 'rb') as f:
data = pickle.load(f)
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
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.
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.
10 Marks Questions
UNIT-I
Unit 2
UNIT-II (2 Marks Questions)
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]'
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:
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}!")
def my_function():
y = 20 # Local variable
print(x) # Access global variable
print(y) # Access local variable
my_function()
Syntax:
gen = my_generator()
print(next(gen)) # Output: 1
print(next(gen)) # Output: 2
Syntax:
Example:
```python
x = 5 + 'hello'
```
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:
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:
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.
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
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:
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
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:
def square(x):
return x ** 2
Syntax:
Syntax:python
# Importing module
import mymodule
mymodule.greet("John")
print(mymodule.square(5)) # Output: 25
Syntax:
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
fib_gen = fibonacci()
for _ in range(5):
print(next(fib_gen)) # Output: 0, 1, 1, 2, 3
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)
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)
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()
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!")
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.
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
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:
root = tk.Tk()
entry = tk.Entry(root)
entry.pack()
root.mainloop()
Syntax:
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:
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 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:
root = tk.Tk()
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:
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.pack()
cb2.pack()
cb3.pack()
submit_button.pack()
root.mainloop()
Syntax:
root = tk.Tk()
# Load image
img = tk.PhotoImage(file="image.png")
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
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: