0% found this document useful (0 votes)
5 views25 pages

Python Special Operators and Data Types

The document discusses various Python concepts including special operators, differences between lists and NumPy arrays, functions of the time module, class variables, geometry management methods in Tkinter, the bind method, Seaborn, common exceptions, advantages of pandas, class and object creation, and exception handling. It also covers the math and cmath modules, built-in dictionary functions, and features of Pandas. Additionally, it explains inheritance in Python and principles of Keras.
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)
5 views25 pages

Python Special Operators and Data Types

The document discusses various Python concepts including special operators, differences between lists and NumPy arrays, functions of the time module, class variables, geometry management methods in Tkinter, the bind method, Seaborn, common exceptions, advantages of pandas, class and object creation, and exception handling. It also covers the math and cmath modules, built-in dictionary functions, and features of Pandas. Additionally, it explains inheritance in Python and principles of Keras.
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

a) What are special operators in Python?

Ans-In Python, special operators are operators that perform specific tasks apart from normal
arithmetic or logical operations. These operators are mainly used to check object identity and
membership. Python provides two types of special operators:

1. Identity Operators
Identity operators are used to compare the memory location of two objects.
They check whether two variables refer to the same object (not just equal values).

There are two identity operators:

(i) is operator

 Returns True if both operands refer to the same object in memory.


 Used for comparison of object identity, not values.

(ii) is not operator

 Returns True if both operands do not refer to the same object.

2. Membership Operators
Membership operators are used to test whether a value or variable is present in a sequence such
as list, tuple, string, dictionary, or set.

There are two membership operators:

(i) in operator

 Returns True if the specified value is present in the sequence.

(ii) not in operator

 Returns True if the value is not present in the sequence.

b) Difference between Python List and


NumPy Array
c) Data Type Support
o List: Can store elements of different data types.
o NumPy Array: Stores only one data type (homogeneous).
2. Performance
o List: Slower for numerical operations.
o NumPy Array: Much faster due to optimized C-based backend.
3. Memory Usage
o List: Consumes more memory.
o NumPy Array: Uses less memory (compact data storage).
4. Mathematical Operations
o List: Does not support element-wise mathematical operations.
o NumPy Array: Supports mathematical and element-wise operations directly.
5. Dimensionality
o List: Mainly 1-dimensional (nested lists required for 2D).
o NumPy Array: Can be 1D, 2D, 3D, or multi-dimensional.
6. Functionality
o List: General-purpose, supports basic operations like append, insert, pop.
o NumPy Array: Supports advanced numerical functions (mean, sum, reshape, dot,
etc.).
7. Indexing and Slicing
o List: Supports basic indexing and slicing only.
o NumPy Array: Offers advanced indexing (boolean, fancy indexing).
8. Use Cases
o List: Used for everyday Python programming and mixed data storage.
o NumPy Array: Used for scientific computing, ML, data analysis.

c) State any four functions of the time module


The time module in Python provides various functions to work with time and date.
Four commonly used functions are:

1. [Link]()

 Returns the current time in seconds since the Unix epoch (January 1, 1970).
 Used for measuring execution time.

Example:

[Link]()
2. [Link](seconds)

 Suspends (pauses) program execution for the given number of seconds.

Example:

[Link](2) # pauses for 2 seconds

3. [Link]()

 Converts a time value (in seconds) into a local time structure (year, month, day,
hour…).

Example:

[Link]([Link]())

4. [Link](format, time_object)

 Converts a time object into a formatted string.

Example:

[Link]("%Y-%m-%d")

Here are the answers for d) to j) — all in clear, exam-oriented form:

d) What is a class variable?


A class variable is a variable that is declared inside a class but outside all methods.
It is shared by all objects of the class.
If one object changes the value, it affects all other objects.

Example:

class Student:
school = "ABC School" # class variable

e) List out Geometry management methods.


In Tkinter (Python GUI), there are three geometry management methods:

1. pack() – Automatically arranges widgets block-wise.


2. grid() – Places widgets in a table-like structure (rows & columns).
3. place() – Allows precise positioning using x and y coordinates.

f) Define term Bind method.


The bind() method in Tkinter is used to bind an event (like mouse click, key press) to a specific
function.

Example:

[Link]("<Button-1>", function_name)

It means: when the user clicks the widget, the function will execute.

g) What is Seaborn?
Seaborn is a Python data visualization library built on top of Matplotlib.
It is used for creating attractive, statistical, and high-level plots like heatmaps, barplots,
pairplots, etc.

h) Write any two common exceptions in


Python.
Two commonly occurring exceptions in Python are:

1. ZeroDivisionError – Raised when dividing a number by zero.


2. ValueError – Raised when the correct data type is given but the value is invalid.

(Others include TypeError, IndexError, KeyError…)


i) What are advantages of pandas?
Advantages of Pandas:

1. Fast and efficient data handling using DataFrame.


2. Easy data cleaning, filtering, and transformation.
3. Supports reading/writing data from CSV, Excel, SQL, JSON, etc.
4. Provides built-in statistical and analytical functions.

j) How to create class and object in Python?


A class is created using the class keyword, and objects are created by calling the class.

Example:

class Student: # class creation


def __init__(self, name):
[Link] = name

obj = Student("Rahul") # object creation

Q2) Attempt any four of the following.

a) Explain math and cmath module in detail.


Python provides two important modules for mathematical operations: math and cmath.
Both are used to perform mathematical calculations, but they differ in the type of numbers they
handle.

1. math Module
The math module in Python provides functions for performing real-number mathematical
operations.
It works only with real (non-complex) numbers and does not support complex numbers.

Key Features of math module

1. Works with integers and floating-point numbers only


2. Provides trigonometric functions
3. Provides logarithmic and exponential functions
4. Provides constants like π (pi) and e
5. Useful for scientific, engineering, and numerical computations

Common math module functions

1. [Link](x)

Returns the square root of a number (only positive numbers).

Example:

import math
[Link](25) # Output: 5.0

2. [Link](x, y)

Returns x raised to the power y.

3. [Link](n)

Returns factorial of n.

4. [Link](), [Link](), [Link]()

Trigonometric functions (in radians).

5. [Link](x, base)

Returns logarithm of x to the specified base.

6. [Link](x)

Returns the smallest integer greater than or equal to x.

7. [Link](x)

Returns the largest integer less than or equal to x.


Important constants in math module

 [Link] → 3.141592…
 math.e → 2.718281…

2. cmath Module
The cmath module is used for mathematical operations involving complex numbers.

Unlike the math module, cmath can directly handle numbers of the form a + bj.

Key Features of cmath module

1. Supports complex numbers


2. Provides trigonometric functions for complex input
3. Provides log, exp, sqrt for complex values
4. Useful in electrical engineering, physics, and advanced mathematics

Here is the detailed, exam-oriented answer for:

b) Explain different data types in Python


Python provides several built-in data types that are used to store different kinds of values. These
data types help in performing various operations efficiently.

Below is a clear and detailed explanation of all major Python data types:

1. Numeric Data Types


These are used to store numbers.

i) int (Integer)

 Stores whole numbers (positive, negative, zero)


 No limit on size

Example:

a = 10
ii) float (Floating-point number)

 Stores decimal numbers

Example:

b = 10.5

iii) complex

 Stores complex numbers of the form a + bj

Example:

c = 3 + 5j

2. Sequence Data Types


i) str (String)

 Represents text data


 Enclosed in single (' '), double (" "), or triple quotes (""" """)

Example:

s = "Hello Python"

ii) list

 Ordered, mutable (changeable) collection


 Can contain mixed data types

Example:

l = [10, "abc", 20.5]

iii) tuple

 Ordered, immutable (cannot be changed)


 Faster than list

Example:

t = (1, 2, 3)
iv) range

 Represents a sequence of numbers


 Often used in loops

Example:

r = range(1, 10)

3. Mapping Data Type


dict (Dictionary)

 Stores key-value pairs


 Unordered, mutable

Example:

d = {"name": "Rahul", "age": 20}

4. Set Data Types


i) set

 Unordered collection of unique items


 Duplicate values not allowed

Example:

s = {1, 2, 3}

ii) frozenset

 Immutable version of a set

Example:

fs = frozenset({1, 2, 3})

5. Boolean Data Type


bool

 Represents True or False values

Example:

flag = True

6. Binary Data Types


Used to store binary data such as images, files, etc.

i) bytes

Immutable sequence of bytes.

ii) bytearray

Mutable version of bytes.

iii) memoryview

Used to access memory of binary data without copying.

Example:

b = bytes([1, 2, 3])
ba = bytearray([1, 2, 3])

Here are the answers for c, d, and e in a clear and exam-oriented form:

c) Explain inheritance in brief with syntax.


Inheritance (Definition)

Inheritance is a core concept of Object-Oriented Programming in Python.


It allows a new class (child class) to acquire the properties and methods of an existing class
(parent class).

This promotes code reusability, extensibility, and organized structure.


Syntax of Inheritance
class ParentClass:
# parent class members
pass

class ChildClass(ParentClass):
# child class members
pass

Example
class Animal:
def sound(self):
print("Animal makes sound")

class Dog(Animal):
def bark(self):
print("Dog barks")

d = Dog()
[Link]() # Inherited from parent
[Link]() # Child class method

d) Explain various types of exception


handling in Python.
Exception handling ensures a program continues to run even when an error occurs.
Python uses try-except blocks to handle exceptions.

1. try-except block

Used to catch and handle exceptions.

try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")

2. try-except-else block

else executes only when no exception occurs.

try:
x = int("10")
except ValueError:
print("Invalid")
else:
print("Conversion successful")

3. try-except-finally block

finally block executes whether exception occurs or not.

try:
f = open("[Link]")
except FileNotFoundError:
print("File not found")
finally:
print("Execution completed")

4. Multiple except blocks

Used to handle more than one type of error.

try:
a = int(input())
except ValueError:
print("Invalid number")
except TypeError:
print("Type error")

5. Raise Statement

Used to manually raise an exception.

raise ValueError("Custom exception")


6. User-defined exceptions

Created using class.

class MyError(Exception):
pass

e) Explain principle of Keras.


Keras is a high-level deep learning framework built on top of TensorFlow.
It is used to build, train, evaluate, and deploy neural networks [Link] of Keras

1. User-friendliness
Keras is designed to be simple, easy to learn, and highly readable.
It allows beginners to build neural networks with minimal code.

2. Modularity

Keras models are made of modular components such as:

 Layers
 Optimizers
 Loss functions
 Activation functions
These can be combined like building blocks.

3. Extensibility

It allows users to create:

 custom layers
 custom models
 custom training loops
Making it highly flexible for researchers.

4. Pythonic Nature

Fully written in Python, following clear and concise coding principles.

5. Runs on Top of TensorFlow

Keras uses TensorFlow as backend, which provides:

 GPU/TPU support
 automatic differentiation
 optimized deep learning operations

6. Fast Prototyping

Keras allows developers to:

 build models quickly


 test ideas faster
 iterate rapidly
This is essential for research and production.
Here is the exam-oriented, clear and detailed answer for:

a) What are built-in dictionary functions in


Python? (with examples)
Python provides several built-in functions and methods to work with dictionaries.
Below are the important dictionary functions/methods along with examples:

1. len()
Returns the number of key–value pairs in the dictionary.

d = {"name": "Raj", "age": 20}


print(len(d)) # Output: 2

2. str()
Returns the dictionary as a string representation.

d = {"a": 10, "b": 20}


print(str(d)) # Output: "{'a': 10, 'b': 20}"

3. type()
Returns the type of the object.

d = {"x": 1, "y": 2}
print(type(d)) # Output: <class 'dict'>

4. dict()
Creates a new dictionary object.

d = dict(name="Riya", age=21)
print(d)
Common Dictionary Methods (Built-in)
5. keys()
Returns all keys of the dictionary.

d = {"a": 1, "b": 2}
print([Link]()) # dict_keys(['a', 'b'])

6. values()
Returns all values.

print([Link]()) # dict_values([1, 2])

7. items()
Returns key-value pairs as tuples.

print([Link]()) # dict_items([('a', 1), ('b', 2)])

8. get(key)
Returns the value for the given key.

d = {"name": "Sam", "age": 22}


print([Link]("age")) # Output: 22

9. update()
Updates dictionary with another dictionary.

d1 = {"a": 1}
d2 = {"b": 2}
[Link](d2)
print(d1) # {'a': 1, 'b': 2}
10. pop(key)
Removes the item with the specified key.

d = {"x": 10, "y": 20}


[Link]("x")
print(d) # {'y': 20}

11. popitem()
Removes and returns the last inserted key-value pair.

d = {"a": 1, "b": 2}
[Link]() # removes ('b', 2)

12. clear()
Removes all items from the dictionary.

d = {"a": 1, "b": 2}
[Link]()
print(d) # {}

13. copy()
Returns a shallow copy of the dictionary.

d1 = {"a": 10}
d2 = [Link]()

14. setdefault(key, default)


Returns the value of the key.
If key does not exist, it inserts the key with the default value.

d = {"name": "John"}
[Link]("age", 25)
print(d) # {'name': 'John', 'age': 25}
Here are the clear, exam-oriented answers for Q3 (b) and (c):

b) Explain features of Pandas in Python.


Pandas is a powerful Python library used for data analysis and data manipulation. It provides
fast, flexible, and expressive structures to handle structured data.

Features of Pandas

1. DataFrame and Series

 Pandas provides Series (1D labeled data) and DataFrame (2D table-like data).
 Easy to create, modify, and analyze structured data.

2. Handling Missing Data

 Pandas offers functions like


isnull(), dropna(), fillna()
to detect and handle missing values.

3. Data Cleaning & Transformation

 Supports powerful operations like filtering, grouping, merging, reshaping, pivoting, etc.

4. Fast and Efficient

 Built on NumPy, giving high performance for large datasets.

5. Data Import and Export

 Can read/write data from/to:


o CSV
o Excel
o JSON
o SQL databases
o HTML tables

6. Label-based Indexing

 Supports indexing using labels with


o .loc[]
o .iloc[]
7. Built-in Statistical Functions

 Provides ready functions like


mean(), sum(), count(), max(), min() etc.

8. Time Series Support

 Specialized tools for time-indexed data, resampling, date conversion, etc.

c) Explain the following with syntax and


example: [Link], [Link]
These methods belong to Tkinter Entry widget (a text input field).

1. [Link]
Purpose

Deletes characters from an Entry widget.

Syntax
[Link](start_index, end_index)

 start_index → starting position (0, 1, 2…)


 end_index → ending position
(END can be used to delete till the end)

Example
from tkinter import *

root = Tk()
e = Entry(root)
[Link]()

[Link](0, "Hello World") # initial text


[Link](0, END) # deletes entire text

[Link]()
2. [Link]
Purpose

Inserts text at a given position in the Entry widget.

Syntax
[Link](index, text)

 index → position where text should be inserted


 text → the string to insert

Example
from tkinter import *

root = Tk()
e = Entry(root)
[Link]()

[Link](0, "Welcome") # inserts at beginning


[Link](7, " User") # inserts after 7th position

[Link]()

d) Write a Python program to find factors of


a given number.
Program
# Program to find factors of a given number

num = int(input("Enter a number: "))

print("Factors of", num, "are:")


for i in range(1, num + 1):
if num % i == 0: # if remainder is zero → i is a factor
print(i)

Explanation
 A number i is a factor of num if num % i == 0.
 The loop checks all numbers from 1 to num.
 Every number that divides perfectly is printed as a factor.

e) Write a Python script to generate


Fibonacci terms using generator function.
Fibonacci Series

A series where
0, 1, 1, 2, 3, 5, 8, ...
each number = sum of previous two numbers.

Program Using Generator Function


# Fibonacci generator function

def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a # produce the next term
a, b = b, a + b # update values

# taking input
terms = int(input("Enter number of Fibonacci terms: "))

print("Fibonacci Series:")
for num in fibonacci(terms):
print(num)

Q4 (a) How to define a function in Python?


Explain with example.
A function in Python is defined using the def keyword.
A function is a block of reusable code that performs a specific task.

Syntax
def function_name(parameters):
statements
return value

Example
def add(a, b):
return a + b

result = add(10, 5)
print("Sum =", result)

Q4 (b) Explain EXCEPT clause with no


exception.
The except clause with no exception is written without specifying an exception type.
It catches all types of exceptions.

Syntax
try:
# risky code
except:
# handles any exception

Example
try:
x = 10 / 0
except:
print("An error occurred!")

This catches any error (ZeroDivisionError, ValueError, etc.).

Q4 (c) Explain IS-A relationship and HAS-A


relationship with example.
1. IS-A Relationship (Inheritance)

Used when one class inherits from another.


Represents a “is a type of” relationship.
Example:

class Animal:
pass

class Dog(Animal): # Dog IS-A Animal


pass

2. HAS-A Relationship (Composition / Containment)

One class contains another class as an object.


Represents a “has a” relationship.

Example:

class Engine:
pass

class Car:
def __init__(self):
[Link] = Engine() # Car HAS-A Engine

Q4 (d) Python program: Check if a key exists


in a dictionary. If exists, replace with another
key/value pair.
Program
my_dict = {"a": 1, "b": 2, "c": 3}

key = input("Enter key to check: ")

if key in my_dict:
print("Key exists! Replacing it...")
new_key = input("Enter new key: ")
new_value = input("Enter new value: ")
my_dict.pop(key) # remove old
my_dict[new_key] = new_value
else:
print("Key not found!")

print("Updated Dictionary:", my_dict)


Q4 (e) Write a Python program to swap the
value of two variables.
Program
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

a, b = b, a

print("After swapping:")
print("a =", a)
print("b =", b)

Below are the Short Notes for Q5 (a, b, c) written in a clear exam-oriented manner:

Q5) Write short notes on:

a) Slicing Dictionaries
Dictionary slicing means extracting a portion (subset) of key–value pairs from an existing
dictionary.
Unlike lists, dictionaries do not support slicing directly because they are unordered
collections.
However, slicing can be done using:

1. Dictionary Comprehension

You can select specific keys and form a new dictionary.

Example:

d = {'a':1, 'b':2, 'c':3, 'd':4}


keys = ['b', 'c']
new_dict = {k: d[k] for k in keys}
print(new_dict) # {'b': 2, 'c': 3}
2. Using list slicing on dictionary keys
d = {'x':10, 'y':20, 'z':30, 'w':40}
sliced = dict(list([Link]())[1:3])
print(sliced) # {'y': 20, 'z': 30}

Use: extracting a part of dictionary for processing, filtering, or converting into smaller chunks.

b) Data Visualization
Data visualization is the process of representing data graphically to identify patterns, trends,
and relationships.
Python provides several libraries to visualize data.

Importance

 Makes data easier to understand


 Helps in decision-making
 Reveals hidden patterns
 Useful for statistical analysis and machine learning

Common Python Libraries

1. Matplotlib – basic plots (line, bar, histogram, scatter, etc.)


2. Seaborn – statistical plots with beautiful themes
3. Plotly – interactive visualizations
4. Pandas Plot – quick plotting directly from DataFrames

Example
import [Link] as plt

x = [1,2,3,4]
y = [10,20,15,25]

[Link](x, y)
[Link]("X-axis")
[Link]("Y-axis")
[Link]("Simple Line Plot")
[Link]()

c) Custom Exception
A custom exception is a user-defined exception created by inheriting from Python’s built-in
Exception class.
It helps handle application-specific errors that are not covered by default exceptions.

Why Custom Exceptions?

 To give meaningful error messages


 To handle errors specific to the application
 To improve debugging and code clarity

Syntax
class MyError(Exception):
pass

Example
class AgeError(Exception):
def __init__(self, msg):
[Link] = msg

def check_age(age):
if age < 18:
raise AgeError("Age must be 18 or above!")
else:
print("Eligible")

try:
check_age(15)
except AgeError as e:
print("Error:", e)

Output:

Error: Age must be 18 or above!

You might also like