0% found this document useful (0 votes)
6 views36 pages

Python Programming Examples and Solutions

The document contains a series of Python programming tasks, including generating Fibonacci terms, creating a basic calculator, validating parentheses, and implementing GUI applications. It covers various programming concepts such as functions, classes, operator overloading, and event handling in GUI. Additionally, it highlights the benefits of Python as a programming language, including its readability, extensive libraries, and community support.

Uploaded by

tamahesh411
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)
6 views36 pages

Python Programming Examples and Solutions

The document contains a series of Python programming tasks, including generating Fibonacci terms, creating a basic calculator, validating parentheses, and implementing GUI applications. It covers various programming concepts such as functions, classes, operator overloading, and event handling in GUI. Additionally, it highlights the benefits of Python as a programming language, including its readability, extensive libraries, and community support.

Uploaded by

tamahesh411
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

1.

Write a Python script to generate # Enter number: 15


Fibonacci terms using generator function. # Enter range start: 10
def fibonacci(limit): # Enter range end: 20
a, b = 0, 1 # In range: True
for _ in range(limit): 5. Write a Python program to print the
yield a table of any number.
a, b = b, a + b def print_table(n):
n = int(input("Enter number of terms: ")) for i in range(1, 11):
print("Fibonacci series:", list(fibonacci(n))) print(f"{n} × {i} = {n*i}")
# Output: num = int(input("Enter number for table: "))
# Enter number of terms: 8 print_table(num)
# Fibonacci series: [0, 1, 1, 2, 3, 5, 8, 13] # Output:
2. Write an anonymous function to find the # Enter number for table: 7
area of a rectangle. 6. Write a Python program that accepts a
area = lambda l, w: l * w list of numbers and returns only even
length = float(input("Enter length: ")) numbers.
width = float(input("Enter width: ")) def get_evens(numbers):
print("Area:", area(length, width)) return [x for x in numbers if x % 2 == 0]
# Output: user_input = input("Enter numbers separated
# Enter length: 5 by space: ")
# Enter width: 3 nums = list(map(int, user_input.split()))
# Area: 15.0 print("Even numbers:", get_evens(nums))
3. Write a Python program to check # Output:
whether a string is a palindrome. # Enter numbers separated by space: 1 2 3 4 5
def is_palindrome(s): 6 7 8 9 10
s = [Link]().replace(" ", "") # Even numbers: [2, 4, 6, 8, 10]
return s == s[::-1] 8. Write a class to reverse a string word by
string = input("Enter a string: ") word.
print(f"Palindrome: class StringReverser:
{is_palindrome(string)}") def __init__(self, text):
# Output: [Link] = text
# Enter a string: radar def reverse_words(self):
# Palindrome: True return ' '.join(reversed([Link]()))
4. Write a Python program to check if a s = input("Enter string: ")
number is in a given range. reverser = StringReverser(s)
def in_range(num, start, end): print("Reversed:", reverser.reverse_words())
return start <= num <= end # Output:
number = float(input("Enter number: ")) # Enter string: Hello World Python
r_start = float(input("Enter range start: ")) Programming
r_end = float(input("Enter range end: ")) # Reversed: Programming Python World
print(f"In range: {in_range(number, r_start, Hello
r_end)}")
# Output:

1
7. Write a class Circle with a for char in [Link]:
parameterized constructor to compute if char in '([{':
area and circumference. [Link](char)
import math elif char in ')]}':
class Circle: if not stack or stack[-1] !=
def __init__(self, radius): mapping[char]:
[Link] = radius return False
def area(self): [Link]()
return [Link] * [Link] ** 2 return len(stack) == 0
def circumference(self): expr = input("Enter expression: ")
return 2 * [Link] * [Link] pv = ParenthesesValidator(expr)
r = float(input("Enter radius: ")) print("Valid:", pv.is_valid())
c = Circle(r) # Output:
print(f"Area: {[Link]():.2f}") # Enter expression: ({[]})
print(f"Circumference: # Valid: True
{[Link]():.2f}") 11. Write a class to create basic calculator
# Output: operations.
# Enter radius: 5 class Calculator:
# Area: 78.54 def add(self, a, b): return a + b
# Circumference: 31.42 def subtract(self, a, b): return a - b
9. Write a class that accepts a string and def multiply(self, a, b): return a * b
number n, and overload * operator. def divide(self, a, b): return a / b if b != 0
class StringMultiplier: else "Error"
def __init__(self, text): calc = Calculator()
[Link] = text a = float(input("Enter first number: "))
def __mul__(self, n): b = float(input("Enter second number: "))
return [Link] * n print(f"{a} + {b} = {[Link](a, b)}")
text = input("Enter string: ") print(f"{a} × {b} = {[Link](a, b)}")
n = int(input("Enter repeat count: ")) # Output:
sm = StringMultiplier(text) # Enter first number: 12
print("Result:", sm * n) # Enter second number: 5
# Output: # 12.0 + 5.0 = 17.0
# Enter string: Hi # 12.0 × 5.0 = 60.0
# Enter repeat count: 5 19. Write a Python program to remove
# Result: HiHiHiHiHi characters at odd index values in a string.
10. Write a class to find the validity of a def remove_odd_index_chars(s):
string of parentheses () [] {}. return s[::2]
class ParenthesesValidator: text = input("Enter string: ")
def __init__(self, expr): print("After removal:",
[Link] = expr remove_odd_index_chars(text))
def is_valid(self): # Output:
stack = [] # Enter string: abcdefghij
mapping = {')': '(', ']': '[', '}': '{'} # After removal: acegi

2
12. Define an abstract class shape and its [Link]("300x100")
subclasses; implement area and volume. [Link](root, text="Generate Password",
from abc import ABC, abstractmethod command=generate_password).pack(pady=1
import math 0)
class Shape(ABC): result_label = [Link](root, text="")
@abstractmethod result_label.pack()
def area(self): pass [Link]()
@abstractmethod # Output: [GUI window with button, clicking
def volume(self): pass shows random password like
class Circle(Shape): "aB3kL9mQ2xZ8"]
def __init__(self, radius):
[Link] = radius 14. Write a GUI program to display an
def area(self): return [Link] * [Link] alert message when a button is pressed.
** 2 import tkinter as tk
def volume(self): return 0 from tkinter import messagebox
class Rectangle(Shape): def show_alert():
def __init__(self, length, width): [Link]("Alert", "Button
[Link] = length was pressed!")
[Link] = width root = [Link]()
def area(self): return [Link] * [Link]("Alert Demo")
[Link] [Link]("200x100")
def volume(self): return 0 [Link](root, text="Click Me",
r = float(input("Enter circle radius: ")) command=show_alert).pack(pady=40)
c = Circle(r) [Link]()
print("Circle area:", f"{[Link]():.2f}") # Output: [GUI with button, clicking shows
# Output: alert popup]
# Enter circle radius: 7 15. Write a GUI program to create a
# Circle area: 153.94 background with changing colors.
import tkinter as tk
13. Write a GUI program to generate a import random
random password with upper/lower case def change_color():
letters. colors = ['red', 'green', 'blue', 'yellow',
import tkinter as tk 'pink', 'orange']
import random [Link](bg=[Link](colors))
import string root = [Link]()
def generate_password(): [Link]("Color Changer")
chars = string.ascii_letters + [Link] [Link]("200x100")
password = ''.join([Link](chars) [Link](root, text="Change Color",
for _ in range(12)) command=change_color).pack(pady=40)
result_label.config(text=f"Password: [Link]()
{password}") # Output: [GUI with button that changes
root = [Link]() background color randomly]
[Link]("Password Generator")

3
16. Write a GUI program to accept the print("Original:", my_dict)
dimensions of a cylinder and display old_k = input("Enter key to replace: ")
surface area and volume. new_k = input("Enter new key: ")
import tkinter as tk if replace_key(my_dict, old_k, new_k):
import math print("Key replaced successfully")
def calculate(): else:
try: print("Key not found")
r = float(radius_entry.get()) print("Updated dictionary:", my_dict)
h = float(height_entry.get()) # Output:
area = 2 * [Link] * r * (r + h) # Original: {'a': 1, 'b': 2, 'c': 3}
volume = [Link] * r * r * h # Enter key to replace: b
result_label.config(text=f"Area: # Enter new key: new_b
{area:.2f}\nVolume: {volume:.2f}") # Key replaced successfully
except: # Updated dictionary: {'a': 1, 'new_b': 2, 'c':
result_label.config(text="Invalid input") 3}
root = [Link]()
[Link]("Cylinder Calculator") 18. Write a Python program to implement
[Link]("250x200") a queue using list.
[Link](root, text="Radius:").pack() class Queue:
radius_entry = [Link](root) def __init__(self):
radius_entry.pack() [Link] = []
[Link](root, text="Height:").pack() def enqueue(self, item):
height_entry = [Link](root) [Link](item)
height_entry.pack() def dequeue(self):
[Link](root, text="Calculate", return [Link](0) if [Link] else
command=calculate).pack(pady=10) "Queue empty"
result_label = [Link](root, text="") def is_empty(self):
result_label.pack() return len([Link]) == 0
[Link]() def size(self):
# Output: [GUI where entering radius=3, return len([Link])
height=5 shows "Area: 150.80\nVolume: q = Queue()
141.37"] [Link](10)
[Link](20)
17. Write a program to check if a key exists [Link](30)
in a dictionary and replace it. print("Queue size:", [Link]())
def replace_key(dictionary, old_key, print("Dequeued:", [Link]())
new_key): print("Queue size after dequeue:", [Link]())
if old_key in dictionary: # Output:
dictionary[new_key] = # Queue size: 3
[Link](old_key) # Dequeued: 10
return True # Queue size after dequeue: 2
return False
my_dict = {'a': 1, 'b': 2, 'c': 3}

4
20. Write a Python program to swap the stack = []
values of two variables. pairs = {')': '(', ']': '[', '}': '{'}
a = input("Enter first variable: ") for char in s:
b = input("Enter second variable: ") if char in '([{':
print(f"Before: a={a}, b={b}") [Link](char)
a, b = b, a elif char in ')]}':
print(f"After: a={a}, b={b}") if not stack or stack[-1] != pairs[char]:
# Output: return False
# Enter first variable: 10 [Link]()
# Enter second variable: 20 return len(stack) == 0
# Before: a=10, b=20 test_str = input("Enter bracket string: ")
# After: a=20, b=10 print("Valid brackets:",
valid_brackets(test_str))
21. Write a Python program to display # Output:
current date and time. # Enter bracket string: ([{}])
from datetime import datetime # Valid brackets: True
now = [Link]()
print("Current date and time:", 24. Write a Python GUI program to reverse
[Link]("%Y-%m-%d %H:%M:%S")) string using Entry widget and Button.
# Output: import tkinter as tk
# Current date and time: 2024-01-15 14:30:25 def reverse_string():
original = [Link]()
22. Write a Python program to accept a reversed_str = original[::-1]
string and number, then repeat the string n result_label.config(text=f"Reversed:
times using operator overloading. {reversed_str}")
class StringRepeater: root = [Link]()
def __init__(self, text): [Link]("String Reverser")
[Link] = text [Link]("300x150")
def __mul__(self, n): [Link](root, text="Enter
return [Link] * n string:").pack(pady=5)
text = input("Enter string: ") entry = [Link](root, width=30)
n = int(input("Enter repeat count: ")) [Link](pady=5)
sr = StringRepeater(text) [Link](root, text="Reverse",
print("Repeated:", sr * n) command=reverse_string).pack(pady=5)
# Output: result_label = [Link](root, text="")
# Enter string: Hello result_label.pack(pady=10)
# Enter repeat count: 3 [Link]()
# Repeated: HelloHelloHello
# Output: [GUI where entering "Hello
23. Write a Python program to check if a World" and clicking Reverse shows
string is valid (only proper brackets (), [], "Reversed: dlroW olleH"]
{} closed in order).
def valid_brackets(s):

5
25. Write a program to demonstrate local • Cross-platform Portability: Python can
and global variable access. run on various platforms including
global_var = "I'm global" Windows, macOS, Linux, and Unix
def test_scope(): without requiring significant code
local_var = "I'm local" changes.
print("Inside function - Local:", local_var) • Interpreted Language: Python does not
print("Inside function - Global:", require compilation, resulting in a fast
global_var) edit-test-debug cycle which improves
print("Outside function - Global:", productivity.
global_var) • Extensive Standard Library: Python
test_scope() offers a large standard library and
# Trying to access local_var here would cause numerous third-party modules for web
error development, data science, machine
learning, scientific computing, and more.
# Output: • Community and Open Source: Python
# Outside function - Global: I'm global is open source and boasts a massive, active
# Inside function - Local: I'm local global developer community that
# Inside function - Global: I'm global provides extensive support, resources,
and open-source tools.
1. What is Python? What are the • Rapid Development: Python's
benefits/features of using Python? features allow developers to quickly
Python is a high-level, general-purpose create prototypes and build production-
programming language designed to ready software efficiently.
emphasize code readability and simplicity,
making it accessible for both beginners and 35. State the uses of TensorFlow
experienced developers.. It was created by TensorFlow is an open-source machine
Guido van Rossum and first released in 1991. learning framework developed by Google.
Python is interpreted and dynamically typed, Key uses:
which enables rapid development, 1. Neural Networks: Build and train various
prototyping, and efficient debugging.. neural network architectures
Key Features and Benefits 2. Deep Learning: Support for CNNs, RNNs,
• Simple, Readable Syntax: Python’s GANs, etc.
syntax is straightforward and close to the 3. Computer Vision: Image classification,
English language, making it easy to learn object detection
and write programs with fewer lines of 4. Natural Language Processing: Text
code compared to many other languages. classification, translation
• Multi-paradigm Support: Python 5. Reinforcement Learning: Agent-based
supports multiple learning systems
programming paradigms such as 6. Production Deployment: Model serving
procedural, object-oriented, and with TensorFlow Serving
functional programming, providing 7. Research: Flexible architecture for
flexibility to developers. experimental models

6
2. Explain different built-in data types in print(list(r)) # [0, 1, 2, 3, 4]
Python with examples (int, float, str, r2 = range(1, 10, 2) # 1,3,5,7,9 (start=1,
range). stop=10, step=2)
Python Built-in Data Types Explained print(list(r2)) # [1, 3, 5, 7, 9]
Let’s break down four important built-in print(type(r)) # <class 'range'>
data types in Python: int, float, str, 3. What are lists and tuples? What is the
and range. These types are fundamental and key difference between them?
used often in programming. Lists and tuples in Python are both structures
1. int (Integer) that store collections of data, but they differ in
• Represents whole numbers (positive, mutability and usage.
negative, or zero), with no decimal point. Lists are mutable, meaning their contents can
• Example: be changed after creation—items can be
python added, removed, or modified. Lists are
age = 25 # int created using square brackets []. For
temperature = -10 # int
big_num = 9888741223399 Key differences between lists and tuples:
print(type(age)) # <class 'int'> Aspect List Tuple
2. float (Floating Point)
• Used for numbers with a decimal point Mutabili Mutable Immutable
(real numbers). ty (changeable) (unchangeable)
• Example:
python Square
Syntax Parentheses()
price = 49.99 # float brackets[]
rate = -0.123 # float
Many (e.g.,
pi = 3.14159 Few (e.g., count,
Methods append,
print(type(price)) # <class 'float'> index)
remove)
3. str (String)
• Stores a sequence of characters, such as Perform Slower due Faster lookup
text or numbers written as text. ance to mutability and iteration
• Example:
python More
Memory Less memory
name = "Alice" # str memory
Usage consumed
greeting = 'Hello!' # str consumed
sentence = "Python 3.14"
print(type(name)) # <class 'str'> For For fixed
Use
4. range collections collections and
Case
• Represents a sequence of numbers; often
that change data integrity
used in loops.
Hashable if
• Does not directly output the values, but
Hashabil contents are
can be converted to a list or iterated over. Not hashable
ity hashable (can be
• Example:
dict keys)
python
r = range(5) # range 0,1,2,3,4

7
4. Describe string manipulation • join(): Joins a list of strings into a
techniques with examples. single string.
String manipulation in Python involves python
various techniques that allow you to modify, sentence = "Python is fun"
format, and analyze text data. Python words = [Link]() # ['Python',
provides numerous built-in methods for 'is', 'fun']
manipulating strings. joined = " ".join(words) # "Python is
Common String Manipulation Techniques fun"
with Examples 5. Repeating Strings
1. Changing Case • Multiply a string to repeat it.
• upper(): Converts all characters to python
uppercase. repeated = "PFB " * 3 # PFB PFB PFB
• lower(): Converts all characters to 6. Checking String Content
lowercase. • Methods
• capitalize(): Capitalizes the first like startswith(), endswith(), isalpha(
character. ), isdigit() help in verifying the
• title(): Capitalizes the first character of contents.
each word. filename = "[Link]"
• swapcase(): Swaps uppercase to print([Link]('.pdf')) # True
lowercase and vice versa.
python 37. What is Scikit-learn?
text = "Hello World" Scikit-learn is a free machine learning library
print([Link]()) # HELLO WORLD for Python. It features:
print([Link]()) # hello world 1. Classification: Identifying categories
print([Link]()) # Hello world (spam/not spam)
print([Link]()) # Hello World 2. Regression: Predicting continuous values
print([Link]()) # hELLO wORLD (house prices)
2. Stripping Spaces 3. Clustering: Grouping similar objects
• strip(): Removes leading and trailing 4. Model Selection: Comparing and tuning
whitespace. models
python 5. Preprocessing: Feature scaling,
text = " Python " normalization
print([Link]()) # Python 6. Dimensionality Reduction: Reducing
3. Replacing Substrings number of features
• replace(): Replaces a specific substring Key Algorithms Included:
with another. - Linear models, SVM, Decision Trees,
python Random Forests
text = "I like Python" - k-means, DBSCAN, hierarchical clustering
print([Link]("like", "love")) # I love - PCA, feature selection methods
Python
4. Splitting and Joining Strings
• split(): Splits a string into a list based
on a delimiter.

8
5. How does a static method work in Static methods are useful for grouping
Python? functions that have some logical connection
A static method in Python is a method that is to a class but do not need to access or modify
bound to a class rather than an instance of the the class or instance data, making the code
class. It does not receive the implicit first more organized.
argument self (which is the instance)
or cls (which is the class). Therefore, it cannot 6. Explain anonymous functions (lambda)
access or modify instance attributes or class in Python.
state. Static methods are typically used for Anonymous functions in Python, known
utility or helper functions that logically as lambda functions, are small, unnamed
belong to the class but do not require access functions defined with the lambda keyword.
to the class or instance-specific data. They can take any number of arguments but
How static methods work: can contain only one expression, which is
• They are defined inside a class but do not evaluated and returned.
operate on class or instance data. Syntax:
• Can be called directly on the class without lambda arguments: expression
creating an Key Points:
instance: [Link](). • Lambda functions do not have a name
• Can also be called from an instance, but (anonymous).
they still do not have access to the instance • Used for short, simple functions, often
or class attributes. used once.
Defining a static method: • Can be assigned to variables and called
You can define a static method using like normal functions.
the @staticmethod decorator above the Examples:
method definition: 1. Basic lambda function:
python double = lambda x: x * 2
class MyClass: print(double(5)) # Output: 10
@staticmethod 2. Lambda with multiple arguments:
def static_method(arg1, arg2): multiply = lambda a, b: a * b
print("Static method called with:", arg1, print(multiply(3, 4)) # Output: 12
arg2) 3. Used inside other functions:
# Calling static method without creating an def make_multiplier(n):
instance return lambda x: x * n
MyClass.static_method(10, 20) doubler = make_multiplier(2)
# Calling static method using an instance print(doubler(11)) # Output: 22
obj = MyClass() 4. Using with map():
obj.static_method(30, 40) nums = [1, 2, 3, 4]
Characteristics: doubled = list(map(lambda x: x * 2, nums))
• No automatic self or cls parameter. print(doubled) # Output: [2, 4, 6, 8]
• Cannot modify object or class state. Lambda functions are powerful for concise
• Acts like a regular function placed in and quick function definitions without
the class for logical grouping. cluttering your code with multiple full
function definitions.

9
7. Name any five built-in modules in making it critical for time-sensitive
Python. applications.
1. os module: from datetime import datetime
The os module provides a portable way to now = [Link]()
interact with the operating system. It allows print([Link]("%Y-%m-%d
you to handle file and directory operations, %H:%M:%S"))
retrieve environment variables, manipulate 5. random module:
paths, and execute system commands. It The random module helps generate
supports file creation, deletion, renaming, pseudo-random numbers, select random
directory traversal, and checking file items from a list, shuffle data, and simulate
existence. For example: random occurrences. It's widely used in
import os simulations, games, and randomized
print([Link]) # Shows OS name like algorithms.
'posix', 'nt' etc. import random
[Link]('new_folder') # Creates a directory print([Link](1, 100)) # Random
print([Link]()) # Lists files in the current integer between 1 and 100
directory print([Link](['apple', 'banana',
This module is essential for automating 'cherry'])) # Random selection
system-level tasks and scripts. 4. What are special operators in Python?
2. sys module: What are the properties of Python lists?
The sys module provides access to In this section, we will discuss special
variables and functions related to the operators and list properties:
Python interpreter. It helps manage the Special Operators in Python:
runtime environment, command-line 1. Identity Operators:
arguments, and system-specific • is - Returns True if both variables are the
parameters. Common uses include exiting same object
a program ([Link]()), checking the • is not - Returns True if both variables are
Python version, and manipulating the not the same object
import path ([Link]). 2. Membership Operators:
3. math module: • in - Returns True if a value is found in the
The math module offers mathematical sequence
functions beyond the basic arithmetic, • not in - Returns True if a value is not found
such as trigonometric functions (sin, cos), in the sequence
logarithms, exponentiation, factorial, and Properties of Python Lists:
constants like pi and e. It enables 1. Ordered: Lists maintain the order of
scientific calculations in Python with elements as they are inserted.
precision. 2. Mutable: Lists can be modified after
4. datetime module: creation.
This module supplies classes to 3. Heterogeneous: Lists can contain
manipulate dates and times easily. You elements of different data types.
can create, format, and compute 4. Dynamic: Lists can grow or shrink in size.
differences between dates and times. It 5. Allow Duplicates: Lists can contain
supports time zones and conversions, duplicate elements.

10
8. Define and explain user-defined Arguments are passed using keywords for
functions with examples. clarity and flexibility.
A user-defined function is declared using the 5. Variable-Length Arguments
def keyword, followed by the function name, def fun(*args):
parameters (if any), and a block of indented for arg in args:
statements. It enables the programmer to print(arg)
decompose complex tasks into simpler fun("Python", "Java", "C++")
subroutines, improving code organization and # Output:
efficiency. # Python
Syntax # Java
def function_name(parameters): # C++
# function body This function accepts multiple arguments
statements using *args.
return value # optional 6. Function With Return Value
Examples def fun(num):
1. Even/Odd Check Function return num * num
def fun(x): res = fun(5)
if x % 2 == 0: print(res) # Output: 25
print("even") A function that returns the square of a number,
else: demonstrating the use of the return statement.
print("odd")
fun(2) # Output: even 12. What is an exception in Python?
This function checks if a number is even or Definition:
odd, illustrating how logic and decision- An exception is an event that occurs during
making function calls work. the execution of a program that disrupts the
2. Parameterized Greeting Function normal flow of the program's instructions.
def fun(name): When a Python script encounters a situation
print("Hello,", name) that it cannot cope with, it raises an exception.
fun("Shakshi") # Output: Hello, Shakshi Types of Errors:
A function that takes a parameter and prints a 1. Syntax Errors: Occur when the parser
personalized greeting. detects an incorrect statement
3. Function With Default Arguments 2. Exceptions: Occur during execution,
def fun(x, y=50): even if syntax is correct
print("x:", x) Common Exception Scenarios:
print("y:", y) • Dividing by zero
fun(10) # Output: x: 10, y: 50 • Accessing non-existent file
This function demonstrates the use of default • Converting invalid string to number
arguments. • Accessing index that doesn't exist
4. Keyword Argument Functiondef • Importing non-existent module
fun(name, age):
print(name, "is", age, "years old.")
fun(age=21, name="Shakshi") # Output:
Shakshi is 21 years old.

11
9. Explain function arguments in detail. student(age=15, name="Jane") # Output:
Python Function Arguments Explained Jane 15
Function arguments are the values you pass 4. Arbitrary Arguments
into a function when you call it. They provide a. *args (Arbitrary Positional Arguments)
input for the function to work with. In Python, • Use *args in the definition to accept
there are several types of function arguments, any number of positional arguments
each giving you flexibility in how functions (packed in a tuple).
handle input. • Example:
Let's break down the main types of function def add_all(*numbers):
arguments, with clear examples for each: return sum(numbers)
1. Positional Arguments print(add_all(1, 2, 3, 4)) # Output: 10
• Arguments are matched to parameters b. **kwargs (Arbitrary Keyword
by their position in the call (first to first, Arguments)
and so on). • Use **kwargs in the definition to
• Example: accept any number of keyword/named
def power(base, exponent): arguments (packed in a dictionary).
return base ** exponent • Example:
print(power(2, 3)) # Output: 8 (base=2, def show_info(**details):
exponent=3) print(details)
2. Default Arguments show_info(name="Tom", age=16,
• Parameters can have a default city="Delhi") # Output: {'name': 'Tom', 'age':
value used if you don't supply that 16, 'city': 'Delhi'}
argument. 5. Lambda Function Arguments
• If you specify a value, it overrides the • Lambda (anonymous) functions are
default. defined with arguments just like
• Default arguments must always come normal functions, but are intended for
after non-default parameters. small, single-use operations.
• Example: • Example:
def greet(name, message="Hello"): square = lambda x: x*x
print(message, name) print(square(5)) # Output: 25
greet("Alice") # Output: Hello Alice
(uses default) 29. List any five button options available in
greet("Bob", "Hi") # Output: Hi Bob Tkinter
(overrides default) In this section, we will explore five
3. Keyword Arguments (Named important button options in Tkinter:
Arguments) Five Key Button Options:
• You explicitly name arguments in the 1. text: Display text on the button
call, regardless of their position. 2. command: Function to call when button is
• Makes code more readable and avoids clicked
confusion in order. 3. state: Control whether button is active or
• Example: disabled
def student(name, age): 4. bg/fg: Background and foreground colors
print(name, age) 5. font: Text font and size

12
[Link] the for loop with syntax and expresses that the child class is a type
example. of the parent.
A for loop in Python is used to iterate over a • How? Achieved using inheritance.
sequence such as a list, tuple, string, • Syntax:
dictionary, or range object, executing a block class Parent:
of code once for each item in the sequence. def details(self):
Python's for loop is more like a "for-each" print("This is the Parent class.")
loop seen in other languages.
Syntax: class Child(Parent): # Child is a Parent
for variable in sequence: def show(self):
# block of code to execute print("This is the Child class.")
• variable takes the value of each item in
the sequence one by one. obj = Child()
• The indented block runs for each item. [Link]() # Inherited from Parent
Simple Example: [Link]()
fruits = ["apple", "banana", "cherry"] • Example:
for fruit in fruits: • In a school, a Student is a Person.
print(fruit) • In a vehicle system, a Car is a Vehicle.
Output: HAS-A Relationship (Composition)
apple • Definition: A "HAS-A" relationship
banana means a class possesses another class as
cherry one of its attributes. The first class uses or
Loop Through a String: "contains" an object of the second. This is
for char in "banana": called composition.
print(char) • How? Achieved by creating an instance
Output: of one class inside another.
Banana • Syntax:
class Engine:
Using range() in for loop: def start(self):
Useful for iterating a specific number of print("Engine started.")
times. class Car:
for i in range(5): # 0 to 4 def __init__(self):
print(i) [Link] = Engine() # Car has an
Output: Engine
01234 def drive(self):
[Link]()
[Link] IS-A and HAS-A relationships print("Car is driving.")
with examples. my_car = Car()
IS-A Relationship (Inheritance) my_car.drive()
• Definition: An "IS-A" relationship means • Example:
one class (child) inherits from another • A Car has an Engine.
class (parent), forming a hierarchy. This • A Library has Books.

13
[Link] is inheritance? Explain its types, 3. Multilevel Inheritance
syntax, and benefits with examples. • A chain of inheritance: grandparent
Inheritance in Python → parent → child.
Inheritance is an object-oriented • Each level can add features and reuse
programming feature that allows one class the previous ones.
(the child or derived class) to acquire class Grandparent:
properties and behavior (methods and def hobby(self):
attributes) from another class (the parent or print("Gardening")
base class). Inheritance promotes code class Parent(Grandparent):
reusability, organization, and the creation of pass
hierarchical relationships between classes. class Child(Parent):
Types of Inheritance in Python pass
Python supports several types of inheritance, ch = Child()
depending on how many parent and child [Link]()
classes are involved: 4. Hierarchical Inheritance
1. Single Inheritance • Multiple children inherit from the
• One child inherits from one parent. same parent.
• Facilitates code reuse and extension. • Common base functionality shared and
class Parent: extended differently.
def speak(self): class Animal:
print("Parent speaking.") def eat(self):
class Child(Parent): print("Eating...")
def play(self): class Dog(Animal):
print("Child playing.") def bark(self):
c = Child() print("Woof!")
[Link]() # Inherited from Parent class Cat(Animal):
[Link]() # Defined in Child def meow(self):
2. Multiple Inheritance print("Meow!")
• One child inherits from multiple d = Dog()
parents. [Link](); [Link]()
• Allows combining features from c = Cat(); [Link](); [Link]()
several sources. 5. Hybrid Inheritance
class Mother: • Combination of multiple inheritance
def work(self): types.
print("Mother working.") • Can create complex class relationships.
class Father: class A:
def drive(self): pass
print("Father driving.") class B(A):
class Son(Mother, Father): pass
pass class C(A):
s = Son() pass
[Link]() class D(B, C):
[Link]() pass

14
[Link] an abstract class Shape and its print("Square area:", [Link]()) #
subclasses Square / Circle. Square area: 25
An abstract class in Python is a blueprint for print("Square perimeter:",
other classes. It cannot be instantiated directly [Link]()) # Square perimeter: 20
and typically contains one or more abstract
methods that must be implemented by its circle = Circle(7)
subclasses. Abstract classes provide a way to print("Circle area:", [Link]()) #
enforce certain methods to be created in child Circle area: 153.93831
classes, ensuring a common interface. print("Circle perimeter:", [Link]())
Here is how to define an abstract # Circle perimeter: 43.98226
class Shape with two abstract
methods area() and perimeter(), and then Explanation:
implement these in • The Shape class inherits from ABC and
subclasses Square and Circle: uses the @abstractmethod decorator for
python methods that must be overridden.
from abc import ABC, abstractmethod • Square and Circle provide their own
# Abstract class Shape implementations
class Shape(ABC): for area() and perimeter().
@abstractmethod • Trying to instantiate Shape directly will
def area(self): raise an error because it's abstract.
pass • This design enforces a consistent interface
@abstractmethod and allows polymorphism when working
def perimeter(self): with different shapes.
pass •
# Subclass Square implementing Shape 8. Compare Python lists and NumPy arrays
class Square(Shape): In this section, we will compare Python lists
def __init__(self, side): and NumPy arrays:
[Link] = side Python Lists:
• Built-in data structure in Python
def area(self): • Can contain elements of different data
return [Link] * [Link] types
def perimeter(self): • Less memory efficient
return 4 * [Link] • Slower for mathematical operations
# Subclass Circle implementing Shape • Dynamic sizing
class Circle(Shape): NumPy Arrays:
def __init__(self, radius): • Part of NumPy library, need to import
[Link] = radius • Homogeneous data types (all elements
def area(self): same type)
return 3.14159 * [Link] ** 2 • More memory efficient
def perimeter(self): • Faster for mathematical operations
return 2 * 3.14159 * [Link] • Fixed size after creation
# Example usage
square = Square(5)

15
[Link] exception handling in Python else:
with examples. print("Result is", res)
Exception Handling in Python finally:
Exception handling in Python lets you print("Execution complete.")
manage errors gracefully, avoiding program Output
crashes and allowing your code to run You can't divide by zero!
smoothly even when something unexpected Execution complete.
happens.
Why Use Exception Handling? [Link] the except clause with no
• Catches errors that would otherwise exception.
crash your program The except clause with no exception
• Lets you give user-friendly error specified in Python is a generic exception
messages handler, often called a "bare except." It
• Allows you to handle different types of catches all types of exceptions that may
exceptions separately occur within the corresponding try block,
syntax: regardless of the exception type.
try: How it works:
# Code • If no exceptions occur in the try block,
except SomeException: the except block is simply skipped.
# Code • If any exception occurs, the except block
else: runs, handling the error.
# Code • This generic except:
finally: • Syntax:
# Code try:
try: Runs the risky code that might cause an # Code that may raise an exception
error. except:
except: Catches and handles the error if one # Handle any exception occurred above
occurs.
else: Executes only if no exception occurs in Example:
try. try:
finally: Runs regardless of what happens print("Running code")
useful for cleanup tasks like closing files. result = 10 / 0
Example: This code attempts division and except:
handles errors gracefully using try-except- print("An error occurred")
else-finally. Output:
try: An error occurred
n=0 If no exception occurs:
res = 100 / n try:
except ZeroDivisionError: print("Division result:", 10 / 2)
print("You can't divide by zero!") except:
except ValueError: print("This won't be printed")
print("Enter a valid number!") Output Division result: 5.0

16
[Link] various types of exceptions in • FloatingPointError: Raised when a
Python. floating-point operation fails due
In Python, exceptions are special classes that to precision or computational issues.
represent errors or unusual conditions 3. Lookup Errors
detected during program execution. They are The LookupError class is the base
part of a class hierarchy rooted in for exceptions that occur when looking up
the BaseException class, from which all other elements in data structures using
exceptions inherit. Exceptions are crucial invalid indices or keys:
for structured error handling, • IndexError: Occurs when attempting
allowing developers to write programs that to access a list or tuple element using
can detect, handle, or recover from an out-of-range index.
runtime problems gracefully. • KeyError: Raised when a
1. BaseException and Exception Hierarchy dictionary key is not found.
At the top of the hierarchy 4. Import Errors
is the BaseException class, which is the Import-related exceptions are used
superclass of all exceptions in Python. when problems arise while
From it, we get several important branches, importing modules:
including SystemExit, KeyboardInterrupt, G • ImportError: Raised when an
eneratorExit, and the general- import statement fails to load a
purpose Exception class. Programmers module or object.
typically use subclasses of Exception for • ModuleNotFoundError: A
error handling, since other BaseException subclass of ImportError, raised when
subclasses are reserved for system- the specific module cannot be located.
level events like user interruption or process 5. Name and Attribute Errors
termination. • NameError: Happens when a local or
The Exception class itself serves as global variable name is not defined.
the foundation for nearly all runtime errors • UnboundLocalError: A subclass
that Python raises automatically or that of NameError raised when a local
developers can manually trigger variable is referenced before
using the raise statement. Under it, Python assignment.
organizes exceptions into categories based on • AttributeError: Occurs when
their purpose. invalid or unavailable attributes
2. Arithmetic Errors are referenced in an object.
Arithmetic-related exceptions are derived 6. Syntax and Indentation Errors
from the ArithmeticError base class. They Syntax problems, detected during parsing,
include: raise:
• ZeroDivisionError: Raised when a • SyntaxError: Occurs when
number is divided or modulo- Python encounters invalid syntax.
divided by zero. • IndentationError: Happens when
• OverflowError: Occurs when the indentation is inconsistent or incorrect.
result of an arithmetic operation • TabError: Raised when indentation
exceeds the limits of representation. uses mismatched tabs and spaces.

17
[Link] the math and cmath modules print([Link](-4))
with examples. Output: (0+2j)
Math Module
The math module provides functions for [Link] the datetime and calendar
performing mathematical operations on real modules with examples.
numbers (integers or floats). If a complex Python datetime and calendar Modules
number is passed to a function from this Python provides two main modules for
module, it raises a TypeError. The module handling dates and
includes a variety of functions for times: datetime and calendar. Let's look at
trigonometric, exponential, logarithmic, and each module, their key uses, and some
factorial operations, along with useful practical examples to help you understand
constants like pi and e. how to work with them.
To use the module, it must be imported: The datetime Module
import math The datetime module lets you create,
Constants in math module: manipulate, and format dates and times in
• [Link] – The mathematical constant π Python. It's commonly used for tasks like
≈ 3.141592653589793. logging timestamps, calculating durations,
• math.e – The base of natural logarithms scheduling events, and formatting date
≈ 2.718281828459045. outputs for users.
Example: Key Examples
import math Getting the Current Date and Time:
print([Link]) import datetime
print(math.e) now = [Link]()
Output: print(now) # e.g., 2025-10-23
3.141592653589793 22:00:00.000000
2.718281828459045 The calendar Module
Cmath Module The calendar module lets you output
The cmath module is similar to math, but it calendars, find the day of the week for any
supports complex numbers in addition to real date, check if years are leap years, and more.
numbers. It can handle input values with both It's useful for applications needing date
real and imaginary parts and returns results as calculations based on calendar rules.
complex numbers. Even if the result is a real Examples
value, it is represented as a complex number Printing a Month Calendar:
with an imaginary part of 0j. import calendar
To use this module, import it as follows: print([Link](2025, 10))
python Output:
import cmath October 2025
Common Functions in the cmath Module: Mo Tu We Th Fr Sa Su
1. [Link](x) – Returns the square 1 2 3 4 5
root of a number, including negative or 6 7 8 9 10 11 12
complex values. 13 14 15 16 17 18 19
Example: 20 21 22 23 24 25 26
import cmath 27 28 29 30 31

18
[Link] is the sys module? Explain in 2. [Link] – Python version information
detail. Returns the version number of the Python
The sys module in Python provides access to interpreter in use.
system-specific parameters, variables, and Example:
functions that interact closely with import sys
the Python interpreter. It allows you to print([Link])
control various aspects of the runtime Output (example):
environment, such as command-line text
arguments, module paths, the interpreter 3.12.1 (tags/v3.12.1:abc123, Dec 1 2025)
version, and input/output streams. This
module is part of Python’s standard library 3. [Link]([arg]) – Exiting a program
and does not require installation — it can be Terminates the program execution. The
imported directly using import sys. argument can be an integer (exit status) or
a string (message).
Purpose of the sys Module Example:
The sys module is primarily used to: import sys
• Interact with the Python interpreter. age = 17
• Handle command-line arguments. if age < 18:
• Manage the input/output streams and [Link]("Age less than 18, access denied")
program termination. else:
• Access or modify search paths for print("Access granted")
module imports. Output:
• Retrieve information about the Python SystemExit: Age less than 18, access denied
environment, version, and platform. This is especially useful in large scripts and
applications to stop execution safely.
Commonly Used Functions and Attributes
1. [Link] – Command-line arguments 4. [Link] – Module search path
It is a list of command-line arguments This is a list of directory paths in which
passed to a Python script. The first element Python looks for modules when importing
([Link]) is the script name, and the rest them. It is initialized with the environment
are arguments supplied by the user. variable PYTHONPATH plus some
standard locations. You can modify it to
Example: include custom module directories.
import sys Example:
print("Script name:", [Link][0]) import sys
print("Arguments passed:", [Link][1:]) print([Link]) # List of module paths
If you run this as: [Link]("/my/custom/modules")
python [Link] 10 20 30 This helps Python locate modules that aren’t
Output: installed in standard directories.
Script name: [Link]
Arguments passed: ['10', '20', '30']
len([Link]) gives the number of arguments.

19
[Link] is Pandas? Explain its features databases, JSON, XML, and more.
and advantages. Functions like read_csv(), to_excel(),
The name Pandas originates from the and read_sql() make data exchange
term “Panel Data”, which refers to multi- convenient.
dimensional data sets commonly used in 5. Data Aggregation and Grouping
statistics and econometrics, and also stands The powerful groupby() function enables
for “Python Data Analysis”. Built on top of the “split-apply-combine” process for
the NumPy library, Pandas integrates summarizing or transforming groups of
seamlessly with other key Python packages data efficiently.
like Matplotlib, NumPy, SciPy, and Scikit-
learn. Advantages of Pandas
Pandas primarily provides two highly 1. Ease of Use
efficient data structures: Pandas makes complex data analysis tasks
• Series – A one-dimensional labeled more intuitive with simple, human-
array (like a column in a spreadsheet). readable syntax for transforming massive
• DataFrame – A two-dimensional datasets quickly.
labeled data structure (like a table with 2. Speed and Efficiency
rows and columns). Internally optimized by NumPy, Pandas
performs computations faster than raw
Key Features of Pandas Python list or dictionary operations, even
1. Powerful Data Structures on millions of rows.
The core objects, Series and DataFrame, 3. Versatility
are optimized for efficient data handling, It supports different data formats and
enabling fast computations and easy integrates seamlessly with other data
manipulation similar to Excel or SQL science libraries such as NumPy,
tables. Matplotlib, and Scikit-learn.
2. Data Cleaning and Preparation 4. Comprehensive Functionality
Pandas provides built-in tools for Pandas supports a full data workflow—
identifying and handling missing or from importing, cleaning, transforming,
invalid data using methods visualizing, to exporting, all within the
like fillna(), dropna(), and replace(). This same framework.
makes data preparation seamless and 5. Powerful for Real-world Data
eliminates errors in analysis. It easily handles real-world messy datasets
3. Flexible Data Indexing and Alignment with missing, duplicated, or inconsistent
Through intelligent indexing, Pandas data values, enabling strong preprocessing
allows quick access, slicing, and pipelines.
reorganization of data using labels,
integers, or boolean logic, ensuring data
remains properly aligned during
operations.
4. Data Integration
Pandas supports reading and writing data
in multiple formats—CSV, Excel, SQL

20
[Link] are the features of NumPy? , and log(). These functions operate on
NumPy (Numerical Python) is a high- entire arrays efficiently.
performance, open-source library in Example:
Python used for numerical computing and arr = [Link]([1, 2, 3, 4])
scientific data analysis. It print([Link](arr)) # Average value → 2.5
provides the ndarray object—a powerful N- print([Link](arr)) # Square root → [1. 1.41
dimensional array—and a collection of 1.73 2.]
mathematical functions to efficiently 4. Broadcasting
perform large-scale numerical operations NumPy performs broadcasting, enabling
without using explicit loops. arithmetic between arrays of
Key Features of NumPy different shapes and sizes automatically.
1. N-Dimensional Array This allows smaller arrays to
Object (ndarray) “stretch” during computations without
The core feature of NumPy is the ndarray, requiring manual resizing.
a fast, compact, and efficient Example:
container for homogeneous data (data import numpy as np
of the same type). Unlike Python lists, a = [Link]([1, 2, 3])
NumPy arrays store values in b=5
contiguous memory blocks, which print(a + b) # Output: [6 7 8]
speeds up computation significantly. 5. Array Indexing and Slicing
Arrays can be 1D (like a list), 2D (like NumPy provides advanced
a matrix), or multidimensional. indexing techniques such as slicing,
Example: boolean indexing, and fancy indexing to
import numpy as np access specific parts of an
arr = [Link]([[1, 2, 3], [4, 5, 6]]) array efficiently.
print([Link]) # Output: 2 Example:
2. Vectorized Operations arr = [Link]([10, 20, 30, 40, 50])
NumPy allows vectorization, meaning print(arr[1:4]) # Slicing → [20 30 40]
operations are automatically applied print(arr[arr > 25]) # Conditional indexing
element-wise on entire arrays, → [30 40 50]
avoiding the need for explicit loops and
resulting in faster performance.
Example:
import numpy as np
a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])
print(a + b) # Output: [5 7 9]
3. Mathematical and
Statistical Functions
NumPy supports a wide
range of mathematical, statistical,
and trigonometric functions
like sum(), mean(), median(), sin(), exp()

21
[Link] is data visualization? List any [Link](style="whitegrid")
four visualization libraries. tips = sns.load_dataset("tips")
Data visualization is the graphical [Link](x="day", y="total_bill",
representation of information and data using data=tips)
visual elements such as charts, graphs, maps, [Link]()
and diagrams. It allows complex datasets to 3. Plotly
be understood visually, helping people Plotly is an interactive, browser-
identify trends, correlations, patterns, and based visualization library for creating
outliers that are difficult to detect from raw dynamic and web-ready charts. It is widely
numerical data alone. The goal of data used for viewing and sharing interactive
visualization is to make data easier to visualizations directly in notebooks or web
understand and interpret, facilitating data- applications.
driven decision-making across disciplines • Example:
like business analysis, machine learning, and import [Link] as px
scientific research. df = [Link]()
Four Popular Data Visualization Libraries fig = [Link](df, x='sepal_width',
in Python y='sepal_length', color='species')
1. Matplotlib [Link]()
Matplotlib is the foundational and most 4. Bokeh
widely used data visualization library in Bokeh is designed for interactive and
Python. It supports 2D plotting for static real-time visualizations in modern web
charts such as line graphs, bar charts, browsers. It is particularly useful for
scatter plots, pie charts, and histograms. visually rich dashboards or live data
• Example: streaming.
import [Link] as plt • Example:
x = [1, 2, 3, 4] from [Link] import figure, show
y = [10, 20, 25, 30] p = figure(title="Simple Example",
[Link](x, y) x_axis_label='x', y_axis_label='y')
[Link]("X-axis") [Link]([1, 2, 3, 4], [6, 7, 2, 4], line_width=2)
[Link]("Y-axis") show(p)
[Link]("Simple Line Chart")
[Link]()
2. Seaborn
Built on top of Matplotlib, Seaborn provides
a high-level interface for creating
aesthetically appealing and statistically
meaningful visualizations. It simplifies the
process of drawing complex graphs and
integrates seamlessly with Pandas
DataFrames.
Example:
import seaborn as sns
import [Link] as plt

22
[Link] the principles of Keras. [Link]()
Keras is an open-source deep learning outputs a clear overview of all layers, shapes,
framework written in Python that simplifies and parameters.
building and training artificial neural 3. Extensibility
networks. It provides a high-level, user- Keras is flexible and allows developers to
friendly interface for designing machine add new components easily.
learning and deep learning models, while • Custom layers, loss functions, and metrics
internally leveraging backends like can be implemented by subclassing
TensorFlow or Theano for performing the existing Keras classes.
computations. • This makes it ideal for research and
experimentation involving new algorithms
Principles of Keras or architectures.
1. Modularity Example:
Keras follows a modular architecture from [Link] import Layer
where models, layers, optimizers, import tensorflow as tf
objectives, and activation functions are class MyCustomLayer(Layer):
treated as independent, reusable def call(self, inputs):
components. return [Link](inputs)
• Developers can quickly build complex
neural networks by chaining modular 34. Define NumPy and state its uses
components together. NumPy (Numerical Python) is a fundamental
• Example: package for scientific computing in Python. It
from [Link] import Sequential provides:
from [Link] import Dense - ndarray: Efficient multi-dimensional array
model = Sequential([ object
Dense(64, activation='relu', - Mathematical Functions: Fast operations on
input_dim=100), arrays
Dense(10, activation='softmax') - Linear Algebra: Matrix operations,
]) decompositions
This modular composition simplifies - Random Number Generation: Various
experimentation and model customization. probability distributions
2. User-Friendliness - Integration: Tools for integrating C/C++
Keras prioritizes simplicity and code
minimalism in its design, offering an Key Uses:
intuitive API that is easy to learn and use. 1. Mathematical and logical operations on
• It hides the low-level details of arrays
computation, making model creation and 2. Fourier transforms and routines for shape
training straightforward. manipulation
• Clear and informative error messages help 3. Linear algebra and random number
users debug and iterate quickly. generation
• Keras models can be easily summarized, 4. Integration with databases
visualized, and saved.
Example:

23
[Link] are common Python libraries for • Scikit-learn – A comprehensive library
data science? for machine learning that supports
Python’s dominance in data science is largely classification, regression, clustering,
due to its vast ecosystem of specialized dimensionality reduction, and model
libraries that make tasks like data processing, evaluation.
analysis, visualization, and modeling efficient • TensorFlow and Keras – For deep
and accessible. The most widely used libraries learning. TensorFlow provides a powerful
include : backend for numerical computation using
• NumPy – The foundation library for dataflow graphs, while Keras acts as a
numerical computing. It provides support high-level API for building and training
for multi-dimensional arrays, matrices, neural networks easily.
and mathematical operations like linear • SciPy – Useful for scientific
algebra and Fourier transforms. computations involving integrals,
Example: optimization, and signal processing.
python
import numpy as np 28. How is grid() geometry management
a = [Link]([1, 2, 3]) method used in Tkinter?
print([Link](a)) # Output: 2.0 In this section, we will learn how to use the
• Pandas – A flexible library for data grid() geometry manager in detail:
manipulation and analysis, offering Basic grid() Syntax:
powerful data structures [Link](row=row_number,
like Series and DataFrame for handling column=column_number, options)
structured data. Common grid() Options:
Example: • row, column: Position in grid
python • rowspan, columnspan: Span multiple
import pandas as pd rows/columns
data = {"Name": ["John", "Alice"], "Age": • padx, pady: External padding
[23, 25]} • ipadx, ipady: Internal padding
df = [Link](data) Summary of grid() Methods:
print(df) • grid(): Place widget in grid
• Matplotlib – The primary data • grid_remove(): Remove widget but
visualization library used for creating remember settings
static, animated, and interactive plots in • grid_forget(): Completely remove widget
2D. from grid
Example: • grid_info(): Get grid configuration
import [Link] as plt information
[Link]([1, 2, 3], [2, 4, 6]) Best Practices for grid():
[Link]("Simple Plot") 1. Use sticky for proper alignment and
[Link]() stretching
• Seaborn – A higher-level interface built 2. Use rowspan and columnspan for
on Matplotlib for producing attractive and complex layouts
statistically informed visualizations such
as heatmaps, violin plots, and pair plots.

24
[Link] is Tkinter? Explain any three button = Button(root, text="Click Me",
commonly used widgets. command=say_hello)
Tkinter is the standard GUI (Graphical [Link]()
User Interface) library for Python. It [Link]()
provides a simple way to build desktop When the user clicks the button, “Hello,
applications with interactive features. Tkinter World!” prints to the console.
comes preinstalled with Python, making it 3. Entry Widget
accessible without additional setup. It allows The Entry widget allows users to input a
developers to create windows, buttons, labels, single line of text, such as usernames or
text boxes, and menus using object-oriented passwords. It is widely used in forms and
or procedural programming styles. login screens.
A widget in Tkinter refers to a visual Example:
component of a GUI, such as a button, label, from tkinter import *
or input field. root = Tk()
entry = Entry(root, width=30)
Commonly Used Tkinter Widgets [Link]()
1. Label Widget [Link](0, "Enter your name")
The Label widget is used to display static [Link]()
text or images on the window. It is often This creates a text box where the user can type
used for titles, captions, or short information.
descriptions.
Example: 7. Differentiate between a set and a
from tkinter import * dictionary in Python
root = Tk() Set:
label = Label(root, text="Welcome to • Unordered collection of unique
Tkinter!", font=("Arial", 14)) elements
[Link]() • Created using curly
[Link]() braces {} or set() function
This displays a window containing text • Contains only keys (no values)
“Welcome to Tkinter!”. • Elements must be immutable
• Used for mathematical set operations
2. Button Widget Dictionary:
The Button widget creates clickable • Unordered collection of key-value
buttons that can trigger specific actions or pairs
commands when pressed. It is commonly • Created using curly
used for event handling such as submitting braces {} with key:value pairs
forms or closing the window. • Contains both keys and values
Example: • Keys must be immutable, values can be
from tkinter import * any type
root = Tk() • Used for storing and retrieving data by
def say_hello(): key
print("Hello, World!")

25
[Link] geometry management • Description: Allows you to specify the
methods in Tkinter with examples. exact x and y coordinates for widget
Tkinter provides three primary geometry placement, either in absolute units or
managers to control how widgets are arranged relative to the parent widget size.
in a window or frame: • Usage Example:
1. pack() Geometry Manager import tkinter as tk
• Description: Arranges widgets in blocks root = [Link]()
before placing them in the parent widget. label = [Link](root, text="Placed at (50,
By default, widgets are packed from the 40)")
top, but you can specify sides (top, bottom, [Link](x=50, y=40)
left, right), fill, and expand options. [Link]()
• Usage Example: The label appears at coordinate (50, 40) in the
import tkinter as tk window.
root = [Link]()
[Link](root, text="Top").pack() [Link] the frame widget in Tkinter
[Link](root, text="Left").pack(side="left") with example.
[Link](root, Frame Widget in Tkinter with Example
text="Right").pack(side="right") A Frame in Tkinter is a container widget
[Link]() used to group other widgets together. It helps
This displays buttons at the top, left, and right organize layouts by acting as a holder where
of the window. you arrange multiple widgets using geometry
2. grid() Geometry Manager managers. Frames are commonly used to
• Description: Organizes widgets in a separate sections of the GUI for clarity and
table-like grid of rows and columns. modularity.
Each widget is assigned to a specific Example: Using Frame in Tkinter
row and column, and you can import tkinter as tk
use rowspan and columnspan to make root = [Link]()
widgets span multiple rows/columns. # Create a Frame
• Usage Example: frame = [Link](root, bg='lightblue',
import tkinter as tk width=200, height=100)
root = [Link]() [Link](padx=10, pady=10)
[Link](root, text="Username").grid(row=0,
column=0) # Add widgets inside the Frame
[Link](root).grid(row=0, column=1) [Link](frame, text="Inside Frame").pack()
[Link](root, text="Password").grid(row=1, [Link](frame, text="Click Me").pack()
column=0) [Link]()
[Link](root, show="*").grid(row=1, • The Frame is packed into the root window
column=1) with padding around it.
[Link]() • The label and button are placed inside the
This creates a small login form using rows Frame, keeping them grouped visually.
and columns. • You can nest frames and use different
3. place() Geometry Manager geometry managers in each for more
advanced layouts.

26
[Link] the delete() and insert() window = [Link]()
methods of Entry widget. entry = [Link](window)
The Tkinter Entry widget is used to accept [Link]()
single-line user input in GUI applications. [Link](0, "Hello World!") # Inserts at
Two important methods for manipulating its the beginning
content are delete() and insert(): [Link]()
delete() Method This puts "Hello World!" in the Entry field
• Purpose: Removes characters from the when the application starts.
Entry field at specified indices. 5. Differentiate between append() and
• Syntax: [Link](first, last=None) extend() methods in lists
• first: Starting index (0-based). In this section, we will differentiate
• last (optional): Ending index (not between append() and extend() methods:
included in deletion, so up to but not append() method:
including). • Adds its argument as a single element to
• If only first is provided, deletes the the end of the list
single character at that index. • The length of the list increases by exactly
• If both are provided, deletes the range. one
• Common usage: [Link](0, • Can add any data type as a single element
'end') clears all contents. extend() method:
Example – Clearing an Entry on Button • Iterates over its argument and adds each
Press: element to the list
import tkinter as tk • The length increases by the number of
window = [Link]() elements in the iterable
entry = [Link](window) • Argument must be iterable
[Link]() Examples:
def clear_entry(): Using append():
[Link](0, 'end') list1 = [1, 2, 3]
button = [Link](window, text="Clear", [Link]([4, 5]) # Adds the entire list as a
command=clear_entry) single element
[Link]() print("After append:", list1)
[Link]() print("Length:", len(list1))
When the button is clicked, the Entry field is Output:
cleared of all text. After append: [1, 2, 3, [4, 5]]
insert() Method Length: 4
• Purpose: Inserts a string at a specified Using extend():
position in the Entry field. list1 = [1, 2, 3]
• Syntax: [Link](index, string) [Link]([4, 5]) # Adds each element
• index: Position to insert (0-based). individually
• string: Text to insert. print("After extend:", list1)
• Often used to pre-fill or update the Entry print("Length:", len(list1))
with default content. Output:
Example – Pre-filling Entry: After extend: [1, 2, 3, 4, 5]
import tkinter as tk Length: 5

27
[Link] is a dictionary in Python? Explain 17. How to create a class and object in
any three built-in dictionary functions Python?
with examples. Python’s object-oriented programming
A dictionary in Python is an unordered (OOP) allows you to model real-world
collection of data that stores key–value pairs. entities in code, making programs more
Keys must be unique and immutable (like organized, reusable and easier to maintain. By
strings, numbers, or tuples), while values can grouping related data and behavior into a
be any Python object. Dictionaries are written single unit, classes and objects help you write
with curly braces {}: cleaner, more logical code for everything
python from small scripts to large applications.
d = {"name": "Alice", "age": 30, "city": "New Class
York"} A class in Python is a user-defined template
Three Built-in Dictionary Functions for creating objects. It bundles data and
Here are three commonly used functions together, making it easier to manage
functions/methods for working with and use them. When we create a new class, we
dictionaries: define a new type of object. We can then
1. get() create multiple instances of this object type.
• Purpose: Retrieves the value for a given Creating Class
key, returns None if the key is absent Classes are created using class keyword.
instead of throwing an error. Attributes are variables defined inside class
• Example: and represent properties of the class.
person = {"name": "Bob", "age": 28} Attributes can be accessed using dot . operator
print([Link]("name")) # Output: Bob (e.g., MyClass.my_attribute).
print([Link]("gender")) # Output: None # define a class
2. clear() class Dog:
• Purpose: Removes all key–value pairs, sound = "bark" # class attribute
leaving an empty dictionary. Object
• Example: An object is a specific instance of a class. It
data = {"a": 1, "b": 2} holds its own set of data (instance variables)
[Link]() and can invoke methods defined by its class.
print(data) # Output: {} Multiple objects can be created from same
3. keys() class, each with its own unique attributes.
• Purpose: Returns a view object of all keys Let's create an object from Dog class.
in the dictionary. class Dog:
• Example: sound = "bark"
stu = {"roll": 101, "name": "Ana"} dog1 = Dog() # Creating object from class
print([Link]()) # Output: dict_keys(['roll', print([Link]) # Accessing the class
'name']) Output
Other useful functions: items() (key–value bark
pairs), values() (all Explanation: sound attribute is a class
values), update() (merge/add data), attribute. It is shared across all instances of
and pop() (remove by key). Dog class, so can be directly accessed through
instance dog1.

28
[Link] basic dictionary operations. You can update as necessary—data in
Describe any four with examples. dictionaries is always changeable unless you
Dictionaries in Python are powerful, flexible use keys that can't be changed (immutable
containers that hold key-value pairs. Let’s types).
look at four fundamental operations you’ll use 4. Removing a Key-Value Pair
regularly, each with clear explanations and You have several ways to remove data:
practical examples. • del keyword: deletes by key
1. Adding a Key-Value Pair • .pop() method: removes by key and
You can add new data to a dictionary by returns its value
assigning a value to a new key. This operation my_dict = {'name': 'Alice', 'age': 35,
is simple and happens instantly: 'profession': 'Doctor'}
my_dict = {'name': 'Alice', 'age': 35} del my_dict['profession'] # Using del
my_dict['profession'] = 'Doctor' # Add new print(my_dict)
key 'profession' age_value = my_dict.pop('age') # Using
print(my_dict) pop()
Output: print('Removed age:', age_value)
{'name': 'Alice', 'age': 35, 'profession': print(my_dict)
'Doctor'} Output:
Adding is just as easy as writing to any key— {'name': 'Alice', 'age': 35}
the dictionary grows automatically. Removed age: 35
2. Accessing a Value by Key {'name': 'Alice'}
To retrieve a value, use the key inside square Both methods update the dictionary and let
brackets, or safely use .get(), which won’t you control what stays in your data.
crash if the key doesn’t exist:
python 3. What is the use of pass and break
my_dict = {'name': 'Alice', 'age': 35, 'city': statements in Python?
'New York'} In this section, we will learn about pass and
print(my_dict['city']) # Direct access break statements:
print(my_dict.get('country')) # Uses get() to Break Statement:
avoid error The break statement is used to exit or
Output: terminate a loop prematurely. When
New York encountered inside a loop, it immediately
None stops the loop and transfers control to the
The .get() method returns None if a key is statement following the loop.
missing, so it’s useful for error-free lookups. Pass Statement:
3. Modifying a Value The pass statement is a null operation. It does
Just assign a new value to an existing key: nothing when executed. It is used as a
my_dict = {'name': 'Alice', 'age': 35} placeholder when a statement is required
my_dict['age'] = 40 # Change the value for syntactically but you don't want any code to
'age' execute.
print(my_dict)
Output:
{'name': 'Alice', 'age': 40}

29
1. Features of Python something. When the user presses Enter, the
In this section, we will see what are the input is read as a string.
features of Python programming language: Syntax:
1. Free and Open Source variable = input(prompt_message)
Python language is freely available at the Example:
official website and you can download it from # Simple input example
the given download link. Since it is open- name = input("Enter your name: ")
source, this means that source code is also print("Hello, " + name + "!")
available to the public. So you can download # Input with type conversion
it, use it as well as share it. age = int(input("Enter your age: "))
2. Easy to Code print(f"You are {age} years old.")
Python is a high-level programming # Multiple inputs
language. Python is very easy to learn the x = float(input("Enter first number: "))
language as compared to other languages like y = float(input("Enter second number: "))
C, C#, Javascript, Java, etc. It is very easy to result = x + y
code in the Python language and anybody can print(f"The sum is: {result}")
learn Python basics in a few hours or days. It Output:
is also a developer-friendly language. text
3. Easy to Read Enter your name: John
As you will see, learning Python is quite Hello, John!
simple. As was already established, Python's Enter your age: 25
syntax is really straightforward. The code You are 25 years old.
block is defined by the indentations rather Enter first number: 10.5
than by semicolons or brackets. Enter second number: 20.3
4. Object-Oriented Language The sum is: 30.8
One of the key features of Python is Object-
Oriented programming. Python supports 6. What are the properties of a dictionary
object-oriented language and concepts of in Python?
classes, object encapsulation, etc. 1. Unordered (Python 3.6 and
5. Interpreted Language below): Dictionaries were unordered
Python is an interpreted language, which collections, but from Python 3.7+, they
means the source code of a Python program is maintain insertion order.
converted into bytecode that is then executed 2. Key-Value Pairs: Store data as key-value
by the Python virtual machine. Python code is pairs.
executed line by line, which makes debugging 3. Mutable: Can be modified after creation.
easy. 4. Keys must be Unique and
2. Explain the input() function with an Immutable: Dictionary keys cannot be
example duplicated and must be of immutable type.
In this section, we will understand the 5. Values can be Any Type: Values can be of
input() function in Python: any data type and can be duplicated.
The input() function is used to take input from 6. Dynamic: Can grow or shrink in size.
the user. When this function is called, the 7. No Indexing by Position: Elements are
program stops and waits for the user to type accessed by keys, not by numerical indices.

30
10. Explain any two tuple operations with Single element repetition: ('hello', 'hello',
an example 'hello', 'hello')
1. Concatenation Operation: 11. What is the use of + and * operators on
Tuples can be concatenated using tuples?
the + operator, which creates a new tuple + Operator (Concatenation):
containing elements from both tuples. • Used to combine two or more tuples
Example: • Creates a new tuple containing all
python elements from the operands
# Tuple concatenation • Does not modify the original tuples
tuple1 = (1, 2, 3) • Both operands must be tuples
tuple2 = (4, 5, 6) * Operator (Repetition):
result = tuple1 + tuple2 • Used to repeat a tuple specified number
print("After concatenation:", result) of times
# Multiple concatenations • Creates a new tuple with repeated
tuple3 = ('a', 'b') elements
tuple4 = ('c', 'd') • The left operand is the tuple, right
tuple5 = ('e', 'f') operand is an integer
final_tuple = tuple3 + tuple4 + tuple5 • Useful for creating patterns or
print("Multiple concatenations:", final_tuple) initializing tuples with repeated values
Output: Example:
text # Combining + and * operators
After concatenation: (1, 2, 3, 4, 5, 6) part1 = ('begin',) * 2
Multiple concatenations: ('a', 'b', 'c', 'd', 'e', 'f') part2 = ('middle',)
2. Repetition Operation: part3 = ('end',) * 2
Tuples can be repeated using the * operator, result = part1 + part2 + part3
which creates a new tuple with elements print("Combined result:", result)
repeated specified number of times. Output:
Example: Combined result: ('begin', 'begin', 'middle',
python 'end', 'end')
# Tuple repetition
base_tuple = (1, 2, 3) 18. What is the syntax of a constructor in
repeated_tuple = base_tuple * 3 Python?
print("After repetition:", repeated_tuple) Constructor Definition:
A constructor is a special method that is
# Repetition with single element tuple automatically called when an object of a class
single_tuple = ('hello',) is created. In Python, the constructor method
repeated_single = single_tuple * 4 is named __init__.
print("Single element repetition:", Basic Syntax:
repeated_single) python
def __init__(self, parameters):
Output: # Initialization code
text [Link] = values
After repetition: (1, 2, 3, 1, 2, 3, 1, 2, 3)

31
13. What is the use of the try-finally block? • Useful for input validation and error
Definition: propagation
The try-finally block is used to ensure that 15. What is the syntax of an exception block
cleanup code is executed regardless of in Python?
whether an exception occurs or not. The code Basic Syntax:
in the finally block always runs, even if: try:
• The try block completes successfully # Code that might raise an exception
• An exception occurs and is handled risky_operation()
• An exception occurs and is not handled except ExceptionType:
• There's a return, break, or continue # Code to handle the exception
statement handle_error()

Syntax: Example 1: Basic Exception Handling


try: python
# Code that might raise an exception try:
risky_operation() number = int(input("Enter a number: "))
finally: result = 100 / number
# Cleanup code that always executes print(f"Result: {result}")
cleanup_resources() except ValueError:
Common Use Cases: print("Invalid input! Please enter a valid
1. Closing files number.")
2. Releasing network connections except ZeroDivisionError:
3. Releasing locks print("Cannot divide by zero!")
4. Database connection cleanup
5. Resource deallocation 16. Write any two common exceptions in
Python
14. Write the syntax of raise statement and 1. ValueError
explain it • Raised when a function receives an
Syntax: argument of the correct type but
raise exception_class(message) inappropriate value
or • Common in type conversion and
raise exception_instance mathematical operations
or 2. TypeError
raise # Re-raise the current exception • Raised when an operation or function is
applied to an object of inappropriate
Detailed Explanation: type
• Use raise to explicitly throw exceptions • Common when performing operations
• Can raise built-in or custom exceptions between incompatible types
• raise without arguments re-raises the
current exception
• Exception chaining shows the original
cause

32
19. What is a class variable? the module name with the suffix .py added.
Definition: Modules allow you to logically organize your
A class variable is a variable that is shared by Python code and make code reusable.
all instances of a class. Class variables are Characteristics of Modules:
defined within the class construction but • Contain Python code (functions,
outside any class methods. They belong to the classes, variables)
class rather than to any specific instance. • Help in organizing code logically
Characteristics: • Promote code reusability
• Shared across all instances of the class • Prevent naming conflicts
• Defined inside the class but outside • Can be imported into other module
methods 22. How to import a package or module in
• Accessed using class name or instance Python?
• Changing class variable affects all In this section, we will learn different ways
instances to import packages and modules:
Syntax: Basic Import Methods:
python 1. Import Entire Module
class ClassName: import module_name
class_variable = value # This is a class 2. Import Specific Items
variable from module_name import item1, item2
def __init__(self, instance_variable): 3. Import with Alias
self.instance_variable = import module_name as alias_name
instance_variable # This is an instance 4. Import All Items (Not Recommended)
variable from module_name import *
20. Define a class method with an example
Definition: 23. Give an example to demonstrate the use
A class method is a method that is bound to of import statement
the class and not the instance of the class. In this section, we will demonstrate the use
Class methods can access and modify class of import statement with practical
state but not instance state. They are defined examples:
using the @classmethod decorator and Example 1: Basic Import Demonstration
take cls as the first parameter. # Demonstration of different import methods
Syntax: # 1. Import entire math module
class MyClass: import math
@classmethod print("1. Using math module:")
def class_method_name(cls, parameters): print(f" Square root of 16: {[Link](16)}")
# Method implementation print(f" Value of pi: {[Link]}")
pass print(f" Factorial of 5: {[Link](5)}")
21. What is a module in Python?
In this section, we will understand what # 2. Import specific functions
modules are in Python: from math import pow, log10
Definition: print("\n2. Using specific imports:")
A module is a file containing Python print(f" 2 raised to power 3: {pow(2, 3)}")
definitions and statements. The file name is print(f" Log base 10 of 100: {log10(100)}")

33
24. List any three functions of the math • Used internally by other random module
module functions
In this section, we will explore three • Not cryptographically secure
important functions from Python's math (use secrets module for security)
module: 26. What is Tkinter in Python?
1. [Link](x) In this section, we will understand what
• Returns the square root of x Tkinter is and its importance:
• Raises ValueError if x is negative Definition:
2. [Link](x) Tkinter is Python's standard GUI (Graphical
• Returns the factorial of x (x!) User Interface) package. It is a thin object-
• x must be a non-negative integer oriented layer on top of Tcl/Tk. Tkinter is not
3. [Link](x, y) the only GUI toolkit for Python, but it is the
• Returns x raised to the power y most commonly used one and comes bundled
• More precise than the built-in operator for with most Python installations.
floats
• Key Features:
25. What is the use of random() in the • Cross-platform: Works on Windows,
random module? macOS, and Linux
In this section, we will understand the • Native look and feel: Uses the native GUI
random() function and its uses: elements of the OS
• Simple and easy to learn: Compared to
Definition: other GUI toolkits
[Link]() returns a random floating- • Mature and stable: Been part of Python
point number in the range [0.0, 1.0). That is, for a long time
it returns a number between 0 (inclusive) and • Good documentation: Extensive
1 (exclusive). This is the most basic function resources available
in the random module.
27. List and explain geometry management
Key Characteristics: methods in Tkinter
• Returns float between 0.0 and 1.0 In this section, we will explore the three
• Uniform distribution (all numbers equally geometry management methods in
likely) Tkinter:
• No arguments required
• Foundation for other random number Three Geometry Management Methods:
generation 1. pack(): Simple automatic layout
• 2. grid(): Table-like layout with rows and
Key Points about random(): columns
• Foundation for most random number 3. place(): Precise pixel-based layout
generation 3. Configure row and column weights for
• Returns float in [0.0, 1.0) responsiveness
• Uniform distribution 4. Use consistent padding
• Can be scaled to any range

34
30. List any four label options in Tkinter - `<Leave>`: Mouse leaves widget
Labels in Tkinter are used to display text or
images. Key options include: 33. What are the advantages of using
- `text`: The text to display Pandas?
- `bg/background`: Background color Theory:
- `fg/foreground`: Text color 1. Data Structure: Provides DataFrame (2D)
- `font`: Font family, size, and style and Series (1D) structures
- `width/height`: Dimensions in text units or 2. Data Cleaning: Handle missing data,
pixels duplicates, outliers
- `anchor`: Text positioning (n, s, e, w, center)
3. Data Transformation: Reshape, pivot,
- `justify`: Text alignment (left, right, center)
merge datasets
4. Time Series: Built-in support for time series
31. Name any four widgets available in data
Tkinter 5. I/O Operations: Read/write various formats
Tkinter provides various widgets for building (CSV, Excel, SQL, JSON)
GUI applications: 6. Performance: Optimized operations with
- Label: Display text or images NumPy
- Button: Clickable button that triggers 7. Integration: Works well with other data
actions science libraries
- Entry: Single-line text input field
- Text: Multi-line text input area 36. State the features of Keras
- Frame: Container to organize other widgets Keras is a high-level neural networks API that
- Checkbutton: Toggle button for boolean runs on top of TensorFlow. Key features:
choices 1. User-Friendly: Simple, consistent interface
- Radiobutton: Single choice from multiple 2. Modular: Composable building blocks
options 3. Easy Prototyping: Fast experimentation
- Listbox: List of selectable items 4. Convolutional Networks: Built-in support
for CNNs
32. What is the bind() method in Tkinter? 5. Recurrent Networks: Support for RNNs,
The `bind()` method is used to attach event LSTMs, GRUs
handlers to widgets. It connects events (like 6. Multiple Backends: Runs on TensorFlow,
mouse clicks, keyboard presses) to callback Theano, or CNTK
functions. When the specified event occurs on 7. Pre-trained Models: Access to models like
the widget, the bound function is called with VGG, ResNet
an event object containing details about the
event.
Syntax:
[Link](event_pattern,
callback_function)
Common Event Patterns:
- `<Button-1>`: Left mouse click
- `<KeyPress>`: Any key press
- `<Enter>`: Mouse enters widget

35
36

You might also like