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

Python Question Bank

The document describes the key components of Python including the interpreter, standard library, syntax, data types, variables, control structures, functions, modules, object-oriented programming, dynamic typing, garbage collection and community/ecosystem. It explains that Python is an interpreted, dynamically typed and garbage collected language that uses indentation for code blocks. The standard data types include numbers, strings, lists, tuples, dictionaries, sets and more. Variables store and manipulate data, and Python supports features like functions, modules, packages and object-oriented programming.

Uploaded by

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

Python Question Bank

The document describes the key components of Python including the interpreter, standard library, syntax, data types, variables, control structures, functions, modules, object-oriented programming, dynamic typing, garbage collection and community/ecosystem. It explains that Python is an interpreted, dynamically typed and garbage collected language that uses indentation for code blocks. The standard data types include numbers, strings, lists, tuples, dictionaries, sets and more. Variables store and manipulate data, and Python supports features like functions, modules, packages and object-oriented programming.

Uploaded by

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

Question Bank

Unit I

1. Describe about the components of Python.


Python is a versatile and high-level programming language known for its simplicity and
readability. It consists of several key components that work together to enable developers to
write and execute code efficiently. These components include:

1. Interpreter: Python is an interpreted language, which means that it doesn't require a separate
compilation step. Instead, Python code is executed directly by the Python interpreter. This
interpreter reads and executes the code line by line, making it easy to develop and test code
interactively.

2. Standard Library: Python comes with a comprehensive standard library that provides a wide
range of modules and packages for various tasks. This library includes modules for file I/O,
regular expressions, data manipulation, networking, and much more. It simplifies common
programming tasks and reduces the need to reinvent the wheel.

3. Syntax: Python's syntax is designed to be clear and readable. It uses indentation (whitespace)
to define code blocks, making it easy to understand the structure of the code. This feature is
often referred to as the "Pythonic" way of writing code.

4. Data Types: Python supports various data types, including integers, floating-point numbers,
strings, lists, tuples, dictionaries, sets, and more. These data types allow developers to work with
a wide range of data and perform operations on them.

5. Variables: In Python, variables are used to store and manipulate data. Variables are
dynamically typed, which means that you don't need to specify the data type when declaring a
variable. Python determines the data type at runtime.

6. Control Structures: Python provides control structures like if statements, loops (for and
while), and exceptions. These control structures allow developers to control the flow of their
programs and handle errors gracefully.

7. Functions: Functions in Python allow you to encapsulate a block of code and reuse it
throughout your program. Python supports both built-in functions from the standard library and
user-defined functions, which you can create as needed.

8. Modules and Packages: Python allows you to organize your code into modules and packages,
making it easy to structure your projects and reuse code across different parts of your
application. Modules are individual Python files, while packages are directories containing
multiple modules.

9. Object-Oriented Programming (OOP): Python is an object-oriented programming language,


which means it supports the creation and manipulation of objects and classes. This paradigm
allows for code organization and encapsulation of data and behavior.

10. Dynamic Typing: Python is dynamically typed, which means that the data type of a variable
Provided By AK
is determined at runtime. This flexibility allows for more concise and adaptable code.

11. Garbage Collection: Python has an automatic memory management system that includes
garbage collection. This means that Python automatically reclaims memory that is no longer in
use, reducing the risk of memory leaks.

12. Community and Ecosystem: Python has a vast and active community of developers and a
rich ecosystem of third-party libraries and frameworks. This ecosystem includes popular
libraries like NumPy, pandas, Django, Flask, and more, which extend Python's capabilities for
specific domains and applications.

These components work together to make Python a versatile and powerful programming
language suitable for a wide range of applications, including web development, data analysis,
scientific computing, automation, and more. Python's simplicity and readability make it an
excellent choice for both beginners and experienced programmers.
2. Define assignment statement.

3. List the standard data types of python.


Python has five standard data types: • Numbers • String • List • Tuple • Dictionary

There are different types of data types in Python. Some built-in Python data types are:

 Numeric data types: int, float, complex


 String data types: str
 Sequence types: list, tuple, range
 Binary types: bytes, bytearray, memoryview
 Mapping data type: dict
 Boolean type: bool
 Set data types: set, frozenset
Provided By AK
4. Define variable in python and list the rules of python variables?
In Python, a variable is a symbolic name that represents a value stored in the computer's
memory. Variables are used to store and manipulate data in your programs. When you create a
variable, you are essentially assigning a name to a value, making it easier to reference and
modify that value throughout your code.
Here's how you can define a variable in Python:
variable_name = value
Here, `variable_name` is the name of the variable, and `value` is the data that you want to store
in the variable. The `=` symbol is the assignment operator, which assigns the value to the
variable.

Here are some important rules and guidelines for naming variables in Python:
1. Variable Name Rules:
- Variable names must start with a letter (a-z, A-Z) or an underscore (_).
- After the initial letter or underscore, variable names can contain letters, digits (0-9), and
underscores.
- Variable names are case-sensitive, which means that `myVariable` and `myvariable` are
considered different variables.
2. Convention for Variable Names:
- Variable names should be descriptive and indicate the purpose of the variable.
- Use lowercase letters for variable names and separate words with underscores (snake_case).
For example, `my_variable_name`.
- In some cases, uppercase letters and underscores (UPPER_CASE) are used for constants.
3. Reserved Keywords: Avoid using Python's reserved keywords as variable names. Reserved
keywords are words that have special meanings in the Python language, such as `if`, `for`,
`while`, `def`, and many others.
4. Avoid Starting with a Number: Variable names cannot start with a number. For example,
`2nd_variable` is not a valid variable name.
5. Meaningful Names: Choose meaningful and relevant variable names that make your code
more understandable. For example, instead of `x` or `temp`, use names like `counter`,
`user_input`, or `total_sum` depending on the context.

5. How can the ternary operators be used in python?


In Python, you can use the ternary operator (also known as the conditional expression) to create
concise conditional statements. The ternary operator is a shorthand way of expressing an `if-
else` statement in a single line. Its syntax is as follows:
result_if_true if condition else result_if_false
Here's how you can use the ternary operator in Python:
1. Basic Example:
x = 10
y = 20
max_value = x if x > y else y
print(max_value) # Output: 20
In this example, `max_value` is assigned the value of `x` if `x` is greater than `y`, and `y` if `x`
is not greater than `y`.
2. Assigning to a Variable:
You can use the ternary operator to assign a value to a variable based on a condition, as shown
in the previous example.
3. Returning a Value:
Provided By AK
You can use the ternary operator to return a value from a function based on a condition. For
example:
def is_even(num):
return True if num % 2 == 0 else False
4. Nested Ternary Operators:
You can nest ternary operators to handle more complex conditions. However, you should use
caution to ensure that your code remains readable.
result = "Even" if num % 2 == 0 else "Negative" if num < 0 else "Positive"
5. Using Ternary Operator with Functions:
You can use the ternary operator to call different functions or methods based on a condition.
```python
def process_data(data):
return transform_data(data) if is_valid(data) else log_error(data)
```
6. Define the two modes in Python.
Python has 2 modes called script mode and interactive mode in Python.
Script Mode:
Script mode is the typical way of writing Python programs as separate script files with a `.py`
extension. These scripts are saved to disk, and you run them using the Python interpreter from
the command line or an integrated development environment (IDE).
Use script mode for creating complete Python programs, modules, and scripts that you save and
run repeatedly. It's ideal for larger, more structured projects.
Example:
1. Create a Python script called `hello.py` with the following content:
# hello.py
print("Hello, world!")
2. Open a terminal or command prompt and navigate to the directory containing `hello.py`.
3. Run the script using the Python interpreter:
python hello.py
This will execute the `hello.py` script and print "Hello, world!" to the console.

Interactive Mode:
Interactive mode allows you to interact with the Python interpreter directly. You enter Python
statements or expressions one at a time, and the interpreter immediately evaluates and responds
to each input.
Use interactive mode for quick experimentation, testing code snippets, exploring Python
features, and learning. It's a dynamic environment for trying out Python expressions and
commands without the need to save a script.
Example:
1. Open a terminal or command prompt and start the Python interactive interpreter by simply
typing `python` and pressing Enter.
2. You can now enter Python statements and get immediate feedback. For instance, you can
perform basic arithmetic:
>>> 2 + 3
5
3. Define variables and manipulate them:
>>> x = 5
Provided By AK
>>> y = 3
>>> x * y
15
4. You can also import modules and use functions interactively:
>>> import math
>>> math.sqrt(16)
4.0
7. Show how Comment is used in python
Comments in Python are used to provide explanatory notes within the code. They are
ignored by the Python interpreter and serve as helpful information for developers and
readers of the code. Comments are a good practice to make your code more readable and to
document your code's functionality. Here's how comments are used in Python:

1. Single-Line Comments:
Single-line comments are used to annotate a single line of code. They start with the `#`
symbol and continue until the end of the line.
# This is a single-line comment
x = 10 # Assigning a value to a variable

2. Multi-Line Comments:
Python does not have a specific syntax for multi-line comments like some other
programming languages. However, you can use multi-line strings (triple-quoted strings) as a
workaround to create multi-line comments. Although these strings are not true comments,
they are often used for documentation purposes.
"""
This is a multi-line comment.
It can span over multiple lines.
Use it to provide detailed explanations.
"""
x = 10
It's important to note that multi-line strings are not ignored by the Python interpreter but
are just assigned to a variable, which is typically unused.

3. Comments for Function/Class Documentation:


Comments can be used to provide documentation for functions and classes. This is often
done within triple-quoted strings, known as docstrings, immediately following the function
or class definition. Docstrings are used by tools like `pydoc` and can be accessed using the
`help()` function.
def add(a, b):
"""
This function takes two arguments and returns their sum.
Args:
a (int): The first number.
b (int): The second number.
Returns:
int: The sum of a and b.
Provided By AK
"""
return a + b
In this example, the docstring provides a clear explanation of what the `add` function does,
the arguments it accepts, and the value it returns.

8.State some programming language features of Python.


1. Free and Open Source
Python language is freely available at the official website and you can download it from the
given download link below click on the Download Python keyword. Download Python Since
it is open-source, this means that source code is also available to the public. So you can
download it, use it as well as share it.
2. Easy to code
Python is a high-level programming language. Python is very easy to learn the language as
compared to other languages like C, C#, Javascript, Java, etc. It is very easy to code in the
Python language and anybody can learn Python basics in a few hours or days. It is also a
developer-friendly language.
3. Easy to Read
As you will see, learning Python is quite simple. As was already established, Python’s syntax
is really straightforward. The code block is defined by the indentations rather than by
semicolons or brackets.
4. Object-Oriented Language
One of the key features of Python is Object-Oriented programming. Python supports object-
oriented language and concepts of classes, object encapsulation, etc.
5. GUI Programming Support
Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython,
or Tk in Python. PyQt5 is the most popular option for creating graphical apps with Python.
6. High-Level Language
Python is a high-level language. When we write programs in Python, we do not need to
remember the system architecture, nor do we need to manage the memory.
7. Large Community Support
Python has gained popularity over the years. Our questions are constantly answered by the
enormous StackOverflow community. These websites have already provided answers to many
questions about Python, so Python users can consult them as needed.
8. Easy to Debug
Excellent information for mistake tracing. You will be able to quickly identify and correct the
majority of your program’s issues once you understand how to interpret Python’s error traces.
Simply by glancing at the code, you can determine what it is designed to perform.
9. Python is a Portable language
Python language is also a portable language. For example, if we have Python code for
Windows and if we want to run this code on other platforms such as Linux, Unix, and Mac
then we do not need to change it, we can run this code on any platform.
10. Python is an Integrated language
Python is also an Integrated language because we can easily integrate Python with other
languages like C, C++, etc.

Provided By AK
11. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by line at a time. like
other languages C, C++, Java, etc. there is no need to compile Python code this makes it easier
to debug our code. The source code of Python is converted into an immediate form
called bytecode.
12. Large Standard Library
Python has a large standard library that provides a rich set of modules and functions so you do
not have to write your own code for every single thing. There are many libraries present in
Python such as regular expressions, unit-testing, web browsers, etc.
13. Dynamically Typed Language
Python is a dynamically-typed language. That means the type (for example- int, double, long,
etc.) for a variable is decided at run time not in advance because of this feature we don’t need
to specify the type of variable.
14. Frontend and backend development
With a new project py script, you can run and write Python codes in HTML with the help of
some simple tags <py-script>, <py-env>, etc. This will help you do frontend development
work in Python like javascript. Backend is the strong forte of Python it’s extensively used for
this work cause of its frameworks like Django and Flask.
15. Allocating Memory Dynamically
In Python, the variable data type does not need to be specified. The memory is automatically
allocated to a variable at runtime when it is given a value. Developers do not need to write int
y = 18 if the integer value 15 is set to y. You may just type y=18.

9. List the data types in python.


https://www.digitalocean.com/community/tutorials/python-data-types
Python supports several built-in data types. Here's a list of some of the most common data
types in Python:
1. Integer (int): Represents whole numbers, e.g., 1, 42, -10.
2. Float (float): Represents floating-point numbers, e.g., 3.14, -0.001.
3. String (str): Represents sequences of characters, e.g., "Hello, World!", 'Python'.
4. Boolean (bool): Represents a binary value, either True or False.
5. List: An ordered, mutable collection of elements, e.g., [1, 2, 3, "apple"].
6. Tuple: An ordered, immutable collection of elements, e.g., (1, 2, 3, "apple").
7. Dictionary (dict): A collection of key-value pairs, e.g., {"name": "John", "age": 30}.
8. Set: An unordered collection of unique elements, e.g., {1, 2, 3}.
9. NoneType (None): Represents the absence of a value, typically used to indicate a null or
undefined value.
10. Complex (complex): Represents complex numbers, e.g., 3 + 4j.
11. Bytes: Represents a sequence of bytes, often used for binary data.
12. Bytearray: A mutable sequence of bytes.
13. Range: Represents a sequence of numbers, often used in for loops, e.g., range(5)
produces 0, 1, 2, 3, 4.
14. Boolean (bool): Represents a binary value, either True or False.
15. Enum: A special data type for creating enumerations.
16. Decimal: Represents floating-point numbers with fixed precision.
17. Date and Time Types: Python also has several date and time-related data types like
`date`, `time`, `datetime`, and `timedelta` available in the `datetime` module.
Provided By AK
18. Custom Objects: You can define your own custom data types using classes.
These are the basic data types in Python. Python is a dynamically-typed language, so you
don't need to explicitly declare the data type of a variable; the interpreter infers it based on
the value assigned to the variable.

10. What is type conversion in Python?


Type conversion, also known as type casting, is the process of changing the data type of a
value from one type to another in Python. Python provides several built-in functions and
methods to perform type conversions. Type conversions are necessary when you want to use
a value in a context that requires a different data type than the one it currently has. Here are
some common examples of type conversion in Python:
1. Implicit Type Conversion (Coercion): This type of conversion is performed by Python
automatically when an operation involves two different data types, and one of them needs to
be converted to match the other. For example, when you add an integer and a floating-point
number, Python converts the integer to a float to perform the addition.
a = 5 # integer
b = 3.14 # float
result = a + b # Implicit type conversion: a is converted to float
2. Explicit Type Conversion (Type Casting): In explicit type conversion, you manually
specify the type to which you want to convert a value. Python provides several functions for
this purpose, such as `int()`, `float()`, `str()`, `list()`, and so on.
num_str = "42"
num = int(num_str) # Explicitly convert a string to an integer
3. Conversion between String and Other Types:
- `str()` function converts other data types to strings.
- `int()`, `float()`, and other appropriate functions can convert strings to numeric types.
num = 42
num_str = str(num) # Convert an integer to a string
4. List and Tuple Conversions:
- You can convert a list to a tuple using `tuple()`, and vice versa using `list()`.
my_list = [1, 2, 3]
my_tuple = tuple(my_list) # Convert a list to a tuple
5. Boolean Conversion: Many values can be converted to a Boolean using the `bool()`
function. In general, empty sequences, numbers not equal to 0, and non-empty strings
evaluate to `True`, while empty strings, zero, and `None` evaluate to `False`.
value = "Hello"
is_true = bool(value) # Converts "Hello" to True
Type conversion is an essential part of working with different data types and performing
various operations in Python. It allows you to manipulate data in a way that best suits your
program's needs. However, you should be cautious when converting between types, as you
may lose information or encounter unexpected behavior if not done correctly.

Provided By AK
11. What are Python strings?
In Python, a string is a sequence of characters enclosed in single, double, or triple quotes.
Strings are a fundamental data type used to represent text or characters in Python. Here are
some key characteristics and operations related to Python strings:

1. String Creation: You can create strings using single quotes (`'`), double quotes (`"`), or
triple quotes (`'''` or `"""`) to enclose the text.
single_quoted = 'Hello, world!'
double_quoted = "Hello, world!"
triple_quoted = '''Hello, world!'''
2. String Concatenation: You can concatenate (combine) strings using the `+` operator.
greeting = "Hello"
name = "Alice"
full_greeting = greeting + ", " + name # Concatenation
3. String Length: You can find the length (number of characters) of a string using the `len()`
function.
text = "Python is awesome"
length = len(text) # Length of the string
4. Accessing Characters: You can access individual characters in a string using indexing.
Python uses 0-based indexing, so the first character is at index 0.
text = "Python"
first_char = text[0] # Access the first character (P)
5. Slicing Strings: You can extract a substring from a string using slicing.
Provided By AK
text = "Python is great"
sub_string = text[7:10] # Slices from index 7 to 9: "is "
6. String Methods: Python provides a variety of string methods to perform operations on
strings, such as converting to uppercase or lowercase, replacing text, finding substrings, and
more.
text = "Python Programming"
upper_text = text.upper() # Convert to uppercase
replaced_text = text.replace("Python", "Java") # Replace text
7. String Formatting: Python supports multiple ways to format strings, including using the
`%` operator for formatting, the `str.format()` method, and f-strings (formatted string
literals).
name = "Alice"
age = 30
formatted_string = "My name is %s, and I am %d years old." % (name, age)
8. Escape Characters: Strings can contain special escape sequences to represent characters
that are hard to input directly, such as newline (`\n`) or tab (`\t`).
new_line = "This is a line.\nThis is a new line."
9. Raw Strings: You can create raw strings by prefixing the string with `r` or `R`. Raw
strings treat backslashes as literal characters, which can be useful when working with
regular expressions or file paths.
raw_string = r"C:\Users\John\Documents"
10. String Immutability: Strings in Python are immutable, meaning you cannot change the
characters in an existing string. When you perform string operations, you create new strings.
text = "Hello"
# The following line creates a new string, it doesn't modify the original.
text = text + " World"
Strings are a versatile and widely used data type in Python, and they play a crucial role in
various programming tasks, such as text processing, data manipulation, and user interface
development.

12. Explain Input and output statements in python.


Input and output (I/O) operations are essential for interacting with users and working with
external data in Python. Python provides several built-in functions and methods for
performing I/O operations, which allow you to read input from the user, display output to
the user, and work with files. Here's an overview of input and output statements in Python:

### Input Statements:


1. `input()` Function:
- The `input()` function is used to receive user input from the keyboard. It prompts the user
to enter a value and returns the entered text as a string.
- You can pass an optional string as an argument to provide a user-friendly prompt.
user_input = input("Enter your name: ")
print("Hello, " + user_input)
2. Converting Input to Other Types:
- By default, `input()` returns a string. To work with the input as a different data type, you
need to explicitly convert it using functions like `int()`, `float()`, or `eval()`.
age = int(input("Enter your age: ")) # Convert input to an integer

### Output Statements:


1. `print()` Function:
Provided By AK
- The `print()` function is used to display output on the console. You can pass one or more
values as arguments to `print()`, and it will output them to the console.
- By default, `print()` separates multiple arguments with spaces and adds a newline
character at the end. You can customize the separator and the ending character using the
`sep` and `end` parameters.
print("Hello, World!")
print("The answer is", 42)
2. Formatted Output:
- You can format the output using f-strings, the `str.format()` method, or the `%` operator.
name = "Alice"
age = 30
print(f"My name is {name}, and I am {age} years old.")
3. Special Characters:
- You can use special escape sequences in strings to represent characters that are hard to
input directly. For example, `\n` for a newline and `\t` for a tab.
print("This is the first line.\nThis is the second line.")

### File I/O:


1. `open()` Function:
- Python allows you to work with files using the `open()` function. It's used to open a file
for reading, writing, or appending.
# Open a file for reading
file = open("example.txt", "r")
2. Reading from Files:
- You can read the contents of a file using methods like `read()`, `readline()`, or by
iterating through the file object in a `for` loop.
with open("example.txt", "r") as file:
content = file.read()
3. Writing to Files:
- To write data to a file, you can use methods like `write()` and `writelines()`.
with open("output.txt", "w") as file:
file.write("This is a line of text.")
4. Closing Files:
- It's good practice to close files after you're done with them. You can use the `close()`
method or work with files using a `with` statement, which automatically closes the file when
the block is exited.
with open("example.txt", "r") as file:
content = file.read()
# File is automatically closed here.
Input and output statements are fundamental for creating interactive programs, processing
external data, and generating useful output for the user or external systems. They play a
crucial role in various Python applications, from simple scripts to complex software
projects.

13. What are the different types of operators used to evaluate Boolean
expression?
In Python, operators are used to perform various operations, and they can also be
used to evaluate Boolean expressions. Boolean expressions are expressions that
result in a Boolean value, which is either `True` or `False`. Here are the different
types of operators used to evaluate Boolean expressions:

Provided By AK
1. Comparison Operators:
- Comparison operators are used to compare two values and determine the
relationship between them. They return a Boolean value.

- `==`: Equal to (e.g., `a == b` returns `True` if `a` is equal to `b`).


- `!=`: Not equal to (e.g., `a != b` returns `True` if `a` is not equal to `b`).
- `<`: Less than (e.g., `a < b` returns `True` if `a` is less than `b`).
- `>`: Greater than (e.g., `a > b` returns `True` if `a` is greater than `b`).
- `<=`: Less than or equal to (e.g., `a <= b` returns `True` if `a` is less than or
equal to `b`).
- `>=`: Greater than or equal to (e.g., `a >= b` returns `True` if `a` is greater
than or equal to `b`).

2. Logical Operators:
- Logical operators are used to combine or modify Boolean values. They are
often used to create complex Boolean expressions.
- `and`: Logical AND (e.g., `a and b` returns `True` if both `a` and `b` are
`True`).
- `or`: Logical OR (e.g., `a or b` returns `True` if either `a` or `b` is `True`).
- `not`: Logical NOT (e.g., `not a` returns the opposite of the Boolean value of
`a`).

3. Identity Operators:
- Identity operators are used to compare the memory locations of two objects.
- `is`: True if the operands reference the same object (e.g., `a is b` returns
`True` if `a` and `b` refer to the same object).
- `is not`: True if the operands reference different objects (e.g., `a is not b`
returns `True` if `a` and `b` refer to different objects).

4. Membership Operators:
- Membership operators are used to check whether a value is a member of a
sequence, such as a list, tuple, or string.
- `in`: True if a value is found in the sequence (e.g., `x in sequence` returns
`True` if `x` is in the `sequence`).
- `not in`: True if a value is not found in the sequence (e.g., `x not in sequence`
returns `True` if `x` is not in the `sequence`).

5. Bitwise Operators (used with integers):


- Bitwise operators perform operations on individual bits of integer values and
can be used to evaluate Boolean expressions.
- `&`: Bitwise AND (e.g., `a & b` returns an integer with the result of bitwise
AND operation).
- `|`: Bitwise OR (e.g., `a | b` returns an integer with the result of bitwise OR
operation).
- `^`: Bitwise XOR (e.g., `a ^ b` returns an integer with the result of bitwise
XOR operation).
- `~`: Bitwise NOT (e.g., `~a` returns the bitwise complement of `a`).
- `<<`: Left shift (e.g., `a << b` shifts the bits of `a` left by `b` positions).
- `>>`: Right shift (e.g., `a >> b` shifts the bits of `a` right by `b` positions).

These operators allow you to create complex Boolean expressions and perform a

Provided By AK
wide range of operations on Boolean values, making them a fundamental part of
Python's expressive power for controlling program flow and logic.

14. Briefly describe about any 10 built-in functions in Python.


Python provides a rich set of built-in functions that serve various purposes. Here's
a brief description of 10 commonly used built-in functions in Python:

1. `print()`: The `print()` function is used to display output on the console. You
can pass one or more values as arguments, and it will print them to the console.
print("Hello, World!")

2. `len()`: The `len()` function is used to determine the length (number of


elements) of a sequence, such as a string, list, or tuple.
text = "Python is great"
length = len(text)

3. `input()`: The `input()` function is used to receive user input from the
keyboard. It prompts the user to enter a value and returns it as a string.
user_input = input("Enter your name: ")

4. `range()`: The `range()` function generates a sequence of numbers. It is often


used in `for` loops for iterating over a range of values.
for i in range(5):
print(i) # Prints numbers 0 to 4

5. `type()`: The `type()` function is used to determine the data type of an object. It
can be helpful for debugging or ensuring that you're working with the correct data
type.
value = 42
data_type = type(value) # Returns <class 'int'>

6. `str()`: The `str()` function is used to convert a value to a string. It's commonly
used for concatenating strings with non-string values.
num = 42
num_str = str(num) # Converts an integer to a string

7. `int()`: The `int()` function is used to convert a value to an integer. It's often
used for converting strings to integers.
num_str = "42"
num = int(num_str) # Converts a string to an integer

8. `float()`: The `float()` function is used to convert a value to a floating-point


number. It's also used for converting strings to floats.
num_str = "3.14"
num = float(num_str) # Converts a string to a float

9. `max()` and `min()`: The `max()` and `min()` functions are used to find the
maximum and minimum values in a sequence of numbers, respectively.
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
max_value = max(numbers) # Returns 9
min_value = min(numbers) # Returns 1

Provided By AK
10. `sum()`: The `sum()` function is used to calculate the sum of all elements in
an iterable, such as a list or tuple.
numbers = [1, 2, 3, 4, 5]
total = sum(numbers) # Returns 15

These built-in functions are just a subset of the many functions Python provides.
They simplify common programming tasks and make Python a powerful and
expressive language for a wide range of applications.
15. Write a python program to print “SKPMCA” 5 times.
You can use a simple `for` loop to print the string "SKPMCA" 5 times in a Python program.
Here's an example:

text = "SKPMCA"

for _ in range(5):
print(text)

In this program, we initialize the `text` variable with the string "SKPMCA". Then, we use a
`for` loop to iterate 5 times, and in each iteration, we print the contents of the `text` variable,
which is "SKPMCA". This will result in "SKPMCA" being printed 5 times to the console.

16. List all the string methods, with description and example.
Strings in Python have a variety of methods that allow you to manipulate and work with
them. Here's a list of some commonly used string methods along with descriptions and
examples:

1. `capitalize()`:
- Converts the first character of the string to uppercase and the rest to lowercase.
text = "hello, world"
capitalized_text = text.capitalize() # "Hello, world"

2. `upper()`:
- Converts all characters in the string to uppercase.
text = "Hello, World"
uppercase_text = text.upper() # "HELLO, WORLD"

3. `lower()`:
- Converts all characters in the string to lowercase.
text = "Hello, World"
lowercase_text = text.lower() # "hello, world"

4. `title()`:
- Converts the first character of each word in the string to uppercase, while making all
other characters lowercase.
text = "hello, world"
title_text = text.title() # "Hello, World"
Provided By AK
5. `strip()`:
- Removes leading and trailing whitespace (including spaces, tabs, and newlines) from the
string.
text = " Python is great "
stripped_text = text.strip() # "Python is great"

6. `split()`:
- Splits the string into a list of substrings based on a specified delimiter (default is
whitespace).
text = "apple, banana, cherry"
fruits = text.split(", ") # ['apple', 'banana', 'cherry']

7. `join()`:
- Combines a list of strings into a single string, using the current string as a delimiter.
words = ["Hello", "World"]
sentence = " ".join(words) # "Hello World"

8. `replace()`:
- Replaces all occurrences of a substring with another substring in the string.
text = "I love programming in Python"
new_text = text.replace("Python", "Java") # "I love programming in Java"

9. `startswith()`:
- Checks if the string starts with a specified prefix and returns a Boolean value.
text = "Hello, World"
starts_with_hello = text.startswith("Hello") # True

10. `endswith()`:
- Checks if the string ends with a specified suffix and returns a Boolean value.
text = "Hello, World"
ends_with_world = text.endswith("World") # True

11. `find()`:
- Searches for a substring in the string and returns the lowest index of its first occurrence.
If not found, it returns -1.
text = "Python is easy and Python is fun"
index = text.find("Python") # 0 (index of the first "Python")

12. `count()`:
- Counts the number of non-overlapping occurrences of a substring in the string.
text = "Python is easy and Python is fun"
occurrences = text.count("Python") # 2

These are just a few of the many string methods available in Python. String methods are
Provided By AK
helpful for a wide range of text manipulation tasks in Python programming.

17. Explain the use of logical operators and membership


operators in Python
In Python, logical operators and membership operators are used to perform
various operations on Boolean values and sequences (like lists, tuples, or
strings). Let's explore their use:
### Logical Operators:Logical operators are used to perform operations on
Boolean values (True or False).
1. `and`: The logical AND operator returns True if both operands are True.
It returns False if at least one of the operands is False.
x = True
y = False
result = x and y # result is False

2. `or`: The logical OR operator returns True if at least one of the operands
is True. It returns False if both operands are False.
x = True
y = False
result = x or y # result is True

3. `not`: The logical NOT operator returns the opposite of the Boolean
value of its operand. If the operand is True, it returns False, and vice versa.
x = True
result = not x # result is False

Logical operators are often used to create complex conditions and control
the flow of a program. They are essential for decision-making and
branching in control structures like `if` statements.

### Membership Operators:


Membership operators are used to check if a specific value is a member of a
sequence, such as a list, tuple, or string.

1. `in`: The `in` operator returns True if the value is found in the sequence;
otherwise, it returns False.
my_list = [1, 2, 3, 4, 5]
result = 3 in my_list # result is True

2. `not in`: The `not in` operator returns True if the value is not found in the
sequence; otherwise, it returns False.
my_list = [1, 2, 3, 4, 5]

Provided By AK
result = 6 not in my_list # result is True

Membership operators are commonly used for searching for specific values
in collections and making decisions based on the presence or absence of
those values.
Both logical operators and membership operators are important tools for
writing conditional statements and creating more complex logic in Python
programs. They help you control the flow of your code and make decisions
based on conditions or the presence of certain values in data structures.

18. Explain expressions in python with order of evaluation with


example.
In Python, an expression is a combination of values and operators that,
when evaluated, results in a value. Expressions can be as simple as a single
value or as complex as a combination of multiple operators and operands.
The order of evaluation is the sequence in which the operators and operands
are processed to calculate the final result. Python follows a specific order of
evaluation, known as the operator precedence.

Here's an explanation of operator precedence in Python, along with


examples to illustrate the order of evaluation:

1. Parentheses `()`:
- Expressions enclosed in parentheses are evaluated first. This allows you
to control the order of evaluation explicitly.
result = (3 + 2) * 4 # The addition inside the parentheses is evaluated first

2. Exponentiation ``:
- Exponentiation operations are evaluated next, from right to left.
result = 2 3 # 2 raised to the power of 3

3. Multiplication `*`, Division `/`, Floor Division `//`, Modulus `%`:


- Multiplication, division, floor division, and modulus operations are
evaluated from left to right.
result = 10 / 2 * 3 # Division is evaluated first, then multiplication

4. Addition `+`, Subtraction `-`:


- Addition and subtraction operations are evaluated from left to right.
result = 5 - 3 + 1 # Left-to-right evaluation

5. Bitwise Shift `<<`, `>>`:

Provided By AK
- Bitwise shift operations are evaluated from left to right.
result = 4 << 1 # Left-shift 4 by 1 position

6. Bitwise AND `&`:


- Bitwise AND operations are evaluated from left to right.
result = 5 & 3 # Bitwise AND of 5 and 3

7. Bitwise XOR `^`:


- Bitwise XOR operations are evaluated from left to right.
result = 5 ^ 3 # Bitwise XOR of 5 and 3

8. Bitwise OR `|`:
- Bitwise OR operations are evaluated from left to right.
result = 5 | 3 # Bitwise OR of 5 and 3

9. Comparison Operators `==`, `!=`, `<`, `<=`, `>`, `>=`, `is`, `is not`, `in`,
`not in`:
- Comparison operations are evaluated from left to right.
result = 5 < 10 and 3 != 2 # Comparison operators evaluated from left to
right

10. Logical NOT `not`:


- The logical NOT operator is evaluated before `and` and `or`.
result = not (5 < 10 and 3 != 2) # Logical NOT is evaluated first

11. Logical AND `and`:


- Logical AND is evaluated after comparison and logical NOT
operations.
result = (5 < 10) and (3 != 2) # Logical AND evaluated after
comparisons

12. Logical OR `or`:


- Logical OR is evaluated after logical AND, comparison, and logical
NOT operations.
result = (5 < 10) or (3 != 2) # Logical OR evaluated after other
operations

It's important to understand the order of evaluation in Python to ensure that


expressions are computed as expected. You can use parentheses to
explicitly specify the order of operations when needed to avoid any
ambiguity.

Provided By AK
19. List out the classes required to perform Date and Time
operations.
In Python, you can perform date and time operations using classes and
functions provided by the `datetime` module from the standard library. Here
are some of the key classes and objects related to date and time operations
in Python:

1. `datetime` Class:
- The `datetime` class is one of the central classes in the `datetime`
module, representing both date and time information. It has attributes for
year, month, day, hour, minute, second, and microsecond.
from datetime import datetime
current_datetime = datetime.now() # Get the current date and time
print(current_datetime)
2. `date` Class:
- The `date` class represents date information only (year, month, and day).
from datetime import date
today = date.today() # Get the current date
print(today)

3. `time` Class:
- The `time` class represents time information only (hour, minute, second,
and microsecond).
from datetime import time
current_time = time(14, 30, 0) # Create a specific time (2:30 PM)
print(current_time)

4. `timedelta` Class:
- The `timedelta` class is used for representing a duration or the difference
between two dates or times.
from datetime import timedelta
time_duration = timedelta(days=5, hours=3) # Represents a duration of 5
days and 3 hours

5. `timezone` Class:
- The `timezone` class represents a fixed offset from UTC (Coordinated
Universal Time).
from datetime import timezone, datetime, timedelta
utc = timezone.utc
current_time = datetime.now(utc)

These classes and objects allow you to work with date and time data,
Provided By AK
perform various operations like arithmetic with dates and times, and format
them for display. The `datetime` module also provides functions for parsing
and formatting date and time strings, working with time zones, and more.

20. Explain Date Arithmetic with examples.


Date arithmetic involves performing mathematical operations on dates, such as addition,
subtraction, and finding the difference between dates. In Python, you can use the `datetime`
module to perform date arithmetic using the `datetime` and `timedelta` classes. Here are
some common examples of date arithmetic:

1. Adding Days to a Date:


You can add a certain number of days to a date using the `timedelta` class and the addition
operator (`+`).
from datetime import datetime, timedelta
current_date = datetime(2023, 11, 7)
days_to_add = timedelta(days=30)
future_date = current_date + days_to_add
print(future_date)
This example adds 30 days to the `current_date` and prints the resulting date.

2. Subtracting Days from a Date:


You can subtract a certain number of days from a date in a similar way.
from datetime import datetime, timedelta
current_date = datetime(2023, 11, 7)
days_to_subtract = timedelta(days=15)
past_date = current_date - days_to_subtract
print(past_date)
This example subtracts 15 days from the `current_date` and prints the resulting date.

3. Calculating the Difference Between Two Dates:


You can find the difference in days between two dates by subtracting one date from
another, resulting in a `timedelta` object.
from datetime import datetime
date1 = datetime(2023, 11, 7)
date2 = datetime(2023, 12, 15)
date_difference = date2 - date1
print(date_difference.days)
In this example, `date_difference` contains the difference between `date2` and `date1`, and
we print the number of days in the difference.

4. Adding Hours, Minutes, or Seconds:


You can also perform date arithmetic with hours, minutes, and seconds by creating
`timedelta` objects with those components and adding them to a `datetime` object.
from datetime import datetime, timedelta
current_time = datetime(2023, 11, 7, 10, 30) # 10:30 AM
time_to_add = timedelta(hours=3, minutes=15)
future_time = current_time + time_to_add
print(future_time)
Provided By AK
This example adds 3 hours and 15 minutes to `current_time` and prints the resulting time.

Date arithmetic is essential for various applications, such as calculating deadlines,


scheduling events, and working with time-based data. The `datetime` module provides a
powerful set of tools for performing these operations.

Unit II

1. How does break, continue and pass work?


In Python, `break`, `continue`, and `pass` are control flow statements used to control the
flow of execution in loops and conditional blocks. Here's how they work:

1. `break`:

- The `break` statement is used to exit a loop prematurely. When a `break` statement is
encountered within a loop (such as a `for` or `while` loop), the loop is immediately
terminated, and the program continues with the next statement after the loop.

for i in range(5):

if i == 3:

break

print(i)

In this example, the loop is terminated when `i` becomes equal to 3, and the program
continues with the next statement after the loop.

2. `continue`:

- The `continue` statement is used to skip the rest of the current iteration and continue with
the next iteration of a loop. When a `continue` statement is encountered within a loop, the
current iteration is stopped, and the loop proceeds with the next iteration.

for i in range(5):

if i == 2:

continue

print(i)

In this example, when `i` is equal to 2, the `continue` statement is executed, skipping the
`print(i)` statement for that iteration, and the loop continues with the next iteration.

3. `pass`:

- The `pass` statement is a no-operation statement. It is a placeholder that does nothing

Provided By AK
when executed. It is often used when a statement is syntactically required, but no action is
needed.

for i in range(5):

if i == 2:

pass

print(i)

In this example, when `i` is equal to 2, the `pass` statement is executed, but it doesn't affect the
loop or program's behavior. The loop continues as usual.

These control flow statements are essential for customizing the behavior of loops and
conditional blocks in your code. `break` is used to exit loops prematurely, `continue` is used
to skip the current iteration and proceed to the next one, and `pass` is used as a placeholder
when no specific action is required at a certain point in the code.

2. What are docstrings in Python?


Docstrings in Python are a form of documentation that allows you to provide a description of
modules, classes, functions, or methods within your Python code. Docstrings are typically
enclosed within triple quotes (either single or double) and are placed immediately following
the definition of a module, class, function, or method. They serve as a form of inline
documentation to help other programmers understand the purpose, usage, and functionality
of the code you've written.

Here are some key points about docstrings in Python:

1. Documentation Purpose: Docstrings are used to describe the purpose and usage of a
module, class, function, or method. They are meant to provide information to other
developers (or to yourself) who may work with the code in the future.

2. Syntax: A docstring is typically enclosed within triple quotes (either `'''` or `"""`) and
placed immediately below the definition line of a module, class, function, or method.

3. Convention: While there is no strict requirement for the format of docstrings, Python
community conventions, as outlined in PEP 257, recommend using triple-double-quotes
(`"""`) and following specific formatting styles (e.g., using reStructuredText or NumPy style
docstrings) for consistency and tool compatibility.

4. Accessing Docstrings: You can access the docstring of an object using the `.__doc__`
attribute. For example, `object.__doc__` provides the docstring for `object`.

5. Importance of Clarity: Writing clear and informative docstrings is essential for


maintainable and collaborative code. It helps other developers understand how to use your
code and its underlying logic.

Provided By AK
6. Docstring Examples:
- Module docstring:
"""
This is a sample module docstring.
It provides an overview of what this module does.
"""
- Function docstring:
def add(a, b):
"""
This function adds two numbers and returns the result.
:param a: The first number
:param b: The second number
:return: The sum of a and b
"""
return a + b
- Class docstring:
class MyClass:
"""
This is a sample class docstring.
It describes the purpose of the class and its attributes/methods.
"""
def __init__(self):
"""Initialize a new instance of MyClass."""
pass
Well-documented code with clear and informative docstrings is considered a good practice
in Python development, as it makes it easier for other developers to understand and use your
code, encourages better code maintenance, and facilitates the use of documentation tools like
Sphinx.

3. Explain if…else statement with example?


The `if...else` statement in Python is used for conditional execution. It allows you to execute
a block of code if a specified condition is `True`, and another block of code if the condition
is `False`. Here's the basic syntax of the `if...else` statement:
if condition:
# Code to execute if the condition is True
else:
# Code to execute if the condition is False
- The `condition` is an expression that is evaluated to a Boolean value (`True` or `False`).
- If the `condition` is `True`, the code block under the `if` statement is executed.
- If the `condition` is `False`, the code block under the `else` statement is executed.
Here's an example of the `if...else` statement in Python:
age = 20
if age >= 18:
print("You are an adult.")
Provided By AK
else:
print("You are not an adult.")
In this example, we check the value of the `age` variable. If `age` is greater than or equal to
18, the condition is `True`, and the code block under the `if` statement is executed, which
prints "You are an adult." If `age` is less than 18, the condition is `False`, and the code block
under the `else` statement is executed, which prints "You are not an adult."

The `if...else` statement is commonly used for making decisions in your code based on
certain conditions. It provides a way to handle both the "true" and "false" cases in a
straightforward manner. You can also use multiple `if...else` statements to create more
complex decision structures, including `if...elif...else` statements for multiple conditions.

4. What are the different flow control statements available in python? Explain
with suitable examples
Python provides several flow control statements that allow you to control the flow of your
code based on conditions, loops, and exceptions. Here are the main flow control
statements in Python, along with examples:
1. `if` statement:
- The `if` statement is used for conditional execution. It allows you to execute a block of
code if a specified condition is `True`.
x = 10
if x > 5:
print("x is greater than 5")
2. `else` statement:
- The `else` statement is used in conjunction with an `if` statement to specify code that
should be executed when the condition is `False`.
x=3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
3. `elif` statement:
- The `elif` statement is used to test multiple conditions in sequence after an `if` statement.
It is used when you have more than two possible outcomes.
x=7
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but not greater than 10")
else:
print("x is not greater than 5")
4. `for` loop:
- The `for` loop is used for iterating over a sequence (such as a list, tuple, or string) or
Provided By AK
other iterable objects.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
5. `while` loop:
- The `while` loop is used to repeatedly execute a block of code as long as a specified
condition is `True`.
count = 0
while count < 5:
print(count)
count += 1
6. `break` statement:
- The `break` statement is used to exit a loop prematurely, even if the loop condition is still
`True`.
for i in range(10):
if i == 5:
break
print(i)
7. `continue` statement:
- The `continue` statement is used to skip the rest of the current iteration in a loop and
move to the next iteration.
for i in range(5):
if i == 2:
continue
print(i)
8. `pass` statement:
- The `pass` statement is a no-operation statement used as a placeholder. It does nothing
when executed and is often used when a statement is syntactically required but no action
is needed.
for i in range(5):
if i == 2:
pass
print(i)
9. `try`, `except`, and `finally` statements:
- These statements are used for exception handling to catch and handle errors gracefully.
try:
result = 10 / 0
except ZeroDivisionError:
print("Division by zero is not allowed")
finally:
print("Execution completed")

Provided By AK
These flow control statements provide you with the tools to make decisions, perform
iterations, handle exceptions, and control the flow of your Python programs.

5. Define Module.
In Python, a module is a file that contains a collection of related functions, classes, and
variables that can be reused in different parts of your program. Modules are a way to
organize and modularize your code, making it more manageable, maintainable, and reusable.
They are essential for structuring large Python applications and promoting code reusability.
Key points about modules in Python:
1. Creating a Module: To create a module, you simply create a `.py` file containing Python
code. This file can include functions, classes, and variables. For example, you might create a
file called `my_module.py`.
2. Importing a Module: To use the contents of a module in another Python script, you need
to import it. This is typically done using the `import` statement.
import my_module
3. Accessing Module Contents: Once a module is imported, you can access its functions,
classes, and variables by using the module's name as a prefix.
result = my_module.my_function()
4. Module Namespacing: Modules introduce a form of namespacing in Python. This means
that if two different modules define a function with the same name, you can distinguish them
by their module names.
5. Standard Library Modules: Python also includes a vast standard library with a wide range
of modules for various purposes, such as `math`, `datetime`, `os`, and more. You can use
these modules in your code without needing to create them.
6. Module Documentation (Docstrings): It's good practice to include documentation
(docstrings) in your modules to describe the purpose and usage of functions, classes, and
variables within the module.
Here's an example of a simple module and how to use it:
```
# my_module.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
```

```
# main.py
import my_module
result1 = my_module.add(5, 3)
result2 = my_module.subtract(10, 4)
print(result1) # Output: 8
print(result2) # Output: 6
```

In this example, we've created a module named `my_module` with two functions, and then
we imported and used these functions in another script called `main.py`. Modules allow you
to structure and organize your code, making it more readable and reusable, and they play a
crucial role in Python software development.
Provided By AK
6.Define package in python with an example.
In Python, a package is a way to organize related modules into a single directory hierarchy.
Packages allow you to group multiple Python modules together in a way that helps manage
large codebases and avoid naming conflicts. Packages are also used to create a namespace to
organize your code.

A package is essentially a directory that contains a special file called `__init__.py`, which
can be empty or contain initialization code for the package. This `__init__.py` file is
executed when the package is imported and can define package-level variables, functions, or
perform other package-specific setup tasks.

Here's an example of how to create and use a Python package:


Suppose you have the following directory structure for a package named `my_package`:
my_package/
__init__.py
module1.py
module2.py
1. `my_package` is the package directory, and it contains the `__init__.py` file, which can be
empty or contain package initialization code.
2. `module1.py` and `module2.py` are Python modules that belong to the `my_package`
package.
Here's what `__init__.py` might look like:
# my_package/__init__.py
# This can be empty or contain package-level initialization code.
# You can define variables, functions, or import modules here.

To use modules from the `my_package` package in your Python code, you can import them
like this:
from my_package import module1
from my_package import module2

result1 = module1.my_function()
result2 = module2.another_function()

print(result1)
print(result2)

In this example, `module1` and `module2` are modules that are part of the `my_package`
package. You can access their functions and variables using dot notation.

Packages help you organize and structure your Python code into meaningful units, making it
easier to manage and maintain large projects. They are commonly used in Python software
development to create a hierarchical organization of modules and to avoid naming conflicts
between modules with similar names from different packages.

Provided By AK
7. What are the rules for local and global variables in Python?
In Python, variables can be categorized as either local or global based on their scope. The
scope of a variable defines where in the code it can be accessed. Here are the rules for local
and global variables in Python:
Local Variables:
1. A local variable is one that is defined within a function or a code block and is accessible
only within that function or block.
2. Local variables have a limited scope, which means they exist and are usable only within
the function or block where they are defined.
3. Attempting to access a local variable outside of its scope will result in a `NameError`.
4. Local variables are created when the function is called and destroyed when the function
exits.
5. Local variables can have the same name as a global variable without causing conflicts
because the local variable takes precedence within its scope.

Example of a local variable:


def my_function():
local_variable = 10 # This is a local variable
print(local_variable)

my_function()
print(local_variable) # This will raise a NameError because local_variable is not defined
globally

Global Variables:
1. A global variable is one that is defined outside of any function or code block and is
accessible throughout the entire code.
2. Global variables have a global scope, which means they can be accessed from any part of
the code, including within functions.
3. To modify a global variable within a function, you need to use the `global` keyword to
indicate that you're working with the global variable.
Example of a global variable:
global_variable = 20 # This is a global variable
def my_function():
global global_variable
global_variable += 5 # Modify the global variable within the function
my_function()
print(global_variable) # Output: 25

It's important to be cautious when using global variables because they can make your code
harder to understand and maintain. It's generally recommended to use local variables when
possible to limit the scope of your variables and avoid unintended side effects in your code.
Global variables should be used sparingly and when necessary for sharing data between
different parts of your program.

8.Differentiate key word and default arguments


Provided By AK
In Python, both keyword arguments and default arguments are related to function parameters,
but they serve different purposes. Here's a differentiation between keyword and default
arguments:

Default Arguments:
1. Default arguments are function parameters that have a predefined default value.
2. When a function is called, if a value is not provided for a default argument, the default value
is used.
3. Default arguments are defined within the function's parameter list with an assignment
operator (`=`) specifying the default value.
Example of a function with a default argument:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}"
# When calling the function, you can omit the 'greeting' argument, and it will use the default
value.
result = greet("Alice") # Result: "Hello, Alice"

Keyword Arguments:
1. Keyword arguments are used to pass values to function parameters by explicitly specifying
the parameter name along with the value.
2. They allow you to provide values for specific function parameters in any order, regardless of
the parameter order in the function definition.
Example of a function with keyword arguments:
def calculate_total(price, tax_rate, discount=0):
return price + (price * tax_rate) - discount
# Using keyword arguments to pass values to the parameters
total = calculate_total(price=100, discount=10, tax_rate=0.08) # Result: 98.0

In summary, default arguments are about providing a default value for a parameter, which is
used when no value is explicitly provided during the function call. Keyword arguments, on the
other hand, are about specifying parameter values by name, allowing you to pass them in any
order and even skip some parameters if needed. Default arguments can be used in conjunction
with keyword arguments to provide flexibility when calling functions.

9. What is anonymous function in Python?


In Python, an anonymous function is a function that is defined without a name. Anonymous
functions are also known as lambda functions. Lambda functions are typically small and
simple, used for short and one-time operations, and are often used as arguments for higher-
order functions or in situations where a named function is not required.
The syntax of a lambda function is as follows:
```lambda arguments: expression```

- `arguments` are the input parameters of the function.


- `expression` is a single expression that is evaluated and returned as the result of the
function.
Provided By AK
Lambda functions are commonly used with functions like `map()`, `filter()`, and `reduce()`,
or as key functions when sorting lists. They provide a concise way to define small, inline
functions without the need to create a full named function.

Here are some examples of using lambda functions in Python:


1. Using lambda with `map()` to square elements in a list:
```numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x2, numbers))
print(squared) # Output: [1, 4, 9, 16, 25]
```
2. Using lambda with `filter()` to filter even numbers from a list:
```numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6, 8]
```
3. Using lambda as a key function to sort a list of tuples based on the second element:
```data = [(3, 10), (1, 20), (2, 5)]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data) # Output: [(2, 5), (3, 10), (1, 20)]
```
Lambda functions are a powerful tool for creating concise and readable code in situations
where a full function definition is not necessary. However, they should be used judiciously
and only for simple, one-off operations, as more complex logic is typically better expressed
through regular named functions.

10. How modules are incorporated in a python program?


Modules are incorporated into a Python program using the `import` statement. The `import`
statement allows you to access the functions, classes, and variables defined in a module and
use them in your Python code. Here's how you can incorporate modules into a Python
program:
1. Basic `import` Statement:
To import an entire module, you can use the basic `import` statement. This allows you to
access the module's content by using the module name as a prefix.
import module_name
For example, if you have a module named `my_module`, you can import it like this:
import my_module
result = my_module.my_function()

2. `import` Statement with Aliases:


You can use aliases to make module names shorter and more convenient to use.
import module_name as alias
For example:
import my_module as mm
result = mm.my_function()
3. Importing Specific Items from a Module:
If you only need specific functions, classes, or variables from a module, you can import
Provided By AK
them individually.
```from module_name import item1, item2```
For example:
from math import sqrt, pi
result = sqrt(16)
4. Importing All Items from a Module:
You can import all items from a module using the `*` wildcard. However, this is generally
discouraged as it can lead to naming conflicts.
from module_name import *
For example:
from my_module import *
result = my_function()
When you import a module, Python searches for it in a set of directories that make up the
Python path. By default, Python includes the current directory and the standard library
directories in the path. If the module you want to import is not in the current directory or a
standard library directory, you should specify its location using the `sys.path` or by
modifying the `PYTHONPATH` environment variable.

Incorporating modules into your Python program allows you to leverage existing code,
organize your code into reusable units, and enhance the functionality of your programs with
libraries and packages.

11. What are the different iterative statements?


In Python, there are several types of iterative statements (looping constructs) that allow you
to execute a block of code repeatedly. The main iterative statements are:

1. `for` Loop:
- The `for` loop is used to iterate over a sequence (such as a list, tuple, string, or other
iterable objects) and execute a block of code for each item in the sequence.
for item in sequence:
# Code to execute for each item
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

2. `while` Loop:
- The `while` loop is used to repeatedly execute a block of code as long as a specified
condition is `True`.
while condition:
# Code to execute as long as the condition is True
Example:
count = 0
while count < 5:
print(count)
count += 1
Provided By AK
3. `for...in...` Loop (Nested `for` Loop):
- You can use nested `for` loops to iterate over multiple sequences or create patterns.
Example of a nested `for` loop:
for i in range(3):
for j in range(2):
print(i, j)

4. `break` Statement:
- The `break` statement is used to exit a loop prematurely, even if the loop condition is still
`True`.
for i in range(10):
if i == 5:
break
print(i)

5. `continue` Statement:
- The `continue` statement is used to skip the rest of the current iteration in a loop and
move to the next iteration.
for i in range(5):
if i == 2:
continue
print(i)

6. `pass` Statement:
- The `pass` statement is a no-operation statement used as a placeholder. It does nothing
when executed and is often used when a statement is syntactically required but no action is
needed.
for i in range(5):
if i == 2:
pass
print(i)

Iterative statements are essential for performing repetitive tasks in your Python programs.
They allow you to iterate over data structures, repeat code until certain conditions are met,
and control the flow of your program. The choice of which type of loop to use depends on
the specific requirements of your task.

12. Explain sentinel loop with example.


A sentinel loop, also known as a sentinel-controlled loop, is a type of loop in Python (or any
programming language) that continues to execute until a specific sentinel value is
encountered. A sentinel value is a predefined value that marks the end of the loop. When the
sentinel value is encountered, the loop terminates. Sentinel loops are commonly used when
you need to process a sequence of input values until a specific signal is received.

Here's an example of a sentinel loop in Python that reads a series of numbers from the user
Provided By AK
and calculates their sum. The loop continues until the user enters a sentinel value (e.g., 0) to
indicate the end of input:
# Initialize a variable to hold the sum
total = 0
# Sentinel value
sentinel = 0
# Continue reading numbers until the sentinel value is entered
while True:
try:
number = float(input("Enter a number (0 to quit): "))
if number == sentinel:
break # Exit the loop when the sentinel value is entered
total += number
except ValueError:
print("Invalid input. Please enter a valid number.")

print(f"The sum of the numbers is: {total}")

In this example:
1. We initialize the `total` variable to keep track of the sum and set the `sentinel` value to 0.
2. We use a `while` loop with the condition `while True`, which creates an infinite loop that
continues until the `break` statement is encountered.
3. Inside the loop, we use a `try...except` block to read a number from the user. If the user
enters a non-numeric value, the program handles the exception and prompts the user to enter
a valid number.
4. If the entered number is equal to the sentinel value (0), the `break` statement is executed,
terminating the loop.
5. Otherwise, the entered number is added to the `total` sum.
6. Once the loop exits, the program calculates and displays the sum of all the numbers
entered, excluding the sentinel value.
This is a common pattern for handling input where you want to allow users to keep
providing input until they indicate that they are done by entering a specific sentinel value.

13. What is actual and formal parameter? Explain the difference along with
an example?
In Python, when you define and call a function, you encounter the concepts of actual
parameters (also known as arguments) and formal parameters (also known as
parameters or function parameters). These terms refer to the values and variables that
are associated with a function. Here's an explanation of the difference between actual
and formal parameters with an example:

Formal Parameters (Parameters):


- Formal parameters are variables defined in the function's parameter list. They act as
placeholders for values that will be passed when the function is called.
- These parameters are part of the function's signature and define the structure of the
Provided By AK
function.
- Formal parameters are used within the function to perform operations.
- Formal parameters are local to the function, meaning they are only accessible and
meaningful within the function.

Actual Parameters (Arguments):


- Actual parameters, often called arguments, are the values or expressions that are
passed to a function when it is called.
- These values or expressions are substituted for the formal parameters within the
function during execution.
- Actual parameters are the data you provide to the function to perform specific tasks or
calculations.
- They are used to supply the function with the necessary data to complete its operation.

Here's an example to illustrate the difference between actual and formal parameters:
# Define a function with formal parameters
def greet(name, greeting):
print(f"{greeting}, {name}!")

# Call the function with actual parameters (arguments)


greet("Alice", "Hello")
greet("Bob", "Hi")

In this example:
- `name` and `greeting` are formal parameters defined in the function `greet()`. They
serve as placeholders for the actual parameters.
- When we call `greet("Alice", "Hello")`, "Alice" and "Hello" are the actual parameters
(arguments) that replace the formal parameters `name` and `greeting` during the
function call.
- The function is called twice with different actual parameters, allowing it to greet
different individuals with different greetings.

In summary, formal parameters are like variables defined within the function's
signature, while actual parameters are the values or expressions that are supplied when
calling the function, and they replace the formal parameters during the function's
execution. The relationship between formal and actual parameters allows functions to
be more flexible and reusable by accepting different inputs.

14. Define range() function and its syntax.


The `range()` function in Python is used to generate a sequence of numbers, which is
often used in for loops to iterate over a specified range of values. The `range()` function
returns an object that represents the sequence of numbers and does not store the entire
sequence in memory, making it memory-efficient for large ranges.
Provided By AK
The syntax of the `range()` function is as follows:
range(stop)
range(start, stop)
range(start, stop, step)

- `stop`: Specifies the upper bound for the sequence. The sequence includes all integers
from 0 up to (but not including) `stop`.
- `start`: Specifies the lower bound for the sequence. The sequence starts from `start`
and goes up to (but not including) `stop`.
- `step`: Specifies the step or increment by which the sequence should be generated. It
is an optional argument, and its default value is 1.

Here are some examples of using the `range()` function:


1. Using `range(stop)` to generate a sequence up to a specified stop value:
numbers = range(5) # Generates a sequence from 0 to 4 (5 is not included)
print(list(numbers)) # Output: [0, 1, 2, 3, 4]
2. Using `range(start, stop)` to generate a sequence with a specified start and stop value:
numbers = range(2, 7) # Generates a sequence from 2 to 6 (7 is not included)
print(list(numbers)) # Output: [2, 3, 4, 5, 6]
3. Using `range(start, stop, step)` to generate a sequence with a specified start, stop, and
step value:
numbers = range(1, 10, 2) # Generates a sequence from 1 to 9 with a step of 2
print(list(numbers)) # Output: [1, 3, 5, 7, 9]
In most cases, you'll use the `range()` function in the context of a `for` loop to iterate
over a range of values. It's a helpful tool for generating sequences of numbers without
explicitly defining them, making your code more efficient and readable.

15. What is the use of continue statement?


The `continue` statement in Python is used to alter the flow of control within a loop,
specifically in `for` and `while` loops. When the `continue` statement is encountered inside a
loop, it causes the remaining code in the current iteration of the loop to be skipped, and the
loop immediately proceeds to the next iteration, as if the current iteration had completed.

The primary use of the `continue` statement is to skip certain parts of the loop's code
execution based on a condition, allowing you to skip the processing of specific elements or
cases that don't meet a certain criterion.
Here's an example of how the `continue` statement is used in a `for` loop:
for i in range(1, 6):
if i == 3:
continue # Skip the current iteration when i is 3
print(i)
In this example, when `i` is equal to 3, the `continue` statement is executed, causing the loop
to skip the `print(i)` statement for that particular iteration. The result is that only the values
1, 2, 4, and 5 are printed.

Provided By AK
Similarly, here's an example of using `continue` in a `while` loop:
count = 0
while count < 5:
count += 1
if count % 2 == 0:
continue # Skip even numbers
print(count)
In this `while` loop, the `continue` statement is used to skip the printing of even numbers
(i.e., numbers divisible by 2), allowing only odd numbers to be printed.

The `continue` statement is a powerful tool for fine-tuning the control flow within loops,
enabling you to skip certain elements or conditions that do not need to be processed within
the loop.

16. Point out the uses of default arguments in python.


Default arguments in Python are used to provide a default value for a function parameter.
They are particularly useful for several purposes:

1. Flexibility: Default arguments make functions more flexible because they allow you to
call the function with fewer arguments than specified in the function definition. When you
don't provide a value for a parameter with a default argument, the default value is used
instead.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}"
# You can call greet() with just a name, and it will use the default greeting.
result = greet("Alice") # Result: "Hello, Alice"

2. Simplifying Function Calls: Default arguments can simplify function calls, especially
when you want to use a common value for a parameter in most cases, but you also need the
option to override it when necessary.
# Using a default argument to simplify function calls
result1 = greet("Alice") # Uses default greeting
result2 = greet("Bob", "Hi") # Uses custom greeting

3. Enhancing Readability: Default arguments can make code more readable by providing
context about the default behavior of a function. Developers can quickly understand the
expected behavior of the function without needing to inspect the function definition.

4. Handling Optional Parameters: Default arguments are used to create optional parameters
in functions. You can define a function with default arguments for parameters that might not
always be needed.
def send_email(to, subject, message, cc=None, bcc=None):
# Function logic for sending emails
pass

In this example, the `cc` and `bcc` parameters are optional and have default values of
`None`. Users can include or exclude these parameters based on their needs.
Provided By AK
5. Backward Compatibility: When you want to add new parameters to an existing function
without breaking existing code that calls the function, you can use default arguments. The
existing code will continue to work with the same behavior, while new code can take
advantage of the additional parameters.
def process_data(data, threshold=0.5):
# Function logic that uses the threshold parameter
pass

6. Parameter Handling: Default arguments can be used to specify default values for cases
where the parameter value is not provided or is missing.
def get_user_info(user_id, name=None, email=None):
# Function logic to retrieve user information
pass

Default arguments provide flexibility and versatility in function design, allowing you to
create functions that handle a wide range of use cases while maintaining code readability
and backward compatibility.

17. How will you create a Package & import it? Explain it with an
example program.
Creating a package in Python involves organizing related modules into a directory
and including a special file called `__init__.py` within that directory. The
`__init__.py` file can be empty or contain initialization code for the package. The
directory containing the package should be placed in a location where Python can
discover it, typically within a directory that's part of the Python path.

Let's create a simple Python package named `my_package` and demonstrate how to
import it.

1. First, create a directory for your package. You can name it `my_package`.

2. Inside the `my_package` directory, create one or more Python modules (`.py`
files) with functions, classes, or variables. For example, create a module named
`module1.py` with the following code:
def say_hello(name):
return f"Hello, {name}!"

3. Create another module named `module2.py` within the `my_package` directory:


def say_goodbye(name):
return f"Goodbye, {name}!"
```

4. In the `my_package` directory, create an empty `__init__.py` file. This file is


Provided By AK
required to treat the directory as a package.

5. Now, let's demonstrate how to import and use the package and its modules in
another Python script.

Create a Python script (e.g., `main.py`) in a different directory:

```python
from my_package import module1, module2

# Use functions from module1


greeting = module1.say_hello("Alice")
print(greeting)

# Use functions from module2


farewell = module2.say_goodbye("Bob")
print(farewell)
```

In this script, we use the `from ... import ...` syntax to import the `module1` and
`module2` modules from the `my_package` package.

6. Run the `main.py` script, and it should import the package and modules and use
their functions:

```
Hello, Alice!
Goodbye, Bob!
```

This example demonstrates how to create a package with modules and import it into
another Python script. Packages are a convenient way to organize related code into
reusable units, making your code more maintainable and organized.

18. Explain variable length arguments with example.


In Python, you can use variable-length arguments to pass a variable number of
arguments to a function. This is achieved using the `*args` and `kwargs` syntax.
Let's focus on `*args` first, which is used for variable-length positional arguments.
Here's an example of how `*args` works in Python:
def add_numbers(*args):
result = 0
for num in args:
Provided By AK
result += num
return result

# Using the function with different numbers of arguments


sum1 = add_numbers(1, 2, 3) # Passing 3 arguments
sum2 = add_numbers(4, 5, 6, 7, 8) # Passing 5 arguments
sum3 = add_numbers() # Passing no arguments

print(sum1) # Output: 6
print(sum2) # Output: 30
print(sum3) # Output: 0

In this example, the `add_numbers` function accepts a variable number of


arguments using `*args`. Inside the function, it iterates over the arguments and
calculates their sum. You can call the function with different numbers of arguments,
and it will work correctly.

Keep in mind that `*args` collects the additional positional arguments into a tuple,
which you can then process within the function.

If you need to handle variable-length keyword arguments, you can use `kwargs` in a
similar way. The `kwargs` parameter collects keyword arguments and their values
into a dictionary, which you can manipulate in your function.

19. How function is defined and called in python?


In Python, you can define and call functions as follows:
Function Definition:
To define a function, you use the `def` keyword followed by the function name and a pair of
parentheses. You can specify any parameters (inputs) inside the parentheses, followed by a
colon. The function body is indented and contains the code to be executed when the function
is called. Here's the basic structure of a function definition:
def function_name(parameter1, parameter2, ...):
# Function body
# Code to be executed
# You can use the parameters here
return result # Optional, you can return a value if needed

Here's an example of a simple function definition:


def greet(name):
message = "Hello, " + name + "!"
return message

In this example, the `greet` function takes one parameter, `name`, and returns a greeting
message.

Provided By AK
Function Calling:
Once you have defined a function, you can call it by using the function's name followed by
parentheses. If the function takes parameters, you provide them inside the parentheses.
Here's how you call a function:
result = function_name(argument1, argument2, ...)

Here's how you would call the `greet` function:


greeting = greet("Alice")
print(greeting) # Output: "Hello, Alice!"

In this example, we call the `greet` function with the argument `"Alice"`, and the function
returns the greeting message, which we then print.

Functions are a fundamental building block in Python, and they allow you to encapsulate
and reuse code, making your programs more modular and easier to maintain.

20. Explore in detail about range function with suitable examples?


The `range` function in Python is used to generate a sequence of numbers within a specified
range. It's commonly used in `for` loops to iterate over a sequence of numbers. The `range`
function is quite flexible and has a few different ways to use it. I'll explain the different
forms of the `range` function and provide examples for each.

Basic Syntax:
range(stop)
range(start, stop)
range(start, stop, step)

- `start`: The starting value of the range (inclusive). If omitted, it defaults to 0.


- `stop`: The stopping value of the range (exclusive). The range will generate numbers up to,
but not including, this value.
- `step`: The step size (the difference between each consecutive number in the range). If
omitted, it defaults to 1.

Now, let's look at examples for each of the three forms:

1. Using `range` with only the `stop` argument:


This form of `range` generates a sequence of numbers from 0 up to, but not including, the
specified `stop` value.
for i in range(5):
print(i)
Output:
0
1
2
3
4

Provided By AK
2. Using `range` with `start` and `stop` arguments:
In this form, you specify the starting value and the stopping value for the range.
for i in range(2, 7):
print(i)
Output:
2
3
4
5
6
3. Using `range` with all three arguments (`start`, `stop`, and `step`):
This form allows you to specify the starting value, stopping value, and the step size for the
range.
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
You can use the `range` function not only for iterating in `for` loops but also for other
purposes, such as generating lists of numbers or indexing specific elements in a sequence.

For example, you can use `list()` to convert a `range` object into a list:
numbers = list(range(1, 6))
print(numbers) # Output: [1, 2, 3, 4, 5]

The `range` function is memory-efficient because it generates values on-the-fly rather than
precomputing the entire sequence, making it suitable for situations where you need to work
with large ranges of numbers.

Provided By AK

You might also like