python question and answers
python question and answers
Here's an example of list comprehension that creates a list of squares of even numbers from 1
to 10:
output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
The advantage of using list comprehension is that it provides a concise and readable way to
create lists in Python. It allows you to write compact code without sacrificing readability. List
comprehension is often faster than traditional looping techniques (like using for loops)
because it is optimized for the Python interpreter. Additionally, it encourages a functional
programming style, which can lead to more elegant and efficient code.
Using the get() Method: You can also use the get() method, which returns the value for the
specified key. If the key is not found, it returns None by default, but you can specify a default
value to return instead.
# Using get() method
print(my_dict.get('city')) # Output: New York
print(my_dict.get('occupation')) # Output: None
print(my_dict.get('occupation', 'Not specified')) # Output: Not specified
Iterating Over Keys: You can iterate over the keys of the dictionary and access the
corresponding values.
# Iterating over keys
for key in my_dict:
print(key, "->", my_dict[key])
Using the keys() Method: You can use the keys() method to get a view object that displays a
list of all the keys in the dictionary.
# Using keys() method
print(my_dict.keys()) # Output: dict_keys(['name', 'age', 'city'])
Using the items() Method: You can use the items() method to get a view object that displays
a list of tuples, where each tuple contains a key-value pair.
# Using items() method
print(my_dict.items()) # Output: dict_items([('name', 'John'), ('age', 30), ('city', 'New
York')])
3. Define properties of key in dictionary. How can you access elements from the
dictionary.
Unique: Keys within a dictionary must be unique. This means that no two keys can have the
same name or value.
Immutable: Keys must be immutable objects. This means that you can use immutable data
types like strings, numbers, or tuples (if they contain only immutable elements) as keys.
However, mutable objects like lists cannot be used as keys.
To access elements from a dictionary, you can use the methods mentioned in the previous
response:
Using Square Brackets: Access elements by specifying the key within square brackets.
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
print(my_dict['name']) # Output: John
Using the get() Method: Access elements using the get() method, which returns the value for
the specified key.
# Using get() method
print(my_dict.get('city')) # Output: New York
print(my_dict.get('occupation')) # Output: None
print(my_dict.get('occupation', 'Not specified')) # Output: Not specified
Iterating Over Keys: You can iterate over the keys of the dictionary and access the
corresponding values.
# Iterating over keys
for key in my_dict:
print(key, "->", my_dict[key])
Using the keys() Method: You can use the keys() method to get a view object that displays a
list of all the keys in the dictionary.
# Using keys() method
print(my_dict.keys()) # Output: dict_keys(['name', 'age', 'city'])
Using the items() Method: You can use the items() method to get a view object that displays
a list of tuples, where each tuple contains a key-value pair.
# Using items() method
print(my_dict.items()) # Output: dict_items([('name', 'John'), ('age', 30), ('city', 'New
York')])
4. Explain key value pair? Mention different data types can be used in key and
value?
A key-value pair is a fundamental concept in dictionaries, which are a data structure used in
Python and many other programming languages. In a key-value pair, a key is associated with
a value. When you need to store and retrieve data based on some identifier (the key),
dictionaries provide an efficient way to do so.
In Python dictionaries, each key is associated with a single value, forming a unique pair.
Here's a basic example:
my_dict = {'name': 'John', 'age': 30}
In this dictionary:
'name' is a key.
'John' is the value associated with the key 'name'.
'age' is another key.
30 is the value associated with the key 'age'.
Keys can be of any immutable data type, such as:
Strings
Numbers (integers, floats)
Tuples (if they contain only immutable elements)
Values can be of any data type, including:
Strings
Numbers
Lists
Tuples
Dictionaries (nested dictionaries)
Here's an example showing different data types used as keys and values:
my_dict = {'name': 'John', 'age': 30, (1, 2): 'tuple_key', 3.14: 'pi', True: 'boolean', 'info': {'city':
'New York', 'country': 'USA'}}
In this dictionary:
'name', 'age', (1, 2), 3.14, True, and 'info' are keys.
'John', 30, 'tuple_key', 'pi', 'boolean', and {'city': 'New York', 'country': 'USA'} are the
corresponding values.
5. What is parameter and types of parameter? How can you insert values in to
dictionary?
a parameter is a variable that is used in a function definition to represent some value that will
be provided when the function is called. Parameters allow functions to accept input and
perform operations on that input.
Types of Parameters:
Positional Parameters: These are parameters that are passed to a function in a specific
order. The function receives the values in the order they are passed.
Example:
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")
greet("Alice", "Bob", "Charlie") # Output: Hello, Alice! Hello, Bob! Hello, Charlie!
To insert values into a dictionary in Python, you can assign values to specific keys using
square brackets [ ].
my_dict = {} # Create an empty dictionary
Also create a dictionary with initial values using curly braces {}:
my_dict = {'name': 'John', 'age': 30}
Keys:
Strings
Integers
Floats
Tuples (if they contain only immutable elements)
Boolean values
Custom objects (if they are hashable)
Values:
Strings
Integers
Floats
Tuples
Lists
Dictionaries (nested dictionaries)
Sets
Boolean values
None (null)
It's important to note that while keys must be of immutable types, values can be of
both immutable and mutable types. Mutable types like lists and dictionaries can be
used as values in a dictionary, allowing for flexible data structures. However, using
mutable types as keys is not allowed because keys need to be hashable for efficient
lookup operations.
Here's an example illustrating different data types used as keys and values in a dictionary:
my_dict = {
'name': 'John', # String key, string value
42: 'answer', # Integer key, string value
3.14: 'pi', # Float key, string value
('apple', 'banana'): 2, # Tuple key, integer value
True: 'boolean', # Boolean key, string value
None: [1, 2, 3], # None key, list value
'info': {'city': 'New York', 'population': 8.4}, # String key, nested dictionary value
}
print(my_dict)
This dictionary demonstrates the variety of data types that can be used as keys and values,
showcasing the flexibility and power of Python dictionaries.
UNIT – IV QUESTION AND ANSWERS
Recursive Function: A recursive function is a function that calls itself during its execution.
This technique is used to solve problems that can be broken down into smaller, similar sub-
problems. Recursive functions typically have two parts:
Base Case: This is the termination condition that prevents the function from making further
recursive calls. It defines the simplest possible case and allows the recursion to stop.
Recursive Case: This is where the function calls itself with modified arguments to solve a
smaller sub-problem. This step is repeated until the base case is reached.
Here's an example of a recursive function to calculate the factorial of a non-negative integer:
def factorial(n):
# Base case
if n == 0:
return 1
# Recursive case
else:
return n * factorial(n - 1)
Recursive functions can be elegant and concise, but they can also be less efficient and
consume more memory compared to iterative solutions. However, they are often used in
situations where the problem naturally lends itself to recursive thinking.
Lambda Function:
A lambda function, also known as an anonymous function, is a small, unnamed function
defined using the lambda keyword. Lambda functions can have any number of parameters but
can only contain a single expression. They are typically used when you need a simple
function for a short period of time and don't want to define a full-fledged function using the
def keyword.
2. Create a Python function that accepts a string and counts the number of upper
and lower case letters with flow chart.
Python function that accepts a string and counts the number of uppercase and lowercase
letters, along with a flowchart illustrating its logic:
def count_upper_lower(text):
upper_count = 0
lower_count = 0
Flow Chart:
3. Define function? Write its syntax? What are formal and actual arguments?
A function is a block of organized, reusable code that performs a specific task. It groups
together a set of statements so that they can be run more than once in a program without
having to rewrite the code each time. Functions help to modularize code, making it more
organized, readable, and maintainable.
In Python, functions are defined using the def keyword followed by the function name and a
set of parentheses containing zero or more parameters. The function body is then indented
and contains the code to be executed when the function is called.
def function_name(parameters):
"""Optional docstring"""
# Function body
# Statements to be executed
return [expression] # Optional return statement
Formal Arguments: These are the parameters defined in the function signature. They act as
placeholders for the values that will be passed to the function when it's called. Formal
arguments are used within the function's body to perform operations.
Actual Arguments: Also known as arguments or parameters, these are the actual values
passed to the function when it's called. They correspond to the formal arguments defined in
the function signature. Actual arguments can be literals, variables, expressions, or even other
function calls.
In this example, 'Alice' is the actual argument passed to the function greet(), and name is the
formal argument that receives this value within the function's body.
4. Write a Python function that takes a list and returns a new list with distinct
elements from the first list with flow chart also.
Python function that takes a list and returns a new list with distinct elements (i.e., removing
duplicates), along with a flowchart illustrating its logic:
def remove_duplicates(input_list):
distinct_elements = []
return distinct_elements
Global and local variables are two types of variables in Python, each with its own scope and
accessibility within a program.
Global Variables:
Scope: Global variables are defined outside of any function or class and can be accessed from
anywhere within the program, including inside functions and classes.
Accessibility: They can be accessed from any part of the program, including inside functions
and classes.
Lifetime: Global variables persist throughout the entire execution of the program.
Example:
global_var = 10
def my_function():
print("Value of global_var inside function:", global_var)
Local Variables:
Scope: Local variables are defined within a function or method and can only be accessed
from within that function or method.
Accessibility: They are accessible only within the function or method where they are defined.
Lifetime: Local variables exist only as long as the function or method is executing.
Example:
def my_function():
local_var = 20
print("Value of local_var inside function:", local_var)
class Dog(Animal):
def sound(self):
print("Dog barks")
# Multiple Inheritance
class Parent1:
def method1(self):
print("Method from Parent1")
class Parent2:
def method2(self):
print("Method from Parent2")
child = Child()
child.method1() # Output: Method from Parent1
child.method2() # Output: Method from Parent2
In the single inheritance example, the class Dog inherits from the class Animal, while in the
multiple inheritance example, the class Child inherits from both Parent1 and Parent2.
In Python, the filter() function is used to filter elements from an iterable (such as a list, tuple,
or set) based on a given condition. It takes two arguments: a function and an iterable. The
function passed to filter() must return a boolean value (True or False), indicating whether the
element should be included in the filtered result.
Using a Function: You can define a separate function and pass it to filter().
def is_even(num):
return num % 2 == 0
Using Lambda Function: You can use a lambda function directly as the first argument to
filter().
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6, 8, 10]
Filtering None Values: You can use filter() to remove None values from a list.
items = [1, None, 3, None, 5, None, 7]
filtered_items = list(filter(None, items))
print(filtered_items) # Output: [1, 3, 5, 7]
Filtering Based on Length: You can filter elements based on their length, for example,
filtering out empty strings.
strings = ["", "hello", "", "world", "", "python"]
non_empty_strings = list(filter(lambda x: len(x) > 0, strings))
print(non_empty_strings) # Output: ['hello', 'world', 'python']
Filtering Based on Custom Conditions: You can filter elements based on any custom
condition.
ages = [25, 17, 30, 16, 21, 18, 35]
adults = list(filter(lambda age: age >= 18, ages))
print(adults) # Output: [25, 30, 21, 18, 35]
The filter() function returns an iterator, so you need to convert it to a list (or tuple, set, etc.) to
view the filtered elements. It's a powerful tool for selectively extracting elements from
iterables based on specific criteria.
UNIT – V QUESTION AND ANSWERS
1. List some few common Exception types and explain when they occur. How to
create user defined exception in python with an example.
Common exception types in Python:
SyntaxError: This occurs when the Python parser encounters a syntax error, such as a
missing colon at the end of a statement or an invalid indentation.
Example:
# Missing colon
if True
print("Hello")
Indentation Error: This occurs when there is an incorrect indentation in the code, such as
mixing tabs and spaces or inconsistent indentation levels.
Example:
def my_function():
print("Indented incorrectly")
NameError: This occurs when a name (variable, function, etc.) is not found in the local or
global scope.
Example:
print(unknown_variable)
ValueError: This occurs when a built-in operation or function receives an argument with the
right type but an inappropriate value.
Example:
x = int("hello")
IndexError: This occurs when trying to access an index that does not exist in a sequence
(e.g., list, tuple, string).
Example:
my_list = [1, 2, 3]
print(my_list[3])
def validate_age(age):
if age < 0 or age > 120:
raise InvalidAgeError(age)
else:
print("Valid age")
In this example:
A custom exception class InvalidAgeError that inherits from the built-in Exception class is
defined.
Override the __init__ method to customize the exception message.
A function validate_age() that raises InvalidAgeError if the age is not within the valid range
is defined.
Tested the custom exception by calling validate_age() with an invalid age and catching the
InvalidAgeError exception. If the age is invalid, the exception is raised, and its message is
printed.
To create a seeded random number generator and generate a float between 0 and 1 (excluding
1) in Python using the random. random() function,
import random
def seeded_random(seed):
random.seed(seed)
def generate_random_float():
return random.random()
End of Program
In Python, the from ... import ... statement is used to import specific attributes (functions,
variables, classes, etc.) from a module into the current namespace. It provides a way to
selectively import only the desired components from a module, rather than importing the
entire module.
The syntax for the from ... import ... statement is as follows:
from module_name import name1, name2, ...
module_name: The name of the module from which you want to import attributes.
name1, name2, ...: The names of the specific attributes (functions, variables, classes, etc.) that
you want to import from the module.
Here's an example to illustrate how the from ... import ... statement works:
The from ... import ... statement to import specific functions from the math_operations
module into another Python script:
# main.py
from math_operations import add, subtract
result_add = add(5, 3)
result_subtract = subtract(10, 4)
In this example:
From math_operations import add, subtract to import only the add and subtract functions
from the math_operations module are used. Then directly use these imported functions (add
and subtract) without prefixing them with the module name. Other functions (multiply and
divide) defined in the math_operations module are not imported and cannot be used directly
in the main.py script.
Using from ... import ... statement allows for more concise and selective imports, which can
improve code readability and reduce potential naming conflicts. However, be cautious not to
import too many attributes from modules, as it can clutter the namespace and make code
harder to understand.
Packages are commonly used in Python for structuring large projects and libraries.
class MyClass:
def method1(self):
pass
def method2(self):
pass
In this example:
Define a user-defined class MyClass with two methods: method1 and method2. Create an
instance obj of the MyClass. Use the isinstance() function along with types.MethodType to
check if obj.method1 and obj.method2 are methods of the class MyClass. The isinstance()
function returns True if the value is an instance of the specified type (types.MethodType in
this case), otherwise False. A regular function (my_function) is not considered a method of
the class.
6. Write syntax for Handling Exceptions with example.
The syntax for handling exceptions in Python along with an example:
try:
# Code that may raise an exception
# ...
# ...
except ExceptionType1 as e:
# Handle exception of type ExceptionType1
# Optionally, you can access the exception object using 'e'
# ...
except ExceptionType2 as e:
# Handle exception of type ExceptionType2
# Optionally, you can access the exception object using 'e'
# ...
except (ExceptionType3, ExceptionType4) as e:
# Handle exceptions of type ExceptionType3 or ExceptionType4
# Optionally, you can access the exception object using 'e'
# ...
except Exception as e:
# Handle any other exceptions not caught by previous except blocks
# Optionally, you can access the exception object using 'e'
# ...
else:
# Optional else block executed if no exception occurs in the try block
# ...
finally:
# Optional finally block always executed regardless of whether an exception occurs
or not
# This block is used for cleanup activities, such as closing files or releasing resources
# It is executed even if a "return", "break", or "continue" statement is encountered in
the "try" or "except" blocks pass # Placeholder for cleanup code
Example demonstrating the usage of the try, except, else, and finally blocks:
try:
x = int(input("Enter a number: "))
result = 10 / x
print("Result:", result)
except ValueError:
print("Please enter a valid integer.")
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("No exceptions occurred.")
finally:
print("Execution completed.")
In this example:
7. Write a Python program to configure the rounding to round to the floor, ceiling
Configure the rounding behavior in Python using the math.floor() and math.ceil() functions
from the math module. Here's a Python program that demonstrates how to round to the floor
and ceiling:
import math
def round_to_floor(number):
"""Round to the nearest integer less than or equal to the given number."""
return math.floor(number)
def round_to_ceiling(number):
"""Round to the nearest integer greater than or equal to the given number."""
return math.ceil(number)
In this program:
Import the math module to access the math.floor() and math.ceil() functions. Define two
functions round_to_floor() and round_to_ceiling() that round a given number to the floor and
ceiling, respectively, using math.floor() and math.ceil() functions. Test the functions with a
sample number (5.7). The round_to_floor() function rounds 5.7 to the nearest integer less
than or equal to 5.
The round_to_ceiling() function rounds 5.7 to the nearest integer greater than or equal to 6.