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

Python Important 6666

The document provides a comprehensive overview of Python programming concepts, including data types, functions, modules, and object-oriented programming principles. It covers key topics such as the differences between sets and dictionaries, the use of libraries like NumPy and Pandas, and various exception handling techniques. Additionally, it discusses GUI development with Tkinter and machine learning with libraries like Scikit-learn and TensorFlow.

Uploaded by

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

Python Important 6666

The document provides a comprehensive overview of Python programming concepts, including data types, functions, modules, and object-oriented programming principles. It covers key topics such as the differences between sets and dictionaries, the use of libraries like NumPy and Pandas, and various exception handling techniques. Additionally, it discusses GUI development with Tkinter and machine learning with libraries like Scikit-learn and TensorFlow.

Uploaded by

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

Python Important • Cross-platform: Python is platform-independent, meaning it runs on different

operating systems.
10. What is Modules.
Ans: A module in Python is a file containing Python code (such as functions, classes, or
Q1. Short answer type questions. 5. Explain the input( ) function variables) that can be imported and used in other Python programs. Modules help organize
Ans: The input() function is used to take input from the user in Python. It reads a line from and reuse code across different programs. For example, math, os, and random are
1. Write down difference between set and dictionary in python?
the input (usually from the keyboard) and returns it as a string. Example: standard Python modules.
Ans: A. Set:
name = input("Enter your name: ") import os # Importing the os module
• A set is an unordered collection of unique elements.
print("Hello, " + name) print(os.getcwd()) # Gets the current working directory
• Elements in a set cannot be duplicated.
6. Define Tkinter. 11. What are special operators in Python?
• It is defined using curly braces {} or the set() constructor.
Ans: Tkinter is the standard GUI (Graphical User Interface) library in Python. It provides Ans: Special operators in Python include:
• Example: set1 = {1, 2, 3}.
tools to create windows, buttons, labels, text fields, and other GUI elements. Tkinter is built • Identity Operators: is and is not (checks if two objects are the same).
• Sets are mutable but do not support indexing.
on top of the Tcl/Tk GUI toolkit • Membership Operators: in and not in (checks if a value is a member of a sequence,
B. Dictionary:
7. How to create class and objject in python. like a list or string).
• A dictionary is a collection of key-value pairs.
Ans: To create a class in Python, use the class keyword, followed by the class name and a 12. Difference between Python list and Numpy array.
• Keys in a dictionary are unique, while values can be duplicated.
colon. You can define methods within the class. An object is an instance of a class, created Ans: Difference between Python List and NumPy Array:
• It is also defined using curly braces {} with key-value pairs separated by colons.
by calling the class. • Python List:
• Example: dict1 = {'a': 1, 'b': 2, 'c': 3}.
class Person: o Can store heterogeneous elements (e.g., integers, strings, floats).
• Dictionaries support indexing based on keys and are mutable.
def __init__(self, name, age): o Slow for numerical operations because it lacks efficient vectorized
2. Define numpy.
self.name = name operations.
Ans: NumPy is a popular Python library used for numerical computing. It provides support
self.age = age o Example: [1, 2, "abc", 3.5].
for large, multi-dimensional arrays and matrices, along with a collection of mathematical
• NumPy Array:
functions to perform operations on these arrays efficiently. It is widely used in data
def greet(self): o Homogeneous, stores elements of the same data type (usually numerical).
science, machine learning, and scientific computing.
print(f"Hello, my name is {self.name} and I am {self.age} years old.") o Faster for mathematical operations due to efficient memory usage and
3. What is exception in python.
# Creating an object support for vectorized operations.
Ans: An exception in Python is an error that occurs during the execution of a program.
person1 = Person("Alice", 25) o Example: numpy.array([1, 2, 3, 4]).
When an error occurs, Python interrupts the normal flow of the program and raises an
person1.greet() 13. State any four time module.
exception. Exceptions can be handled using try-except blocks to prevent the program from
8. How to import package python. Ans:
crashing. Example: ZeroDivisionError, TypeError, ValueError.
Ans: To import a package or module in Python, use the import statement. You can import • time.time() - Returns the current time in seconds since the Epoch.
4. Explain features of python
the entire module or specific functions from it. • time.sleep(seconds) - Pauses the program for the specified number of seconds.
Ans: Features of Python:
import math # Imports the entire math module • time.localtime() - Converts seconds since Epoch to a struct_time object.
• Easy to Learn and Use: Python has a simple syntax and is easy for beginners to
from math import sqrt # Imports only the sqrt function from the math module • time.strftime(format) - Formats struct_time as a string according to the format.
learn.
9. Define functions in python 14. What is class variable?
• Interpreted Language: Python code is executed line by line, making debugging
Ans: A function in Python is a block of reusable code that performs a specific task. It is Ans: A class variable is a variable that is shared among all instances of a class. It is defined
easier.
defined using the def keyword followed by the function name and parentheses (). Functions within a class but outside any instance methods. Changes to the class variable affect all
• Dynamically Typed: Variable types are inferred at runtime, so you don't need to
can take parameters and return values. instances of the class.
declare them.
def add(a, b): 15. List out Geometry management methods.
• Object-Oriented: Supports classes and objects, facilitating code reusability.
return a + b Ans:
• Extensive Libraries: Python has a vast collection of libraries and frameworks for
result = add(5, 3) • pack(): Packs widgets into the parent widget.
different purposes (e.g., NumPy, Pandas, Django).
print(result) # Output: 8 • grid(): Arranges widgets in a table-like structure.

• place(): Places widgets at specific coordinates. Ans:The random.random() function returns a random floating-point number between 0.0 1. Unordered: Dictionaries are unordered collections of key-value pairs.
16. Define term Bind method. and 1.0. 2. Keys Are Unique: Keys must be unique, but values can be duplicated.
Ans: The bind() method in Tkinter is used to bind an event (like a mouse click or key press) 24. What is the syntax of constructor in Python? 3. Mutable: You can change, add, or remove key-value pairs after the dictionary is
to a widget. It allows an action to be performed when the event occurs. Ans: class MyClass: created.
17. What is Sea born? def __init__(self, value): 32. Write the use of an import statement with an example.
Ans: Seaborn is a Python data visualization library built on top of Matplotlib. It provides a self.value = value Ans: The import statement is used to include external modules into your code.
high-level interface for creating attractive and informative statistical graphics, particularly 25. What is the use of try - finally block? import math
for working with pandas data frames. Ans: The try - finally block ensures that the code inside the finally block is executed print(math.sqrt(16)) # Output: 4.0
18. Write any two common exceptions in Python. regardless of whether an exception occurs in the try block. 33. What is scikit-learn?
Ans: 26. List out any 5 button options in Python? Ans: Scikit-learn is a popular Python library for machine learning. It provides simple and
• ValueError: Raised when a function receives an argument of the correct type but an Ans: efficient tools for data mining, data analysis, and machine learning algorithms, such as
inappropriate value. 1. text: Text displayed on the button. classification, regression, clustering, and dimensionality reduction.
• TypeError: Raised when an operation or function is applied to an object of an 2. command: Function to execute when the button is clicked. 34. Write the definition of class method.
inappropriate type. 3. bg: Background color of the button. Ans: A class method is a method that is bound to the class, not the instance. It can modify
19. What are advantages of pandas. 4. fg: Foreground (text) color of the button. class-level data and is defined using the @classmethod decorator.
Ans: 5. state: Specifies the button state (e.g., NORMAL, DISABLED). 35. Write the syntax of the Raise statement & explain it.
• Efficient Data Manipulation: Allows fast and easy manipulation of structured data. 27. How is grid() geometry management method used in tkinter? Ans: raise ExceptionType("Error message")
• Data Alignment: Automatically aligns data by labels. Ans: The grid() method arranges widgets in a table-like structure. It places widgets in rows The raise statement is used to manually raise an exception. It takes an exception type (e.g.,
• Handling Missing Data: Has built-in methods for detecting and filling missing data. and columns. ValueError, TypeError) and an optional error message.
• Data Cleaning: Provides extensive functionality for cleaning and transforming button1.grid(row=0, column=0) 36. Break and pass statement in Python.
datasets. button2.grid(row=0, column=1) Ans: break: Exits the nearest enclosing loop & pass: Does nothing; used as a placeholder
20. List out special operators in Python? 28. State the uses of tensor flow. for future code.
Ans: Ans:
1. Identity Operators: is, is not 1. Deep Learning: TensorFlow is used for building and training deep learning models. Q2. Long answer type questions.
2. Membership Operators: in, not in 2. Machine Learning: It provides tools for creating, training, and deploying machine
3. Arithmetic Operators: +, -, *, / learning models. 1. Explain int 'float' Str, range data types with syntax and example.
4. Logical Operators: and, or, not 3. Cross-platform: TensorFlow works across various devices, from mobile to cloud. Ans: 1. int: Represents integer numbers (whole numbers).
21. Explain any two tuple operations with an example. 29. Write Syntax of Raise Statement. x = 10 # Integer
Ans: 1. Indexing: Access elements by their index. Ans: if age < 0: print(type(x)) # Output: <class 'int'>
t = (1, 2, 3) raise ValueError("Age cannot be negative") 2. float: Represents floating-point numbers (decimal numbers).
print(t[1]) # Output: 2 30. List out any 4 label option. y = 10.5 # Floating-point number
2. Slicing: Get a portion of the tuple Ans: print(type(y)) # Output: <class 'float'>
t = (1, 2, 3, 4) 1. text: Sets the text to display. 3. str: Represents string data (sequence of characters).
print(t[1:3]) # Output: (2, 3) 2. bg: Sets the background color. s = "Hello" # String
22. What is the use of '+' and '*' operators on tuples? 3. fg: Sets the foreground (text) color. print(type(s)) # Output: <class 'str'>
Ans: + is used for concatenation & * is used for repetition 4. font: Specifies the font type and size. 4. range: Represents a sequence of numbers, typically used in loops.
23. What is the use of random() in random module? 31. What are the properties of a Dictionary? r = range(5) # Creates a range object from 0 to 4
Ans: print(list(r)) # Output: [0, 1, 2, 3, 4]
obj = Child()
2. Describe for loop in python with syntax and example. 4. What is Inheritance? Explain its types with syntax and example. obj.display()
Ans: A for loop in Python is used to iterate over a sequence (such as a list, tuple, string, or Ans: Inheritance is a feature of object-oriented programming (OOP) that allows a class 4. Hierarchical Inheritance:In hierarchical inheritance, multiple child classes inherit from
range) and perform a block of code for each element in that sequence. (child class or subclass) to inherit properties and methods from another class (parent class the same parent class.
Syntax: or superclass). This helps in code reusability, as the child class can reuse the attributes class Animal:
for variable in sequence: and methods of the parent class without rewriting them. def sound(self):
# Code block (loop body) Types of Inheritance: print("Animal makes sound.")
1. Single Inheritance: In single inheritance, a child class inherits from only one class Cat(Animal): # Cat inherits from Animal
• variable: This is the control variable that holds the current item from the sequence during parent class. def meow(self):
each iteration. class Parent: print("Cat meows.")
• sequence: This can be any iterable object such as a list, tuple, string, or range.
def display(self): class Dog(Animal): # Dog also inherits from Animal
• The code block inside the loop will be executed once for each element in the sequence.
print("Parent class") def bark(self):
class Child(Parent): print("Dog barks.")
Example 1: Iterating over a list
my_list = [1, 2, 3, 4, 5] pass d = Dog()
for num in my_list:
print(num)
obj = Child() c = Cat()
Example 2: Using range() in a for loop obj.display() d.sound() # Inherited from Animal class
for i in range(1, 6): 2. Multiple Inheritance: In multiple inheritance, a child class inherits from more than one d.bark() # Defined in Dog class
print(i)
Example 3: Iterating over a string parent class. c.sound() # Inherited from Animal class
word = "Python" class Parent1: c.meow() # Defined in Cat class
for char in word:
print(char) def display1(self): 5. Hybrid Inheritance:Hybrid inheritance is a combination of two or more types of
print("Parent1 class") inheritance, such as multiple and multilevel inheritance.
3. Differentiate between list and Tuple. class Parent2: class Vehicle:
Ans: def display2(self): def general_info(self):
print("Parent2 class") print("This is a vehicle.")
class Child(Parent1, Parent2): class Car(Vehicle):
pass def car_info(self):
obj = Child() print("This is a car.")
obj.display1() # Output: Parent1 class class Truck(Vehicle):
obj.display2() # Output: Parent2 class def truck_info(self):
3. Multilevel Inheritance: In multilevel inheritance, a child class inherits from a parent print("This is a truck.")
class, and another class can inherit from that child class (forming a chain of inheritance). class ElectricCar(Car, Vehicle): # Multiple and hierarchical
class Grandparent: def electric_info(self):
def display(self): print("This is an electric car.")
print("Grandparent class") ec = ElectricCar()
class Parent(Grandparent): ec.general_info() # Inherited from Vehicle class
pass ec.car_info() # Inherited from Car class
class Child(Parent): ec.electric_info() # Defined in ElectricCar class
pass

5. Explain predefined and user defined functions with example o Pandas: A powerful library for data manipulation and analysis, offering data • time: Represents a time (hour, minute, second, microsecond).
Ans: 1. Predefined Functions structures like DataFrame. • timedelta: Represents a duration, the difference between two dates or times.
Predefined functions (also called built-in functions) are functions that are provided by o NumPy: A library for numerical computing with support for large, multi- Example of the datetime Module
Python by default. You don't need to define them; they are ready to use. Examples of dimensional arrays and matrices, along with a collection of mathematical from datetime import datetime, date, time, timedelta
predefined functions include print(), len(), type(), etc. functions.
• Example: 3. Scientific Computing Libraries # Getting the current date and time
my_list = [1, 2, 3, 4] These libraries are designed for scientific and mathematical computations, often used in current_datetime = datetime.now()
print(len(my_list)) # Output: 4 research and academia. print("Current date and time:", current_datetime)
num = 10 • Example:
print(type(num)) o SciPy: Builds on NumPy and provides additional functionality for # Creating a date object
2. User-Defined Functions optimization, integration, interpolation, and more. specific_date = date(2024, 10, 2)
A user-defined function is a function that you create in your code. It is used to group a set of o SymPy: A library for symbolic mathematics, enabling algebraic operations, print("Specific date:", specific_date)
statements that you want to execute multiple times, making your code more organized and calculus, and equation solving.
reusable. To define a function in Python, you use the def keyword. 4. Machine Learning and AI Libraries # Creating a time object
• Syntax: These libraries provide tools for building and training machine learning models and specific_time = time(14, 30) # 2:30 PM
def function_name(parameters): performing AI tasks. print("Specific time:", specific_time)
# Code block • Example:
return value # Optional o Scikit-learn: A library for machine learning that offers simple and efficient # Performing date arithmetic with timedelta
• Example: tools for data mining and analysis. tomorrow = current_datetime + timedelta(days=1)
def add_numbers(a, b): o TensorFlow: An open-source framework for building machine learning and print("Tomorrow's date and time:", tomorrow)
return a + b deep learning models developed by Google.
result = add_numbers(5, 3) o PyTorch: An open-source machine learning library developed by Facebook, # Getting the difference between two dates
print(result) # Output: 8 known for its flexibility and ease of use in deep learning applications. days_difference = specific_date - date.today()
5. Web Development Libraries print("Days until the specific date:", days_difference.days)
6. Explain different types of python libraries. These libraries facilitate web development by providing tools for building web applications 2. calendar Module
Ans: 1. Standard Libraries and handling web-related tasks. The calendar module provides functions related to the calendar, including functionalities
These are built-in libraries that come with Python and provide a wide range of • Example: to display a calendar for a specific month or year, as well as to determine the day of the
functionalities. They cover areas such as file I/O, system calls, data manipulation, and o Flask: A lightweight web framework for building web applications with week for a given date.
more. Python. Example of the calendar Module
• Example: o Django: A high-level web framework that promotes rapid development and python
o os: Provides functions to interact with the operating system. clean, pragmatic design. Copy code
o sys: Contains system-specific parameters and functions. import calendar
o math: Provides mathematical functions. 7. Explain data time and calendar module with example.
2. Data Manipulation and Analysis Libraries Ans: 1. datetime Module # Displaying a calendar for a specific month
These libraries are used for data manipulation, analysis, and handling large datasets The datetime module provides classes for manipulating dates and times. It includes year = 2024
efficiently. several classes, but the most commonly used ones are: month = 10
• Example: • datetime: Combines both date and time. print(f"Calendar for {calendar.month_name[month]} {year}:\n")
• date: Represents a date (year, month, day). print(calendar.month(year, month))
Ans: The sys module in Python provides access to some variables used or maintained by check = Checkbutton(window, text="Agree")
# Finding the day of the week for a specific date the interpreter and functions that interact with the Python runtime environment. This check.pack()
day_of_week = calendar.weekday(2024, 10, 2) # 0 = Monday, 1 = Tuesday, etc. module is part of the standard library, meaning it comes bundled with Python and does not
print("Day of the week for 2024-10-02:", calendar.day_name[day_of_week]) require any installation. 11. Which are the basic dictionary operations? Explain any 4 with example.
Common Functions and Attributes of sys. Ans: Dictionaries in Python are unordered collections of key-value pairs. They are mutable
# Checking if a year is a leap year • sys.argv: List of command-line arguments passed to the script. and allow for fast retrieval, insertion, and deletion of items.
is_leap = calendar.isleap(2024) • sys.exit([arg]): Exit from the program. The optional argument is the exit status. 1. Accessing Values:
print("Is 2024 a leap year?", is_leap) • sys.version: A string containing the version of Python. d = {'a': 1, 'b': 2}
• sys.platform: String indicating the platform. print(d['a']) # Output: 1
8. Describe Local and Global Variable with syntax and example. • sys.path: List of directories that the interpreter searches for modules.
Ans: 1. Local Variables • sys.stdin, sys.stdout, sys.stderr: File objects representing the interpreter’s 2. Adding/Updating Items:
Local variables are defined within a function and can only be accessed inside that standard input, output, and error streams. d['c'] = 3 # Adds a new key-value pair
function. They are created when the function starts and destroyed when the function ends. • sys.version_info: Tuple containing version information. print(d) # Output: {'a': 1, 'b': 2, 'c': 3}
Syntax: The sys module is a powerful tool for interacting with the Python interpreter and the
def function_name(): execution environment. It provides useful functionalities for system-level operations, 3. Removing Items:
local_variable = value # Local variable command-line arguments handling, and managing input and output. Understanding how to d.pop('b') # Removes the key 'b'
# Code using local_variable use the sys module effectively can enhance your Python programming, especially when print(d) # Output: {'a': 1, 'c': 3}
Example of Local Variable: writing scripts and applications that require system-level interactions.
def my_function(): 10. Explain different types of Tkinter widgets with example. 4. Checking for Keys:
local_var = "I am a local variable" Ans: Button: Creates a clickable button. print('a' in d) # Output: True
print(local_var) # Accessible inside the function from tkinter import Button, Tk print('d' in d) # Output: False
my_function() window = Tk()
2. Global Variables button = Button(window, text="Click Me") 12. Explain math and Cmath module in detail.
Global variables are defined outside of any function and can be accessed from any part of button.pack() Ans: Math Module:
the code, including inside functions. They remain in memory for the lifetime of the program. window.mainloop() The math module provides mathematical functions for real numbers and performs tasks
Syntax: like square roots, trigonometric operations, and logarithms. It's suitable for calculations
global_variable = value # Global variable Label: Displays text or images. involving real numbers (integers, floats).
def function_name(): from tkinter import Label Key functions:
# Code using global_variable label = Label(window, text="Hello World") • math.sqrt(x): Returns the square root of x.
Example of Global Variable: label.pack() • math.sin(x), math.cos(x), math.tan(x): Trigonometric functions.
global_var = "I am a global variable" # Global variable • math.factorial(x): Returns the factorial of x.
def my_function(): Entry: Creates a text entry field. • math.log(x, base): Returns the logarithm of x to the given base.
print(global_var) # Accessible inside the function from tkinter import Entry • math.pi: Constant representing π (3.1415...).
my_function() entry = Entry(window) Example:
print(global_var) entry.pack() import math
print(math.sqrt(16)) # 4.0
9. Explain SYS module in detail. Checkbutton: Creates a checkbox. print(math.factorial(5)) # 120
from tkinter import Checkbutton

Cmath Module: Ans: Exception handling in Python allows you to manage runtime errors, preventing the 2. Modularity: Everything in Keras is modular, allowing developers to easily build and
The cmath module provides functions for complex numbers, similar to the math module program from crashing unexpectedly. The mechanism involves try, except, else, finally, and customize models using layers, optimizers, and loss functions.
but with support for complex data types. This is useful when dealing with real and raise. 3. Composability: Models in Keras are constructed using a sequence of layers or a
imaginary numbers in scientific computations. 1. try-except block: Catches and handles exceptions. directed acyclic graph (for more complex architectures).
Key functions: try: 4. Extensibility: Keras is highly flexible, allowing custom layers and models to be
• cmath.sqrt(x): Returns the square root of x for complex numbers. result = 10 / 0 created.
• cmath.sin(x), cmath.cos(x), cmath.tan(x): Trigonometric functions for complex except ZeroDivisionError: 5. Backend Agnostic: Keras was originally backend agnostic, meaning it could run on
numbers. print("You can't divide by zero!") top of multiple deep learning backends like TensorFlow, Theano, or CNTK. However,
• cmath.exp(x): Exponential of x for complex numbers. 2. Multiple Exceptions: Catching different exceptions. now it focuses on TensorFlow as the primary backend.
• cmath.phase(x): Returns the phase of a complex number. try:
Example: result = int("abc") 16. What are built in dictionary function in Python with example.
import cmath except ValueError: Ans: Python provides several built-in functions to work with dictionaries. Here are some of
print(cmath.sqrt(-1)) print("Invalid literal for int!") the most commonly used ones:
3. else: Code to run if no exception occurs. 1. dict.keys(): Returns a view object containing the dictionary’s keys.
13. Explain different data types in Python. d = {"a": 1, "b": 2, "c": 3}
Ans: Python supports various built-in data types, categorized as follows: try: print(d.keys()) # Output: dict_keys(['a', 'b', 'c'])
1. Numeric Types: result = 10 / 2 2. dict.values(): Returns a view object containing the dictionary’s values.
o int: Integer values, e.g., 10, -5. except ZeroDivisionError: print(d.values()) # Output: dict_values([1, 2, 3])
o float: Floating-point numbers, e.g., 10.5, 3.14. print("Division error") 3. dict.items(): Returns a view object containing the dictionary’s key-value pairs.
o complex: Complex numbers, e.g., 1 + 2j. else: print(d.items()) # Output: dict_items([('a', 1), ('b', 2), ('c', 3)])
2. Sequence Types: print("No error, result is:", result) 4. dict.get(key, default): Returns the value for the specified key. If the key is not found,
o list: Ordered, mutable sequence of elements, e.g., [1, 2, 3]. 4. finally: it returns the default value.
o tuple: Ordered, immutable sequence, e.g., (1, 2, 3). try: print(d.get("a")) # Output: 1
o str: Immutable string of characters, e.g., "hello". result = 10 / 2 print(d.get("z", "Not found")) # Output: Not found
o range: Represents a sequence of numbers, e.g., range(0, 10). finally: 5. dict.update(): Updates the dictionary with elements from another dictionary or
3. Mapping Type: print("This will always execute.") from an iterable of key-value pairs.
o dict: Collection of key-value pairs, e.g., {"name": "Alice", "age": 25}. 5. raise: Manually raising an exception. d.update({"d": 4, "e": 5})
4. Set Types: raise ValueError("This is an error message.") print(d) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
o set: Unordered collection of unique elements, e.g., {1, 2, 3}. 6. dict.pop(key): Removes the key and returns its value. Raises a KeyError if the key is
o frozenset: Immutable version of a set. 15. Explain principle of Keras. not found.
5. Boolean Type: Ans: Keras is an open-source neural network library in Python, designed to enable fast value = d.pop("a")
o bool: Represents True or False. experimentation with deep learning models. It is built on top of TensorFlow and provides a print(value) # Output: 1
6. None Type: high-level API that simplifies model building. print(d) # Output: {'b': 2, 'c': 3, 'd': 4, 'e': 5}
o None: Represents the absence of a value. Key Principles: 7. dict.clear(): Removes all the elements from the dictionary.
1. User-Friendly API: Keras aims to be user-friendly and modular. The API is designed d.clear()
14. Explain various types of exceptional handling in Python. to be simple, so developers can focus on building and experimenting with models print(d) # Output: {}
without worrying about low-level details.
17. Explain features of pandas in Python.
Ans: Pandas is a powerful data manipulation and analysis library for Python, widely used in self.engine = Engine() # Car HAS-A Engine
data science. Some of its key features are: 20. Explain EXCEPT Clause with no exception.
1. DataFrame: The primary data structure, similar to a table with rows and columns, Ans: In Python, you can use an except clause without specifying any particular exception. def drive(self):
ideal for handling and analyzing structured data. This will catch any kind of exception that occurs in the try block. self.engine.start()
2. Data Alignment: Pandas automatically aligns data in computations based on labels, Example: print("Car is driving")
making it easy to manipulate missing or irregular data. try:
3. Handling Missing Data: Pandas provides functions like isnull(), fillna(), and dropna() x = 10 / 0 car = Car()
to identify and handle missing data efficiently. except: car.drive()
4. Indexing and Slicing: Powerful methods for selecting, filtering, and slicing data using print("An error occurred!") # This will catch any exception Here, the Car class has an instance of the Engine class, creating a HAS-A relationship.
labels, booleans, or positions (loc, iloc). This is generally discouraged because it catches all exceptions, including system-related
5. GroupBy Operations: Allows grouping of data for aggregation or transformation. ones, making it harder to debug. It's better to catch specific exceptions. 22. Explain function Arguments in detail?
Ans: In Python, function arguments allow you to pass values to a function when you call it.
18. Explain the following with proper syntax and example entry.delete, entry.insert. 21. Explain IS-A relationship and HAS-A relationship with example. There are several types of function arguments:
Ans: In Tkinter (Python's standard GUI library), Entry widgets are used to take input from Ans: 1. IS-A Relationship: The IS-A relationship refers to inheritance. A derived (child) 1. Positional Arguments: These are arguments that need to be passed in the same
the user. Here’s how entry.delete() and entry.insert() work: class inherits from a base (parent) class, meaning the child class "is a" more specific type order as the function definition.
1. entry.delete(start, end): Deletes characters from the Entry widget. start is the of the parent class. def greet(name, age):
starting index, and end is the ending index. Example: print(f"Hello, {name}. You are {age} years old.")
o To delete all the text in the Entry widget: entry.delete(0, 'end'). class Animal: greet("Alice", 25) # Output: Hello, Alice. You are 25 years old.
Example: def speak(self): 2. Keyword Arguments: Arguments can be passed using their parameter names,
import tkinter as tk print("Animal speaks") allowing them to be provided in any order.
root = tk.Tk() greet(age=25, name="Alice") # Output: Hello, Alice. You are 25 years old.
entry = tk.Entry(root) class Dog(Animal): # Dog IS-A Animal 3. Default Arguments: You can provide default values for function parameters. If no
entry.pack() def speak(self): argument is passed for that parameter, the default value will be used.
entry.delete(0, 'end') print("Dog barks") def greet(name, age=30):
root.mainloop() print(f"Hello, {name}. You are {age} years old.")
2. entry.insert(index, text): Inserts the specified text at the given index. dog = Dog() greet("Bob") # Output: Hello, Bob. You are 30 years old.
entry.insert(0, "Hello, World!") # Inserts the text at the beginning dog.speak() # Output: Dog barks 4. Variable-Length Arguments: There are two types of variable-length arguments:
Here, Dog is a subclass of Animal, forming an IS-A relationship. o (Non-keyword arguments): Allows passing a variable number of positional
19. How to define function in Python? Explain with suitable example. 2. HAS-A Relationship: The HAS-A relationship refers to composition. A class contains an arguments.
Ans: A function in Python is defined using the def keyword followed by the function name, instance of another class as one of its attributes, meaning that one class "has a" reference def add(*numbers):
parameters in parentheses, and a colon. The body of the function contains the statements to another. return sum(numbers)
to execute. Example: print(add(1, 2, 3)) # Output: 6
Example: class Engine: o (Keyword arguments): Allows passing a variable number of keyword
def greet(name): def start(self): arguments.
print("Hello, " + name + "!") print("Engine started") def print_details(**info):
greet("Alice") # Output: Hello, Alice! for key, value in info.items():
Here, greet() is the function name, and it takes one parameter name. When the function is class Car: print(f"{key}: {value}")
called with the argument "Alice", it prints a greeting message. def __init__(self): print_details(name="Alice", age=25, city="New York")

23.Write in brief about anonymous functions. root = tk.Tk() d = {'a': 1, 'b': 2, 'c': 3}
Ans: An anonymous function in Python is a function without a name, typically created button1 = tk.Button(root, text="Button 1") item = d.popitem()
using the lambda keyword. These functions are limited to a single expression and are used button2 = tk.Button(root, text="Button 2") print(d) # Output: {'a': 1, 'b': 2}
where simple functionality is needed without defining a full function. button1.pack(side="left") print(item) # Output: ('c', 3)
Syntax: button2.pack(side="right") 3. del: Deletes a specific key-value pair from the dictionary or deletes the entire
lambda arguments: expression root.mainloop() dictionary.
Example: 2. grid(): The grid() method organizes widgets in a table-like structure (grid of rows and d = {'a': 1, 'b': 2, 'c': 3}
add = lambda x, y: x + y columns). del d['a']
print(add(3, 5)) # Output: 8 Example: print(d) # Output: {'b': 2, 'c': 3}
Anonymous functions are often used in higher-order functions like map(), filter(), and import tkinter as tk
reduce(). root = tk.Tk() del d # Deletes the entire dictionary
label1 = tk.Label(root, text="Name") 4. clear(): Removes all elements from the dictionary, leaving it empty.
24. Explain math built-in-module with examples? label1.grid(row=0, column=0) d = {'a': 1, 'b': 2, 'c': 3}
Ans: The math module provides a variety of mathematical functions for performing entry1 = tk.Entry(root) d.clear()
mathematical operations on real numbers. entry1.grid(row=0, column=1) print(d) # Output: {}
Some commonly used functions in the math module: label2 = tk.Label(root, text="Age")
1. math.sqrt(x): Returns the square root of x. label2.grid(row=1, column=0) 27. What is Python? What are the benefits of using Python?
import math entry2 = tk.Entry(root) Ans: Python is a high-level, interpreted programming language known for its simplicity and
print(math.sqrt(16)) # Output: 4.0 entry2.grid(row=1, column=1) readability. It supports multiple programming paradigms, including procedural, object-
2. math.pow(x, y): Returns x raised to the power of y. root.mainloop() oriented, and functional programming. Python is dynamically typed and has a vast
print(math.pow(2, 3)) # Output: 8.0 3. place(): The place() method allows absolute positioning of widgets using x and y standard library that makes it suitable for a wide range of applications, including web
3. math.factorial(x): Returns the factorial of x (x!). coordinates. development, data science, machine learning, automation, and more.
print(math.factorial(5)) # Output: 120 Example: Benefits of Using Python:
4. math.pi: Returns the value of π (pi). import tkinter as tk 1. Easy to Learn and Read: Python’s syntax is simple and easy to understand, which
print(math.pi) # Output: 3.141592653589793 root = tk.Tk() makes it an excellent choice for beginners.
5. math.log(x, base): Returns the logarithm of x to the specified base. button = tk.Button(root, text="Click Me") 2. Large Standard Library: Python comes with a rich standard library that includes
print(math.log(10, 2)) # Output: 3.3219280948873626 (log base 2 of 10) button.place(x=50, y=100) modules and packages for various tasks, such as file handling, regular expressions,
6. math.sin(x), math.cos(x), math.tan(x): Trigonometric functions. root.mainloop() and web scraping.
print(math.sin(math.pi/2)) # Output: 1.0 3. Cross-Platform Compatibility: Python code can run on various operating systems
26. Explain functions to delete elements in Dictionary? like Windows, macOS, and Linux without modification.
25. Explain methods for geometry management in tkinter with examples? Ans: Python provides several methods to delete elements from a dictionary: 4. Extensive Support for Third-Party Libraries: Python has a vast ecosystem of third-
Ans: Tkinter provides three geometry management methods to organize widgets in a 1. pop(key): Removes the key and returns its value. Raises a KeyError if the key is not party libraries for data analysis (Pandas, NumPy), machine learning (TensorFlow,
window: found. PyTorch), web frameworks (Django, Flask), and more.
1. pack(): This method packs widgets into the window in a horizontal or vertical d = {'a': 1, 'b': 2, 'c': 3} 5. Interpreted Language: Python is executed line by line, which helps with debugging
fashion. It arranges widgets in blocks before placing them in the parent widget. value = d.pop('b') and testing.
Example: print(d) # Output: {'a': 1, 'c': 3}
import tkinter as tk print(value) # Output: 2 28. Explain frame widget in Tkinter with an example.
2. popitem(): Removes and returns the last inserted key-value pair from the dictionary.
Ans: In Tkinter, a Frame is a container widget used to organize other widgets in a window. It • Scope: Global variables can be accessed from anywhere in the program, while local def multiply(self, a, b):
acts as a placeholder and allows you to group and manage related widgets. variables are confined to the function they are declared in. return a * b
Example: • Lifetime: Global variables exist for the entire program duration, whereas local
import tkinter as tk variables only exist as long as the function executes. def divide(self, a, b):
root = tk.Tk() • Modifying Global Variables: To modify a global variable within a function, the global if b == 0:
root.title("Frame Example") keyword must be used. return "Division by zero is undefined"
# Creating a frame widget return a / b
frame = tk.Frame(root, borderwidth=5, relief="sunken")
Q3. Programs.
frame.pack(pady=10, padx=10) calc = Calculator()
# Adding widgets to the frame 1. Write a python GUI program to display an alert message when a button is pressed. print(calc.add(10, 5)) # 15
label = tk.Label(frame, text="This is inside the frame") Ans: print(calc.subtract(10, 5)) # 5
label.pack() import tkinter as tk print(calc.multiply(10, 5)) # 50
button = tk.Button(frame, text="Click Me") from tkinter import messagebox print(calc.divide(10, 0)) # Division by zero is undefined
button.pack() 4. Write a program to implement concept of queue using list.
root.mainloop() def show_alert(): Ans:
messagebox.showinfo("Alert", "Button Pressed!") queue = []
29. Explain the features of Numpy
Ans: NumPy (Numerical Python) is a fundamental package for numerical computing in root = tk.Tk() # Enqueue
Python. It provides support for large multi-dimensional arrays and matrices, along with a root.title("Alert Message") queue.append(10)
collection of mathematical functions to operate on these arrays efficiently. queue.append(20)
Key Features: button = tk.Button(root, text="Press Me", command=show_alert) queue.append(30)
1. N-Dimensional Array (ndarray): The core feature of NumPy is the ndarray, a button.pack(pady=20)
powerful array object that supports n-dimensional arrays. # Dequeue
2. Broadcasting: NumPy allows for element-wise operations on arrays of different root.mainloop() print(queue.pop(0)) # 10
shapes, through broadcasting. 2. Write a python program to print a table of any number. print(queue.pop(0)) # 20
3. Mathematical Functions: NumPy provides a wide variety of functions for Ans: print(queue) # [30]
mathematical operations, such as linear algebra, random number generation, and num = int(input("Enter a number: ")) 5. Write a Python program to find factors of a given number.
statistical calculations. for i in range(1, 11): Ans:
4. Array Slicing and Indexing: NumPy allows efficient slicing and indexing of arrays, print(f"{num} x {i} = {num * i}") def find_factors(n):
enabling selection and manipulation of array subsets. 3. Write a program to create class to perform basic calculator operations. factors = []
5. Integration with Other Libraries: NumPy is integrated with many other scientific Ans: for i in range(1, n + 1):
libraries such as SciPy, Matplotlib, and Pandas, making it essential for data analysis and class Calculator: if n % i == 0:
visualization. def add(self, a, b): factors.append(i)
6. Performance: NumPy arrays are more efficient in terms of memory and computation
compared to Python lists, making them ideal for large datasets. return a + b return factors

30. Explain difference between local and global variable. def subtract(self, a, b): num = int(input("Enter a number: "))
Ans: Key Differences: return a - b print("Factors:", find_factors(num))
6. Write a Python script to generate Fibonacci termsusing generator function.

Ans: Ans: Ans:


def fibonacci(n): class RepeatString: def remove_odd_index_characters(s):
a, b = 0, 1 def __init__(self, string, n): return ''.join([s[i] for i in range(len(s)) if i % 2 == 0])
for _ in range(n): self.string = string
yield a self.n = n s = input("Enter a string: ")
a, b = b, a + b print("Result:", remove_odd_index_characters(s))
def __mul__(self, other): 13. Write a python program to swap the value of two variables.
n = int(input("How many terms? ")) return self.string * other Ans:
for num in fibonacci(n): # Same as question 8
print(num) string = input("Enter a string: ") a=5
7. Write a Python program to check if a given key already exists in a n = int(input("Enter repetition count: ")) b = 10
dictionary. If Key exists replace with another key/value pair. rs = RepeatString(string, n) a, b = b, a
Ans: print(rs * n) print("a =", a, "b =", b) # a = 10, b = 5
def check_and_replace_key(d, old_key, new_key, new_value): 11. Write python GUI program to generate a random password with upper 14. Write a Python program to display current date and time.
if old_key in d: and lower case letters. Ans:
del d[old_key] Ans: import datetime
d[new_key] = new_value import tkinter as tk print("Current Date and Time:", datetime.datetime.now())
return d import random 15. Define an abstract class shape and its subclass (square / circle). The
import string subclass has an init function which takes an argument (length/radius)
d = {'a': 1, 'b': 2, 'c': 3} Both classes have an area & volume function which can print the area
print(check_and_replace_key(d, 'b', 'd', 4)) # {'a': 1, 'c': 3, 'd': 4} def generate_password(): and volume of shape where the area of shape by default 0.
8. Write a Python program to swap the value of two variables. length = 8 Ans:
Ans: characters = string.ascii_letters from abc import ABC, abstractmethod
a=5 password = ''.join(random.choice(characters) for i in range(length))
b = 10 label.config(text=f"Generated Password: {password}") class Shape(ABC):
a, b = b, a @abstractmethod
print("a =", a, "b =", b) # a = 10, b = 5 root = tk.Tk() def area(self):
9. Write a python script using class to reverse a string word by word? root.title("Password Generator") pass
Ans:
class ReverseString: button = tk.Button(root, text="Generate Password", command=generate_password) @abstractmethod
def reverse(self, s): button.pack(pady=10) def volume(self):
return ' '.join(reversed(s.split())) pass
label = tk.Label(root, text="")
s = input("Enter a string: ") label.pack() class Square(Shape):
rs = ReverseString() def __init__(self, length):
print(rs.reverse(s)) root.mainloop() self.length = length
10. Write a python class to accept a string and number 'n' from user and 12. Write a python program to accept string and remove the characters which
display 'n' repetition of strings by overloading *operator. have odd index values of given string using user defined function. def area(self):
return self.length ** 2 top_element = stack.pop() if stack else '#' however, you can create a new dictionary with selected keys. You can use dictionary
if mapping[char] != top_element: comprehensions or the dict constructor to achieve this.
def volume(self): return False Example:
return 0 # Since a square is 2D else: original_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
stack.append(char) sliced_dict = {k: original_dict[k] for k in ['b', 'c']}
class Circle(Shape): print(sliced_dict) # Output: {'b': 2, 'c': 3}
def __init__(self, radius): return not stack
self.radius = radius 2. Data visualization.
validator = ParenthesesValidator() Ans: Data visualization is the graphical representation of information and data. By using
def area(self): s = input("Enter parentheses string: ") visual elements like charts, graphs, and maps, data visualization tools provide an
return 3.14159 * self.radius ** 2 print("Valid:" if validator.is_valid(s) else "Invalid") accessible way to see and understand trends, outliers, and patterns in data. Popular
18. Write an anonymous function to find area of rectangle. Python libraries for data visualization include Matplotlib, Seaborn, and Plotly.
def volume(self): Ans: Example:
return 0 # Circle is 2D area = lambda length, width: length * width import matplotlib.pyplot as plt
print("Area of Rectangle:", area(5, 10)) data = [1, 2, 3, 4, 5]
s = Square(4) 19. Write Python GUI program to create back ground with changing colors. plt.plot(data)
c = Circle(3) Ans: plt.title("Line Graph")
print(f"Square Area: {s.area()}, Volume: {s.volume()}") import tkinter as tk plt.show()
print(f"Circle Area: {c.area()}, Volume: {c.volume()}") import random
16. Write a Python program to check whether a number is in a given range. 3. Custom Exception.
Ans: def change_color(): Ans: In Python, you can create custom exceptions by defining a new class that inherits
def in_range(n, start, end): colors = ["red", "green", "blue", "yellow", "pink", "orange"] from the built-in Exception class. Custom exceptions allow you to handle specific error
return start <= n <= end root.config(bg=random.choice(colors)) cases in a more meaningful way.
Example:
n = int(input("Enter a number: ")) root = tk.Tk() class CustomError(Exception):
print("In range:", in_range(n, 1, 100)) root.title("Color Changer") pass
17. Write a Python class to find the validity of a string of parentheses, '(', ')', root.geometry("300x300") def do_something(x):
'{' , '}', '[' , ']'. These brackets must be closed in the correct order for if x < 0:
example "( )" and "( ) [ ] { }" are valid but "[ )", "({[)]" and "{{{" are button = tk.Button(root, text="Change Background Color", command=change_color) raise CustomError("Negative value not allowed.")
invalid. button.pack(pady=50) return x
Ans: try:
class ParenthesesValidator: root.mainloop() do_something(-1)
def is_valid(self, s): except CustomError as e:
stack = [] Q4. Short Notes. print(e)
mapping = {')': '(', '}': '{', ']': '['} 1. Slicing Dictionaries.
Ans: Slicing dictionaries in Python allows you to retrieve a subset of key-value pairs based 4. Raise statement
for char in s: on specific keys. Unlike lists and tuples, dictionaries do not support slicing by index;
if char in mapping:

Ans: The raise statement is used to trigger an exception in Python. You can use it to raise my_tuple = (1, 2, 3, 4)
built-in exceptions or your custom exceptions. Raising exceptions is useful for enforcing print(my_tuple[1])
certain conditions in your code.
Example:
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or older.")
return "Age is valid."
try:
check_age(15)
except ValueError as e:
print(e)

5. Package
Ans: In Python, a package is a way of organizing related modules into a single directory
hierarchy. A package typically contains an __init__.py file that defines the package's
interface and can also include sub-packages and modules. Packages help in organizing
code and preventing naming conflicts.

6. Assertion
Ans: An assertion is a statement in Python that tests a condition. If the condition evaluates
to True, the program continues executing; if it evaluates to False, an AssertionError is
raised. Assertions are mainly used for debugging purposes and to check for conditions that
must be true for the program to run correctly.
Example:
def divide(a, b):
assert b != 0, "Denominator cannot be zero!"
return a / b
try:
divide(5, 0)
except AssertionError as e:
print(e)

7. Tuple
Ans: A tuple is an immutable sequence type in Python, which means that once a tuple is
created, its contents cannot be changed. Tuples can hold a collection of items, and they
are defined using parentheses ().
Example:

You might also like