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

Python Question Bank Complete 100 Question

Uploaded by

naaziya707
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
123 views

Python Question Bank Complete 100 Question

Uploaded by

naaziya707
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Unit 1: Introduction to Python

2 Marks

1) What are the key features of Python?


• Easy to read, interpreted, dynamically typed, object-oriented, large libraries, cross-platform,
community-supported.

2) List any four string methods in Python?


.upper(), .lower(), .replace(), .strip().

3) What are the properties of a Python list?


• Mutable, ordered, allows duplicates, heterogeneous.

4) Explain the difference between a tuple and a list in Python?


• Lists are mutable and use `[]`; tuples are immutable and use `()`.

5) What is the use of a pass and break statement?


• Placeholder, does nothing. break : Exits loop immediately.

6) How can you access a value in a dictionary? Provide an example?


• my_dict = {"name": "Alice"}
print(my_dict["name"]) # Alice

7) List any two types of functions in Python and give a brief description of each?
• Built-in :- Predefined, e.g., `print()`.
• User-defined :- Created by user, e.g., `def my_func()`.

8) What is string slicing in Python? Provide an example?


• Extract part of string. `text = "Hello"; print(text[0:4]) # Hell`

9) List any special operators in Python and give a description of each?

• in, not in :- Check membership.


• is, is not :- Check identity.

10) Explain the concept of local and global variables with an example?
• Local is inside functions, global is outside.

11) What is the difference between append () and extend () methods in Python lists?
• append() :- Adds single item.
• extend() :- Adds multiple items.

12) How do you create a function in Python? Write a simple example of a function that
adds two
numbers.
• def add(a, b):
return a + b

4 Marks

1. What is Python? What are the benefits of using Python?


• Python is a high-level, versatile programming language known for simplicity and readability.
• Benefits:- include easy syntax, extensive libraries, cross-platform support, and
suitability for rapid development.

2. Explain function arguments in detail.


• Positional :- Values matched by position.
• Keyword :- Values matched by parameter name.
• Default :- Parameters with a default value.
• Arbitrary :- `*args` (for tuples), `**kwargs` (for dictionaries) handle variable numbers of
arguments.

3. Describe string manipulation techniques in Python with examples.


• Concatenation :- `+` operator to join strings (`"Hello" + "World"`).
• Slicing :- Extract parts using `[start:end]`.
• Methods :- `.upper()`, `.lower()`, `.replace()`, `.strip()`, etc.
• Example :-
text = "Python"
print(text.upper()) # Output: "PYTHON"
print(text[1:4]) # Output: "yth"

4. What is a dictionary? Explain three built-in dictionary functions with examples.


• A collection of key-value pairs.
• Examples :-
• ‘len()` - finds dictionary length: `len(my_dict)`.
• `keys()` - returns all keys: `my_dict.keys()`.
• `get()` - fetches a value by key with a default: `my_dict.get("key", "default")`.

5. Write an anonymous function to find the area of a rectangle given its length and width.
• area = lambda length, width: length * width
print(area(5, 3)) # Output: 15

6. Explain the use of control statements (break, continue, pass) with examples.
• break : Exits the loop.
for i in range(5):
if i == 3:
break
print(i)
• continue : Skips to the next iteration.
for i in range(5):
if i == 3:
continue
print(i)
• pass : Placeholder that does nothing.
for i in range(5):
if i == 3:
pass

7. How do you access and manipulate elements in a list? Provide examples of common
list operations.
• Access :- my_list[index].
• Modify :- my_list[index] = new_value.
• Append :- my_list.append(value).
• Remove :- my_list.remove(value).
• Example :-
my_list = [1, 2, 3]
my_list.append(4) # [1, 2, 3, 4]
my_list[0] = 10 # [10, 2, 3, 4]

8. What are the properties of dictionaries in Python? How do you access and modify their
values?
• Mutable, unordered, key-value pairs.
• Access/Modify
my_dict = {"name": "Alice"}
print(my_dict["name"]) # Access
my_dict["name"] = "Bob" # Modify

9. Define nested loops in Python and provide an example of their usage.


Loops inside loops, often used for multi-dimensional data.
for i in range(2):
for j in range(3):
print(i, j)

10. What are the differences between global and local variables in Python? Provide
examples
• Local : Defined inside a function; can’t be accessed outside.
• Global : Defined outside functions; accessible anywhere.
x = 10 # Global
def func():
x = 5 # Local
print(x) # Output: 5

func()
print(x) # Output: 10

11. Explain string slicing in Python with examples.


• Extracts parts of strings using `[start:end:step]`.
• Example :-
text = "Hello, World!"
print(text[0:5]) # Output: "Hello"
print(text[::2]) # Output: "Hlo ol!"

12. What is the significance of the if-else statement? Provide an example demonstrating
its use.
• The `if-else` statement allows conditional execution of code.
• Example :-
num = 10
if num > 5:
print("Greater than 5")
else:
print("5 or less")

13. Describe the different types of functions in Python and give examples for each.
• Built-in : Predefined functions (e.g., `len()`, `print()`).
• User-defined : Functions created with `def` (e.g., `def my_func(): pass`).
• Lambda : Anonymous, single-expression functions (e.g., `lambda x: x + 1`).

14. How do you create and use a tuple in Python? Illustrate with examples.
Tuples are immutable, defined with `()` and can hold multiple items.
my_tuple = (1, 2, 3)
print(my_tuple[1]) # Output: 2

15. How do you create and use lists and tuples in Python? Provide examples
• List : Mutable, created with `[]`.
my_list = [1, 2, 3]
my_list.append(4) # [1, 2, 3, 4]
• Tuple : Immutable, created with `()`.
my_tuple = (1, 2, 3)
# Access element
print(my_tuple[1])
4 Marks

1. Write a Python program to accept a string and remove the characters which have odd
index values of the given string using a user-defined function.

def remove_odd_index(s):
return ''.join([s[i] for i in range(len(s)) if i % 2 == 0])

print(remove_odd_index("example"))
# Output: "eape”

2. Write a Python program to swap the value of two variables.


x, y = 5, 10
x, y = y, x
print(x, y) # Output: 10 5

3. Write a Python program to find factors of a given number.


def factors(n):
return [i for i in range(1, n + 1) if n % i == 0]
print(factors(12)) # Output: [1, 2, 3, 4, 6, 12]

4. Write a Python program to count the number of vowels in a given string.


def count_vowels(s):
return sum(1 for char in s if char.lower() in 'aeiou')
print(count_vowels("hello")) # Output: 2

5. Write a Python program that accepts a list of numbers and returns a new list
containing only the even numbers.
def filter_even(numbers):
return [num for num in numbers if num % 2 == 0]

print(filter_even([1, 2, 3, 4])) # Output: [2, 4]

6. Write a Python program to demonstrate the use of 'break' and 'continue' statement in a
loop.
for i in range(5):
if i == 3:
break
print(i) # Output: 0 1 2

for i in range(5):
if i == 3:
continue
print(i) # Output: 0 1 2 4

7. Write a Python function that takes two lists and returns a dictionary with elements
from the first list as keys and elements from the second list as values.
def lists_to_dict(keys, values):
return dict(zip(keys, values))
print(lists_to_dict(['a', 'b'], [1, 2]))
# Output: {'a': 1, 'b': 2}

8. Write a Python program to check if a string is a palindrome.


def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("madam")) #True

9. Write a Python program to find the largest and smallest numbers in a list.
def min_max(numbers):
return min(numbers), max(numbers)
print(min_max([1, 2, 3, 4])) # (1, 4)

10. Write a Python program to merge two dictionaries into one.


dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

11. Write a Python function to calculate the factorial of a number using recursion.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

print(factorial(5)) # Output: 120

12. Write a Python program to demonstrate nested if-else statements.


num = 10
if num > 0:
if num % 2 == 0:
print("Positive and even")
else:
print("Positive and odd")
else:
print("Non-positive")

13. Write a Python program to reverse a given string.


def reverse_string(s):
return s[::-1]

print(reverse_string("hello")) # Output: "olleh"

14. Write a Python program that accepts a list of integers and returns the sum of all the
odd numbers in that list.
def sum_odd(numbers):
return sum(num for num in numbers if num % 2 != 0)

print(sum_odd([1,2, 3, 4, 5]))# Output: 9

15. Write a Python program that use while loop to print the numbers from 1 to 10.
i=1
while i <= 10:
print(i)
i += 1

16. Write a Python function to check if a number is prime.

def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

print(is_prime(7)) # Output: True

17. Write a Python program to add two numbers using an anonymous function. The
program should take two numbers as input and print their sum.
add = lambda a, b: a + b
print(add(3, 5)) # Output: 8

18. Write a Python program to filter out even numbers from a list using an anonymous
function. The program should return a new list containing only the odd numbers.

numbers = [1, 2, 3, 4, 5, 6]
odd_numbers = list(filter(lambda x: x % 2 != 0, numbers))
print(odd_numbers) # Output: [1, 3, 5]

Unit 2: Modules and Packages


2 Marks

1. Write any three functions of Math module.


• math.sqrt(x): Returns the square root of `x`.
• math.pow(x, y): Returns `x` raised to the power `y`.
• math.floor(x): Returns the largest integer less than or equal to `x`.

2. What is the use of random () in a random module?


• Generates a random float number between 0.0 (inclusive) and 1.0 (exclusive).

3. Name any five built in modules in Python.


• os
• sys
• math
• datetime
• random
4. Give two functions from Calendar module.
• calendar.isleap(year): Checks if the specified year is a leap year.
• calendar.month(year, month): Returns a string representation of the specified month and
year.

5. Define package and give example of built in packages.


• A collection of modules organized in a directory with an `__init__.py` file.
• Example of built-in packages**: json, collections, urllib.

4 Marks

1. Explain user defined functions with example


• Functions created by the user to perform specific tasks. Defined with the `def` keyword and
can include parameters.

def greet(name):
return f"Hello, {name}!"

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

2. Explain the Time module with at least four functions


• Used to work with time-related functions.
• time.time(): Returns the current time in seconds since the epoch.
• time.sleep(seconds): Pauses execution for the specified number of seconds.
• time.ctime(): Converts a time expressed in seconds to a readable string.
• time.localtime(): Returns the current local time as a structured time tuple.

3. Write steps for creating user defined package


• Create a new directory for the package.
• Add an `__init__.py` file inside the directory (can be empty, but it makes the directory a
package).
• Add other Python modules (files) within the directory.
• Import the package in your program using `import package_name`.

4. Explain Sys module in details


Provides functions and variables to manipulate the Python runtime environment.
• sys.argv : List of command-line arguments passed to a script.
• sys.exit() : Exits the program.
• sys.path : List of directories the interpreter searches for modules.
• sys.version : Returns the version of the Python interpreter.

5. Write three different ways to import modules.


• Standard import :- `import math`
• Import specific functions :- `from math import sqrt, pow`
• Import with an alias :- `import math as m`

Unit 3: Classes Objects and Inheritance


2 Marks

1. What is class variables?


• Variables that are shared among all instances of a class.
• They are defined within the class but outside any methods.
• All objects of the class can access and modify them.

class MyClass:
class_variable = 0 # This is a class variable

def __init__(self, instance_var):


self.instance_var = instance_var

obj1 = MyClass(1)
obj2 = MyClass(2)
print(MyClass.class_variable) # Output: 0
2. How to create class and object in python?
• Define a class using the `class` keyword.
• Create an object by calling the class as if it were a function.

class Dog:
def __init__(self, name):
self.name = name

my_dog = Dog("Buddy") # Creating an object


print(my_dog.name) # Output: "Buddy"

3. What is the syntax of class?


class ClassName:
# Class variables

def __init__(self, parameters):


# Instance variables

def method_name(self):
# Method body

3 Marks (Short Note)

1. Class Method

• A method bound to the class, not instances, defined with `@classmethod` and takes `cls` as
the first parameter.
• Example:
class Dog:
species = "Canis familiaris"
@classmethod
def get_species(cls):
return cls.species
print(Dog.get_species()) # Output: Canis familiaris

2. Benefits of inheritance
• Code Reusability : Reuses code from the parent class.
• Extensibility : Child classes can extend or override parent class behavior.
• Maintainability : Changes in the parent class reflect in child classes.
• Hierarchical Classification : Represents relationships between classes.
• Example:
class Animal:
def speak(self):
return "Animal sound"

class Dog(Animal):
def speak(self):
return "Bark"

dog = Dog()
print(dog.speak()) # Output: Bark

3. Polymorphism
• Allows different classes to use the same method name, with each class providing its own
implementation.
• This enables flexible and dynamic behavior.
• Example:
class Animal:
def speak(self):
return "Animal sound"

class Dog(Animal):
def speak(self):
return "Bark"

class Cat(Animal):
def speak(self):
return "Meow"

def make_animal_speak(animal):
print(animal.speak())

dog = Dog()
cat = Cat()
make_animal_speak(dog) # Output: Bark
make_animal_speak(cat) # Output: Meow

4 Marks

1. Explain IS-A relationship and HAS-A Relationship with example.


• IS-A Relationship :- Indicates inheritance, where a subclass is a specific type of the parent
class.
• Example: A `Dog` **is a** `Animal`.
class Animal:
pass
class Dog(Animal):
pass
• HAS-A Relationship : Represents composition, where one class contains an instance of
another class.
• Example: A `Car` **has a** `Engine`.
class Engine:
pass

class Car:
def __init__(self):
self.engine = Engine()

2. Explain inheritance in brief with its syntax.


• Inheritance allows a class (child) to inherit attributes and methods from another class (parent).
• The child class can extend or override functionality.
• Syntax :
class Parent:
# Parent class code

class Child(Parent):
# Child class can add or override methods and properties
• Example:
class Animal:
def speak(self):
return "Animal sound"

class Dog(Animal):
def speak(self):
return "Bark"

3. What is method overloading?


• Method overloading refers to the ability to define multiple methods with the same name but
different arguments.
• Python doesn’t support traditional method overloading, but it can be achieved through default
arguments or variable-length arguments.
• Example:
class Calculator:
def add(self, a, b=0):
return a + b

calc = Calculator()
print(calc.add(5)) # Output: 5
print(calc.add(5, 3)) # Output: 8
4. How does python static method works?
• A static method is a method bound to the class rather than its instances.
• It is defined using the `@staticmethod` decorator and doesn't take `self` or `cls` as the first
argument.
• Example:
class Math:
@staticmethod
def add(a, b):
return a + b

print(Math.add(5, 3)) # Output: 8

5. Explain function overloading with example.


• Function overloading allows defining multiple functions with the same name but different
signatures (number/type of arguments).
• Python doesn’t support function overloading directly, but similar behavior can be achieved
using default arguments or `*args`.
• Example:

class Printer:
def print(self, text=None):
if text is not None:
print(text)
else:
print("No text to print")

printer = Printer()
printer.print("Hello") # Output: Hello
printer.print() # Output: No text to print

6. What does super() do in python?


• super()` is used to call a method from the parent class, typically in a subclass to extend or
override functionality.
• Example:
class Animal:
def speak(self):
return "Animal sound"

class Dog(Animal):
def speak(self):
return super().speak() + " and Bark"

dog = Dog()
print(dog.speak()) # Output: Animal sound and Bark
4 Marks (Programs)

1. Write the python script using class to reverse the string word by word.
class StringReversal:
def __init__(self, string):
self.string = string

def reverse(self):
return ' '.join(self.string.split()[::-1])

# Usage:
print(StringReversal("Hello World").reverse()) # Output: World Hello

2. Write a program of python to create a class circle and calculate area and
circumference of circle
(Use parameterized constructor).
import math

class Circle:
def __init__(self, radius):
self.radius = radius

def area(self):
return math.pi * self.radius ** 2

def circumference(self):
return 2 * math.pi * self.radius

# Usage:
circle = Circle(5)
print(circle.area(), circle.circumference())
```

3. Write a python program to create class which perform basic calculator operations.
class Calculator:
def add(self, a, b): return a + b
def subtract(self, a, b): return a - b
def multiply(self, a, b): return a * b
def divide(self, a, b): return a / b if b != 0 else "Error"

# Usage:
calc = Calculator()
print(calc.add(10, 5), calc.subtract(10, 5), calc.multiply(10, 5), calc.divide(10, 5))
Unit 4: Exception Handling
2 Marks

1. Differentiate between error and exception.


• Error : Serious issues that terminate the program (e.g., syntax errors).
• Exception : Events that can be caught and handled (e.g., division by zero).

2. Write the syntax of exception.

try:
# code
except ExceptionType as e:
# handle exception

3. What is the use of try - finally block?


• The `finally` block executes after `try` block, whether an exception occurs or not, typically for
cleanup.

4. Justify more than one except statement can a try-except block have.
• You can have multiple `except` blocks to handle different types of exceptions separately:

try:
# code
except TypeError:
# handle TypeError
except ValueError:
# handle ValueError

5. Write and explain syntax of Raise Statement.


raise Exception("Error message")

6. Write syntax of Assert Statement

assert condition, "Error message"

4 Marks

1. Try-Except statement
• The `try-except` statement handles exceptions in Python.
• The code inside the `try` block is executed, and if an exception occurs, the `except` block
handles it.
try:
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Cannot divide by zero!")

2. Raise statement.
• The `raise` statement is used to explicitly raise an exception, either new or re-raising an
existing one.

# Raising a specific exception


raise ValueError("This is a custom error message")

# Re-raising the current exception


try:
1/0
except ZeroDivisionError as e:
print(f"An error occurred: {e}")
raise # Re-raises the ZeroDivisionError

3. Custom Exception
• A custom exception is created by defining a new class that inherits from the built-in `Exception`
class.

class MyCustomError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)

# Using the custom exception


try:
raise MyCustomError("Something went wrong in my program!")
except MyCustomError as e:
print(f"Caught custom exception: {e}")

Unit 5: GUI Programming


2 Marks

1. What is the purpose of Tkinter?


• Tkinter is the standard GUI (Graphical User Interface) library in Python.
• It allows you to create desktop applications with a graphical interface, providing tools to build
windows, buttons, labels, text fields, and more.

2. List out Geometry Management methods.


• These methods manage the layout of widgets in a window:
• pack() :- Organizes widgets in blocks (top, bottom, left, right, etc.).
• grid() :- Organizes widgets in a grid-like structure (rows and columns).
• place() :- Places widgets at a specific position (using x, y coordinates).

3. Name the different widgets available in Tkinter.


• Some common widgets in Tkinter include:
• Label : Displays text or images.
• Button : A clickable button.
• Entry : A single-line text input field.
• Text : A multi-line text input field.
• Checkbutton : A check box.
• Radiobutton : A radio button.
• Listbox : A list of items.
• Canvas : A drawing area for shapes, images, etc.
• Scrollbar : Provides a scrollbar for widgets like `Text` or `Listbox`.
• Frame : A container for other widgets.

4 Marks

1. Explain any three widgets in tkinter in brief.


• Label Widget : A `Label` widget is used to display text or images. It is non-interactive and
typically used for showing information to the user.
• Example:

from tkinter import *


root = Tk()
label = Label(root, text="Hello, Tkinter!")
label.pack()
root.mainloop()

• Button Widget : A `Button` widget is used to create clickable buttons in the GUI.
• It can trigger actions when clicked.
• Example:
from tkinter import *
def on_click():
print("Button clicked!")

root = Tk()
button = Button(root, text="Click Me", command=on_click)
button.pack()
root.mainloop()

• Entry Widget : An `Entry` widget is used for text input in a single-line field. It allows users to
enter data.
• Example:
from tkinter import *
def show_entry():
print(entry.get())

root = Tk()
entry = Entry(root)
entry.pack()
button = Button(root, text="Submit", command=show_entry)
button.pack()
root.mainloop()

2. Explain methods for Geometry Management in tkinter with example.


• Geometry management in Tkinter helps to organize the placement of widgets in a window.
• The three main methods are:
• pack() : Packs widgets in the parent widget (typically vertically or horizontally).
• Example:
from tkinter import *
root = Tk()
label1 = Label(root, text="Label 1")
label1.pack(side=TOP)
label2 = Label(root, text="Label 2")
label2.pack(side=LEFT)
root.mainloop()

• grid() : Arranges widgets in a grid layout, with rows and columns.


• Example:
from tkinter import *
root = Tk()
label1 = Label(root, text="Label 1")
label1.grid(row=0, column=0)
label2 = Label(root, text="Label 2")
label2.grid(row=1, column=1)
root.mainloop()
• place() : Places widgets at an absolute position (x, y).
• Example:
from tkinter import *
root = Tk()
label = Label(root, text="Positioned Label")
label.place(x=50, y=50)
root.mainloop()

3. Explain widget resizing with an example.


• Widget resizing can be done by using the `width` and `height` parameters or methods like
`pack()` or `grid()` with `fill` and `expand` options.
•| For resizing a window or widget dynamically, use the `pack()` or `grid()` options.
• Example of resizing a widget:
from tkinter import *
root = Tk()
label = Label(root, text="Resizable Label", width=20, height=5)
label.pack(fill=BOTH, expand=True)
root.mainloop()

4. Explain label widget in tkinter with an example.


• The `Label` widget is used to display text or images. It's typically used to show static
information.
• Example:
from tkinter import *
root = Tk()
label = Label(root, text="This is a label widget", font=("Arial", 14))
label.pack()
root.mainloop()

5. Explain button widget with an example.


• The `Button` widget is used to create interactive buttons.
• The button can perform an action when clicked, defined using the `command` parameter.
• Example:
from tkinter import *
def on_button_click():
print("Button clicked!")

root = Tk()
button = Button(root, text="Click Me", command=on_button_click)
button.pack()
root.mainloop()

6. Explain entry widget in tkinter with an example.


• The `Entry` widget allows users to input text in a single-line field.
• Example:
from tkinter import *
def show_input():
user_input = entry.get()
print("User input:", user_input)

root = Tk()
entry = Entry(root)
entry.pack()
button = Button(root, text="Submit", command=show_input)
button.pack()
root.mainloop()

7. Explain frame widget in tkinter with an example.


• A `Frame` widget is a container for grouping other widgets together.
• It helps in organizing the layout of complex interfaces.
• Example:
from tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()

label = Label(frame, text="Label inside Frame")


label.pack()

button = Button(frame, text="Button inside Frame")


button.pack()

root.mainloop()

8. Explain the following with proper syntax and example:


a) entry. delete. b) entry. insert
• entry.delete()
• The `delete()` method is used to delete text from an `Entry` widget between the specified
indices.
• Syntax:
entry.delete(start, end)
• Example:
from tkinter import *
root = Tk()
entry = Entry(root)
entry.pack()
entry.insert(0, "Hello")
entry.delete(0, 3) # Deletes "Hel"
root.mainloop()

b) `entry.insert()`
• The `insert()` method is used to insert text at a specific position in the `Entry` widget.
• Syntax:
entry.insert(index, text)
• Example:
from tkinter import *
root = Tk()
entry = Entry(root)
entry.pack()
entry.insert(0, "Hello World!")
root.mainloop()

Marks (Programs)

1. Write Python GUI program to create back ground with changing colors.
import tkinter as tk
import random

def change_color():
root.config(bg=random.choice(['red', 'green', 'blue', 'yellow', 'purple']))
root.after(1000, change_color)

root = tk.Tk()
root.geometry("400x400")
change_color()
root.mainloop()

2. Write Python GUI program to accept a decimal number and convert and display it to
binary, octal and hexadecimal.

import tkinter as tk

def convert():
num = int(entry.get())
result = f"Binary: {bin(num)[2:]}\nOctal: {oct(num)[2:]}\nHex: {hex(num)[2:].upper()}"
result_label.config(text=result)

root = tk.Tk()
entry = tk.Entry(root)
entry.pack()
tk.Button(root, text="Convert", command=convert).pack()
result_label = tk.Label(root, text="")
result_label.pack()
root.mainloop()

3. Write Python GUI program to accept dimension of a cylinder and display the surface
area and the volume of cylinder.

import tkinter as tk
import math

def calculate():
r = float(radius_entry.get())
h = float(height_entry.get())
area = 2 * math.pi * r * (r + h)
volume = math.pi * r**2 * h
result_label.config(text=f"Area: {area:.2f}\nVolume: {volume:.2f}")

root = tk.Tk()
radius_entry = tk.Entry(root)
radius_entry.pack()
height_entry = tk.Entry(root)
height_entry.pack()
tk.Button(root, text="Calculate", command=calculate).pack()
result_label = tk.Label(root, text="")
result_label.pack()
root.mainloop()

Unit 6: Python Libraries


2 Marks

1. What are the advantages of Pandas?


• Efficient data manipulation and analysis.
• Handles large datasets and supports various data types.

2. State the features of Keras.


• Easy-to-use, modular API for building neural networks.
• Supports both CPU and GPU for training.

3. What is Sea born?


• Seaborn is a Python library for statistical data visualization based on Matplotlib.

4. Give two features of Pandas in Python


• DataFrame for structured data.
• Tools for handling missing data.

4 Marks

1. Define Pandas? Explain features of pandas in Python.


• Pandas is an open-source Python library used for data manipulation and analysis.
• It provides powerful tools like DataFrames and Series to work with structured data.
• Features of Pandas :-
• DataFrame : A 2-dimensional labeled data structure for handling data in tables.
• Handling Missing Data : Functions for detecting and filling or dropping missing values.
• Data Alignment : Automatically aligns data for different sources.
• Groupby : Provides functionality for grouping data and performing operations on them.

2. What is Data Visualization? List any 4 data visualization libraries.


• Data visualization is the graphical representation of data to identify patterns, trends, and
insights.
• It turns raw data into visual formats like charts, graphs, and plots.
• 4 Data Visualization Libraries :-
- Matplotlib
- Seaborn
- Plotly
- Bokeh

3. What is Tensor Flow? Explain features of Tensor Flow.


• TensorFlow is an open-source machine learning framework developed by Google.
• It is used for building and training deep learning models.
• Features of TensorFlow :-
• Flexibility : Supports a variety of machine learning models, including deep learning.
• Scalability : Can scale to large datasets and distributed systems.
• Cross-platform : Runs on CPUs, GPUs, and mobile devices.
• Ecosystem : Provides a wide range of tools like TensorFlow Lite, TensorFlow Hub, and
TensorFlow.js.

4. Difference between Python list and Numpy array


• Python List : A general-purpose container for different data types and sizes, can store mixed
data types, and is slower for numerical operations.
• Numpy Array : A specialized array for numerical data, supports element-wise operations, and
is faster and more memory-efficient than lists.

You might also like