0% found this document useful (0 votes)
8 views22 pages

Python Programming Concepts Explained

The document provides a comprehensive overview of Python programming concepts, including the Python interpreter, error types, keyword arguments, tuples, binary files, multiple inheritance, and the Tkinter module for GUI development. It also covers applications of Python in web development, data science, AI, and automation, along with string operations, dictionary functions, and set methods. Additionally, it discusses exception handling, argument passing, queue implementation, file types, polymorphism, encapsulation, layout managers in Tkinter, and creating bar charts using Matplotlib.

Uploaded by

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

Python Programming Concepts Explained

The document provides a comprehensive overview of Python programming concepts, including the Python interpreter, error types, keyword arguments, tuples, binary files, multiple inheritance, and the Tkinter module for GUI development. It also covers applications of Python in web development, data science, AI, and automation, along with string operations, dictionary functions, and set methods. Additionally, it discusses exception handling, argument passing, queue implementation, file types, polymorphism, encapsulation, layout managers in Tkinter, and creating bar charts using Matplotlib.

Uploaded by

Veerabhadra Pura
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Solved QP

Dec Jan 2024/2025


Section - A

1) What is a Python Interpreter?

 A Python interpreter is a program that reads and executes Python code line by line,
rather than compiling the entire program into machine code at once.

 It serves as an intermediary that converts your human-readable Python code into


intermediate bytecode that the computer's processor can understand and run.

2) What is the use of the indentation feature in Python?

 In Python, indentation is used to define the scope and structure of code blocks (like
those inside loops, functions, or if-statements) instead of using curly braces {}.

 It enforces a standardized, readable coding style, as the interpreter will throw an


error if the spacing is inconsistent or incorrect.

3) What is an Error? Mention the types of Errors.

 An error is a flaw or "bug" in a program that prevents it from executing successfully


or causes it to produce incorrect results.

 The three main types of errors are: Syntax Errors (incorrect code grammar), Runtime
Errors (problems that occur while the program is running, like dividing by zero), and
Logical Errors (the code runs but gives the wrong output).

4) What are keyword arguments? Give an example.

 Keyword arguments are arguments passed to a function by explicitly stating the


parameter name followed by an equals sign and the value (e.g., parameter_name =
value).

 They allow you to pass arguments in any order, making the function call more
readable.

o Example: def greet(name, age): ... can be called as greet(age=25,


name="John").

5) What is a tuple in python?

 A tuple is a built-in data type used to store a collection of items in a single variable,
defined by placing elements inside parentheses ().

 Tuples are immutable, meaning once they are created, their elements cannot be
changed, added, or removed.
6) Write any two similarities of List and Tuple.

 Ordered Sequences: Both lists and tuples maintain the order of elements based on
their insertion.

 Indexing and Slicing: Both allow you to access individual elements using their index
(e.g., item[0]) and support slicing to extract a range of elements.

7) What is a Binary file? Give example.

 A binary file stores data as a sequence of bytes that is not human-readable; it


requires specific software to interpret the data correctly.

 These files are used for complex data like media or compiled code.

o Examples: Image files (.png, .jpg), audio files (.mp3), or executable files (.exe).

8) What is Multiple Inheritance?

 Multiple inheritance is an Object-Oriented Programming feature where a child class


is derived from more than one base (parent) class.

 This allows the child class to inherit and combine attributes and methods from
multiple parent classes.

9) What is Tkinter Module?

 Tkinter is Python's standard, built-in library used for creating Graphical User
Interfaces (GUIs) for desktop applications.

 It provides a set of tools and "widgets" like buttons, labels, menus, and text boxes to
build interactive windows easily.

SECTION – B

10) Explain the applications of Python.

 Web Development: Python is widely used for server-side web development through
powerful frameworks like Django and Flask, which allow developers to build scalable
and secure web applications quickly.

 Data Science and Analysis: With libraries such as Pandas, NumPy, and Matplotlib,
Python is the leading language for processing large datasets, performing statistical
analysis, and creating data visualizations.

 Artificial Intelligence and Machine Learning: Python provides specialized libraries


like TensorFlow, Keras, and Scikit-learn, making it the industry standard for
developing AI models, neural networks, and predictive algorithms.
 Automation and Scripting: Python is frequently used to write scripts that automate
repetitive tasks, such as file management, web scraping (using BeautifulSoup), and
system administration.

11) Explain string operations with an example.

 Concatenation (+): This operation joins two or more strings together to form a single
string.

o Example: "Hello" + " World" results in "Hello World".

 Repetition (*): This allows a string to be repeated a specified number of times.

o Example: "Hi" * 3 results in "HiHiHi".

 Slicing ([ ]): Slicing is used to extract a specific part (substring) of a string by defining
a start and end index.

o Example: text = "Python"; text[0:2] results in "Py".

 Membership Testing (in / not in): These operators check if a specific character or
substring exists within a string, returning a Boolean value.

o Example: "Py" in "Python" returns True.

12) Explain Built-in functions on Dictionaries.

 len(dict): Returns the total number of key-value pairs stored in the dictionary.

 keys(): Returns a view object containing all the keys present in the dictionary.

 values(): Returns a view object containing all the values associated with the keys in
the dictionary.

 items(): Returns a view object consisting of tuples, where each tuple is a (key, value)
pair.

 get(key): Safely retrieves the value of a specific key. If the key does not exist, it
returns None instead of raising an error.

 update(another_dict): Merges the dictionary with another dictionary or an iterable


of key-value pairs, overwriting existing keys.

13) Explain any 6 set methods with example.


 add(): Adds a single element to the set. If the element is already present, the set
remains unchanged.

o Example: my_set.add(5)

 update(): Adds multiple elements (from a list or another set) to the current set.

o Example: my_set.update([1, 2, 3])

 remove(): Deletes a specified element from the set. It raises a KeyError if the
element is not found.

o Example: my_set.remove(2)

 discard(): Also deletes a specified element but does not raise an error if the element
is missing.

o Example: my_set.discard(10)

 union(): Returns a new set containing all unique elements from two or more sets.

o Example: [Link](set2)

 intersection(): Returns a new set containing only the elements that are common to
both sets.

o Example: [Link](set2)

14) Explain Tuple methods Count(), index() with example.

 count() Definition: This method returns the number of times a specified value occurs
within the tuple.

o Example: If tup = (1, 2, 3, 2, 2), then [Link](2) will return 3.

 index() Definition: This method finds the first occurrence of a specified value and
returns its index position.

o Example: If tup = ('a', 'b', 'c'), then [Link]('b') will return 1.

 Immutability Context: Because tuples are immutable, they only have these two built-
in methods; they lack methods like append() or sort() which would change the data.

 Error Handling: If the index() method is called for a value that does not exist in the
tuple, Python will raise a ValueError.

15) Explain any 5 operations on Dataframes with example.


 head(n): Displays the first n rows of the Dataframe, which is useful for quickly
inspecting the data structure.

o Example: [Link](5)

 describe(): Generates descriptive statistics for numerical columns, such as mean,


standard deviation, min, and max values.

o Example: [Link]()

 drop(): Used to remove rows or columns from the Dataframe by specifying labels.

o Example: [Link](columns=['Age'])

 Filtering: Allows selection of rows based on specific conditions.

o Example: df[df['Salary'] > 50000]

 sort_values(): Sorts the Dataframe based on the values of one or more specified
columns.

o Example: df.sort_values(by='Name', ascending=True)

SECTION — C

16) a) Explain for loop in python with example.

 Definition: The for loop in Python is used for iterating over a sequence (such as a list,
tuple, dictionary, set, or string).

 Mechanism: It executes a block of code repeatedly for each item present in the
sequence in the order they appear.

 Range Function: It is frequently used with the range() function to iterate a specific
number of times.

 Syntax: for item in sequence: {code block}.

 Example:

Python

fruits = ["apple", "banana", "cherry"]

for x in fruits:

print(x)

16) b) Explain the features of Python.

 Simple and Easy to Learn: Python has a clean, readable syntax that closely resembles
the English language, making it accessible for beginners.
 Interpreted Language: Python code is executed line by line, which makes debugging
easier and eliminates the need for a separate compilation step.

 High-Level Language: Developers don't need to manage low-level details like


memory management or CPU architecture, as Python handles these automatically.

 Large Standard Library: Python comes with a vast library of pre-written code for
tasks like web development, data analysis, and file manipulation.

17) a) Explain exception handling with an example.

 Purpose: Exception handling is used to manage runtime errors so that the program
doesn't crash unexpectedly when an error occurs.

 Try Block: The try block contains the code that might raise an error or "exception."

 Except Block: The except block contains the code that runs only if an error occurs in
the try block.

 Finally/Else: The finally block runs regardless of an error, and the else block runs only
if no error occurred.

 Example:

Python

try:

num = 10 / 0

except ZeroDivisionError:

print("You cannot divide by zero!")

17) b) Explain passing arguments in Python with example.

 Positional Arguments: Arguments that are passed to a function based on their order
in the function call.

 Keyword Arguments: Arguments passed by explicitly naming the parameter (e.g.,


name="Alice"), allowing them to be out of order.

 Default Arguments: Parameters that take a predefined value if no argument is


provided by the caller.

 Variable-length Arguments: Using *args for a variable number of positional


arguments or **kwargs for keyword arguments.

 Example:
Python

def greet(name, msg="Hello"):

print(msg, name)

greet("John") # Uses default "Hello"

greet(msg="Hi", name="Sara") # Keyword arguments

18) a) Explain implementation of queue using list with an example.

 Principle: A Queue follows the FIFO (First-In-First-Out) principle, where the first
element added is the first one to be removed.

 Enqueue: Adding an element to the end of the queue is done using the .append()
method.

 Dequeue: Removing an element from the front of the queue is done using .pop(0).

 Efficiency Note: While lists can act as queues, using pop(0) is slow for large lists;
[Link] is preferred for professional use.

 Example:

Python

queue = []

[Link]("A") # Enqueue

[Link]("B")

print([Link](0)) # Dequeue - Output: "A"

18) b) Explain built-in functions on Tuples.

 len(tuple): Returns the total number of elements present in the tuple.

 max(tuple) / min(tuple): Returns the largest and smallest items in the tuple,
respectively.

 sum(tuple): Returns the arithmetic sum of all numeric elements in the tuple.

 tuple(iterable): Converts an iterable object (like a list or string) into a new tuple.

19) a) Explain file types with example.


 Text Files: These store data as plain text (strings). They are human-readable and use
standard character encoding like UTF-8. Example: .txt, .py, .csv.

 Binary Files: These store data in bytes (0s and 1s) and are not readable by human
text editors. Example: .jpg, .mp3, .exe.

 Access Modes: Text files are opened using 'r' or 'w', while binary files require 'rb' or
'wb'.

 End-of-line: Text files automatically handle line endings (\n), whereas binary files
treat all data as raw bytes without interpretation.

19) b) Explain polymorphism and encapsulation with an example.

 Polymorphism: The ability for different classes to be treated as instances of the same
general class through the same interface (e.g., different objects having the same
method name like speak()).

 Encapsulation: The practice of bundling data (attributes) and methods into a single
unit (class) and restricting direct access to some of the object's components (using
private variables).

 Information Hiding: Encapsulation protects an object's internal state from outside


interference.

 Example:

Python

class Animal:

def __init__(self):

self.__id = 101 # Encapsulation (private)

def speak(self): pass # Polymorphism base

class Dog(Animal):

def speak(self): print("Woof")

20) a) Explain the place Layout Manager. Write the commonly used parameters of the
place() method.

 Definition: The place() manager allows you to position widgets at specific absolute or
relative coordinates within a window.
 Coordinate System: It uses X and Y coordinates, where (0,0) is the top-left corner of
the parent container.

 Parameters (x, y): These specify the absolute horizontal and vertical offset in pixels.

 Parameters (relx, rely): These specify the relative position as a float between 0.0 and
1.0 (percentage of the parent size).

 Parameters (width, height): Specifies the exact size of the widget in pixels.

 Parameter (anchor): Determines which part of the widget is placed at the given
coordinates (e.g., 'center', 'nw').

20) b) Explain the creation of Bar Chart using Matplotlib Library.

 Purpose: A bar chart is used to compare data across different categories.

 Function: Use [Link](x, height) where x is the category labels and height is the
values.

 Customization: You can add labels using [Link](), [Link](), and a title using
[Link]().

 Example:

Python

import [Link] as plt

langs = ['C', 'Python', 'Java']

students = [23, 45, 12]

[Link](langs, students)

[Link]()
Feb/March 2024
SECTION – A

1) What is Python IDLE?

 Definition: IDLE (Integrated Development and Learning Environment) is the default


integrated development environment provided with the standard Python installation.

 Components: It features a multi-window text editor with syntax highlighting and an


interactive Python shell for immediate code execution.

 Key Features: It includes basic debugging tools, such as call stacks and breakpoints,
to help developers find and fix errors in their scripts.

 Purpose: It is designed to be a lightweight and simple tool specifically tailored for


beginners to learn the Python language easily.

2) What is Statement in Python?

 Definition: A statement is a complete instruction that the Python interpreter can


execute to perform a specific action or command.

 Execution Flow: Statements generally control the flow of a program, such as


assigning values, looping through data, or making decisions.

 Types: Common examples include assignment statements (e.g., x = 10), conditional


statements (if-else), and loop statements (for, while).

 Contrast: Unlike expressions, which always evaluate to a specific value, a statement


represents a command that changes the state of the program.

3) What is an exception handling?

 Mechanism: Exception handling is a process used to manage runtime errors


(exceptions) so that a program can continue running or shut down gracefully.

 The Blocks: It primarily uses the try block to test a block of code and the except block
to handle any errors that occur.

 Additional Control: It also uses the finally block for code that must execute
regardless of an error and the else block for code that runs only if no error occurs.

 Benefit: It prevents programs from crashing unexpectedly and allows developers to


provide user-friendly error messages instead of technical stack traces.

4) What are format specifiers? Give an example.

 Definition: Format specifiers are special characters used in string formatting to act as
placeholders for values within a string.
 Function: They define how data types (like integers, floats, or strings) should be
converted and displayed when printed or stored.

 Syntax: They are typically used with the % operator or within the .format() method
to map variables to specific locations in a string.

 Example: In the code print("Score: %d" % 95), the %d is a format specifier indicating
that a decimal integer should be placed there.

5) What is a dictionary?

 Data Structure: A dictionary is a built-in Python data type that stores data in
unordered, mutable collections of key-value pairs.

 Key Rules: Each key in a dictionary must be unique and immutable (like a string,
number, or tuple), while the values can be of any data type.

 Syntax: Dictionaries are defined using curly braces {} with keys and values separated
by colons, such as {"name": "John", "age": 25}.

 Access: They are highly efficient for data retrieval because you can access a value
instantly if you know its corresponding key.

6) What is a list in python?

 Definition: A list is a mutable, ordered sequence of elements that allows you to store
multiple items (even of different types) in a single variable.

 Indexing: Lists use zero-based indexing, meaning the first element is at index 0, the
second at index 1, and so on.

 Syntax: They are defined by placing comma-separated values inside square brackets
[].

 Flexibility: Because lists are mutable, you can change, add, or remove elements after
the list has been created using methods like append() or pop().

7) What is object oriented programming?

 Paradigm: Object-Oriented Programming (OOP) is a programming model based on


the concept of "objects," which can contain both data and code.

 Classes and Objects: It uses "classes" as blueprints to create "objects," which are
specific instances of those classes with their own data.

 Core Principles: The four main pillars of OOP are Encapsulation, Inheritance,
Polymorphism, and Abstraction.

 Advantages: It promotes code reusability, modularity, and easier maintenance by


organizing code into self-contained logical units.
8) What is operator overloading in python?

 Concept: Operator overloading allows a single operator to perform different tasks


based on the data types of the objects it is interacting with.

 Example: The + operator is overloaded in Python because it adds two integers but
concatenates (joins) two strings.

 Implementation: It is achieved by defining special "magic" or "dunder" methods (like


__add__ or __mul__) within a class to define custom behavior.

 Benefit: It makes custom objects behave like built-in types, making the code more
intuitive and readable.

9) What is SQLite3 module?

 Definition: The sqlite3 module is a built-in Python library that provides a standard
interface for interacting with SQLite relational databases.

 Serverless: It is unique because it allows for a disk-based database that doesn't


require a separate server process to run.

 Integration: It allows developers to use standard SQL commands (like SELECT, INSERT,
CREATE) directly within Python code.

 Use Cases: It is widely used for local data storage in desktop applications, mobile
apps, and for prototyping more complex database systems.

SECTION B

10) Explain different types of Data types in Python.

 Numeric Types: Includes int (whole numbers), float (decimal numbers), and complex
(numbers with real and imaginary parts).

 Sequence Types: Includes str (text), list (mutable collections), and tuple (immutable
collections).

 Mapping Type: The dict (dictionary) type, which stores data in key-value pairs for fast
retrieval.

 Set Types: Includes set (unordered collection of unique items) and frozenset
(immutable version of a set).

11) Explain passing arguments in Python with example.

 Positional Arguments: The most common type, where values are assigned to
parameters based on the order they are provided.

 Default Arguments: Parameters that take a pre-defined value if no argument is


provided during the function call.
 Variable-length Arguments: Using *args for a variable number of positional
arguments and **kwargs for a variable number of keyword arguments.

 Example:

Python

def power(base, exp=2): # exp has a default value

return base ** exp

print(power(5)) # Uses default (25)

print(power(5, 3)) # Overrides default (125)

12) Explain built-in functions on tuples.

 len(): Returns the total number of elements present in the tuple.

 max() and min(): These find and return the largest and smallest values within the
tuple, respectively (provided the data types are comparable).

 tuple(): A constructor function used to convert other sequences (like lists or strings)
into a tuple.

 sum(): Calculates the arithmetic total of all numeric elements stored inside the tuple.

13) Explain any 3 set methods with example.

 add(): Adds a single element to the set. If the element already exists, the set remains
unchanged.

o Example: my_set.add(10)

 union(): Returns a new set containing all unique elements from both sets involved in
the operation.

o Example: [Link](set2)

 remove() / discard(): Used to delete an element. remove() raises an error if the item
is missing, while discard() does not.

o Example: my_set.remove("Apple")

 intersection(): Returns only the elements that are common to both sets.

14) What is an inheritance? Explain multiple inheritance and multipath inheritance with
example.

 Inheritance: A mechanism where a "child" class acquires the properties and methods
of a "parent" class, promoting code reuse.
 Multiple Inheritance: A class inherits from two or more distinct parent classes (e.g.,
class Child(Parent1, Parent2)).

 Multipath Inheritance: Occurs when a child class inherits from two parent classes,
both of which share a common grandparent class.

 Example (Multiple):

Python

class Flyer: pass

class Swimmer: pass

class Duck(Flyer, Swimmer): pass # Inherits from both

15) Write a program to draw pie chart.

To draw a pie chart in Python, we typically use the matplotlib library:

Python

import [Link] as plt

# 1. Prepare Data

labels = ['Python', 'Java', 'C++', 'Ruby']

sizes = [45, 30, 15, 10]

colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']

# 2. Plotting

[Link](sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140)

# 3. Formatting

[Link]('equal') # Ensures pie is a circle

[Link]("Programming Language Popularity")

# 4. Display

[Link]()

SECTION — C (8 Marks Each / 4 Marks per sub-question)


16a) Explain for loop in python with example.

 Purpose: Used to iterate over a sequence (list, tuple, string, or range) and execute
code for each item.

 Syntax: Uses the for item in sequence: structure.

 range(): Commonly used with the range() function to repeat an action a specific
number of times.

 Example:

Python

for i in range(3):

print("Hello", i)

16b) Explain break and continue statements with example in python.

 Break: Immediately terminates the current loop and resumes execution at the next
statement after the loop.

 Continue: Skips the remaining code inside the current loop iteration and moves to
the next item in the sequence.

 Control Flow: Both are used inside loops to modify the default behavior based on
specific conditions.

 Example:

Python

for i in range(5):

if i == 2: continue # Skips 2

if i == 4: break # Stops at 4

print(i)

17a) Explain types of errors with example.

 Syntax Error: Incorrect grammar (e.g., if x = 5: instead of ==).

 Name Error: Using a variable that hasn't been defined yet.

 Type Error: Performing an operation on an incompatible data type (e.g., adding a


string to an integer).

 Index Error: Trying to access a list or tuple index that is out of range.

17b) Explain basic string operations with an example.


 Concatenation: Joining two strings together using the + operator.

 Repetition: Repeating a string multiple times using the * operator.

 Slicing: Extracting a portion of a string using string[start:end].

 Membership: Checking if a substring exists within a string using the in operator.

 Example: "Hello" + " World" results in "Hello World".

18a) Explain Built-in functions on dictionaries.

 keys(): Returns a view object containing all the keys in the dictionary.

 values(): Returns a view object containing all the values in the dictionary.

 items(): Returns a list of tuples, where each tuple is a (key, value) pair.

 get(key): Safely retrieves the value of a key; returns None instead of an error if the
key is missing.

18b) Explain Tuple methods: count() and index() with example.

 count(): Returns the number of times a specific value appears in the tuple.

 index(): Searches for a specific value and returns the index of its first occurrence.

 Errors: index() will raise a ValueError if the item is not present.

 Example: t = (1, 2, 2, 3); [Link](2) returns 2; [Link](3) returns 3.

19a) Explain file types with example.

 Text Files: Store data as plain text strings (e.g., .txt, .py, .csv). They are human-
readable.

 Binary Files: Store data as bytes (e.g., .png, .mp3). They require special software to
read.

 Access Modes: Text files are usually opened in 'r' or 'w', while binary files use 'rb' or
'wb'.

 Line Endings: Text files interpret line endings (\n), whereas binary files treat them as
raw data.

19b) Explain polymorphism with example.

 Definition: The ability for different objects or functions to behave differently based
on the data type or class they are acting upon.

 Operator Polymorphism: The + operator adds numbers but concatenates strings.


 Method Overriding: A child class provides a specific implementation of a method
that is already defined in its parent class.

 Example: A speak() method in a Dog class prints "Woof", while in a Cat class, it prints
"Meow".

20a) Explain the place layout manager. Write the commonly used parameters of the
place() method.

 Definition: The place() manager allows you to position widgets at specific x and y
coordinates within a window.

 Absolute vs Relative: It supports both absolute pixels and relative percentages of the
window size.

 Parameter x, y: Specifies the exact horizontal and vertical offset in pixels.

 Parameter anchor: Determines which part of the widget (e.g., NW, Center) is
positioned at the coordinates.

20b) Explain Operations on Tables Using Python SQLite Module with example.

 Connection: Use [Link]() to open a database file.

 Cursor: Create a cursor object to execute SQL commands.

 Execution: Use [Link]() to run commands like CREATE TABLE, INSERT, or


SELECT.

 Commit: Use [Link]() to save changes to the database permanently.

 Example:

Python

import sqlite3

conn = [Link]('[Link]')

curr = [Link]()

[Link]("CREATE TABLE Users (id INT, name TEXT)")

[Link]()

Extra Questions
1) Explain common Dictionary Operations with examples.

 Accessing and Modifying: Values are accessed using their keys in square brackets.
You can add a new key-value pair or update an existing one using the assignment
operator.
 The del Statement: Used to remove a specific entry. For example, del student["age"]
removes the key "age".

 The pop() Method: Removes the item with the specified key name and returns the
value of the removed item.

 Dictionary Views: Use keys() to get all keys, values() for all values, and items() to get
all key-value pairs as a list of tuples.

2) How do you create a Histogram in Python? (With Code)

 Purpose: Histograms represent the frequency distribution of a continuous variable.

 Implementation: We use the [Link]() function from the [Link] library.

 Customization: The bins parameter defines how many intervals the data should be
split into.

 Code Example:

Python

import [Link] as plt

data = [1, 2, 2, 3, 3, 3, 4, 4, 5, 10, 12, 15]

[Link](data, bins=5, color='skyblue', edgecolor='black')

[Link]('Values')

[Link]('Frequency')

[Link]('Sample Histogram')

[Link]()

3) Explain how to create a Line Chart using Matplotlib. (With Code)

 Core Function: The [Link]() function connects data points with a line to show trends
over time or categories.

 Visual Styling: You can specify markers (like 'o' for dots) and line styles (like '--' for
dashed lines).

 Labeling: Essential components include [Link](), [Link](), and [Link]().

 Code Example:

Python
import [Link] as plt

x = [1, 2, 3, 4, 5]

y = [10, 25, 15, 30, 20]

[Link](x, y, marker='o', linestyle='-', color='red', label='Growth')

[Link]('Sales Trend Over Time')

[Link]()

[Link]()

4) How do you implement a Stack using a List? (With Code)

 Principle: A Stack follows the LIFO (Last-In-First-Out) principle.

 Push & Pop: We use .append() to push an element to the top and .pop() (no index) to
remove the topmost element.

 Utility Methods: Use len(stack) == 0 to check for underflow (empty stack) and stack[-
1] to "peek" at the top element.

 Code Example:

Python

stack = []

# Push operation

[Link](10)

[Link](20)

print("Stack after push:", stack)

# Pop operation

if len(stack) > 0:

top_element = [Link]()

print("Popped element:", top_element)


print("Final Stack:", stack)

5) Write a program to append data to a file. (With Code)

 Append Mode: You must open the file using the 'a' mode. This places the cursor at
the end of the file.

 File Creation: If the file does not exist, opening it in 'a' mode will create a new one.

 Safety: Using the with statement ensures the file is automatically closed, preventing
data corruption.

 Code Example:

Python

content_to_add = "\nThis is a new line added to the file."

# 'a' stands for append

with open("[Link]", "a") as file:

[Link](content_to_add)

print("Data appended successfully.")

6) What is Single Inheritance?

 Definition: A child class inherits from exactly one parent class.

 Access: The child class gets access to all public and protected attributes and methods
of the parent.

 Usage: It is the simplest and most common form of inheritance.

 Example: class Dog(Animal): where Dog is the child and Animal is the parent.

7) Explain Hierarchical Inheritance.

 Structure: A single parent class serves as the base for multiple child classes.

 Feature Sharing: All child classes inherit common features from the same root but
can have their own unique methods.

 Visual: It looks like an inverted tree.

 Example: class Car(Vehicle): and class Bike(Vehicle):. Both inherit from Vehicle.
8) What is Hybrid Inheritance?

 Composition: It is a combination of two or more types of inheritance (e.g., Multiple +


Hierarchical).

 Complexity: Used to model real-world relationships where a single type of


inheritance isn't enough.

 Diamond Problem: It can lead to ambiguity, which Python solves using Method
Resolution Order (MRO).

 Example: A class structure that involves both multi-level and multiple inheritance
paths.

9) Compare List, Tuple, and Set.

 Mutability: Lists and Sets are mutable (changeable); Tuples are immutable.

 Duplicates: Lists and Tuples allow duplicates; Sets only store unique items.

 Ordering: Lists and Tuples are ordered; Sets are unordered and unindexed.

 Syntax: List [], Tuple (), Set {}.

10) Explain Logical Operators in Python.

 and: Returns True if both conditions are True.

 or: Returns True if at least one condition is True.

 not: Reverses the boolean value (True becomes False).

 Context: Typically used in if statements to combine multiple requirements.

11) Difference between append() and extend() in Lists.

 append(): Adds the entire object as a single new element at the end.

 extend(): Iterates through an iterable and adds each of its elements individually.

 Size Change: Append adds 1 to the length; extend adds n to the length.

 Example: [1].append([2,3]) -> [1, [2,3]]; [1].extend([2,3]) -> [1, 2, 3].

12) What are Arithmetic Operators in Python?

 Basic: +, -, *, / for addition, subtraction, multiplication, and division.

 Modulus (%): Returns the remainder (e.g., 7 % 2 is 1).

 Floor Division (//): Returns the quotient as a whole number (e.g., 7 // 2 is 3).

 Exponent (**): Calculates power (e.g., 2 ** 3 is 8).


13) What is the is vs == operator?

 ==: Checks for value equality (Do these two things have the same contents?).

 is: Checks for identity (Are these two variables pointing to the exact same memory
location?).

 Data Types: is is often used to check against None.

 Example: Two separate lists with the same numbers are == but not is.

14) Components of a Class.

 Attributes: Variables that store data for the object.

 Methods: Functions that define what the object can do.

 Constructor (__init__): A special method used to initialize attributes.

 self: A reference to the current instance of the class.

15) What are Python Comments?

 Single Line: Defined using the # symbol.

 Docstrings: Multi-line strings using """ """ used for documentation.

 Purpose: To explain code logic for better maintainability.

 Execution: Comments are completely ignored by the Python interpreter.

You might also like