Python viva
Python viva
UNIT 1
Identifiers:
Identifiers are names used to identify a variable, function, class, module, or other object in
Python. Here are the rules for creating identifiers:
1. Allowed characters: Identifiers can include letters (a-z, A-Z), digits (0-9), and
underscores (_).
2. Cannot start with a digit: An identifier must start with a letter or an underscore.
3. Case-sensitive: Identifiers are case-sensitive, meaning myVar and myvar are different
identifiers.
4. No special characters: Identifiers cannot contain special characters like @, $, %, etc.
5. Length: There is no explicit limit on the length of identifiers, but they should be
meaningful and concise.
Examples of valid identifiers:
my_variable
data1
_private_var
ClassName
Examples of invalid identifiers:
1st_variable (cannot start with a digit)
my-variable (contains a special character)
class (matches a keyword)
Keywords:
Keywords are reserved words in Python that have a predefined meaning and cannot be used as
identifiers. These keywords define the syntax and structure of the Python language.
Here’s a list of Python keywords (as of Python 3.10):
False , async , await, break , class , None , True .
Statements and expressions:
Statements are instructions that the interpreter executes.
Expressions are combinations of values and operators that produce a new value.
Type conversions :
Built-in Type Conversion Functions
1. int(): Converts a value to an integer.
num_str = "42"
num_int = int(num_str) # Converts string to integer
2. float(): Converts a value to a float.
num_int = 5
num_float = float(num_int) # Converts integer to float
3. str(): Converts a value to a string.
num = 100
num_str = str(num) # Converts integer to string
4. list(): Converts an iterable (like a string or tuple) to a list.
my_tuple = (1, 2, 3)
my_list = list(my_tuple) # Converts tuple to list
5. tuple(): Converts an iterable to a tuple.
my_list = [1, 2, 3]
my_tuple = tuple(my_list) # Converts list to tuple
6. set(): Converts an iterable to a set, removing duplicates.
my_list = [1, 2, 2, 3]
my_set = set(my_list) # Converts list to set
7. dict(): Converts a sequence of key-value pairs into a dictionary.
my_list = [("a", 1), ("b", 2)]
my_dict = dict(my_list) # Converts list of tuples to dictionary
Implicit vs. Explicit Conversion
Implicit Conversion (Coercion): Python automatically converts one data type to another
when necessary.
a = 10 # int
b = 5.5 # float
result = a + b # a is implicitly converted to float
Explicit Conversion: The programmer specifies the conversion using the functions
mentioned above.
a = "10"
b=5
result = int(a) + b # 'a' is explicitly converted to int
Type Conversion Considerations
String to Number: When converting a string to a number, ensure the string is a valid
representation of a number, or a ValueError will occur.
Lists:
A list is a mutable, ordered collection of items. Lists can hold mixed data types, including
integers, strings, other lists, and more. They are defined using square brackets ([...]).
Properties of Lists
1. Mutability: Lists are mutable, meaning you can change, add, or remove items after the
list has been created.
2. Ordered: The items in a list maintain their order, and each item can be accessed using its
index (starting from 0).
3. Heterogeneous: A list can contain items of different data types.
Adding Elements:
append(): Adds an element to the end of the list.
insert(): Inserts an element at a specified position.
extend(): Extends the list by appending elements from another iterable.
Removing Elements:
remove(): Removes the first occurrence of a specified value.
pop(): Removes and returns an element at a specified index (default is the last item).
clear(): Removes all items from the list.
Accessing Elements:
You can use slicing to access a range of items.
sliced_list = my_list[1:4] # Returns items from index 1 to 3
Finding Length:
Use len() to get the number of elements in a list.
Del statement:
The del statement in Python is used to delete objects, including variables, lists, or dictionary
entries. It can help manage memory and clean up unused objects in your code.
x = 10
print(x) # Output: 10
del x
# print(x) # Raises NameError: name 'x' is not defined
UNIT 3
Dictionary:
A dictionary in Python is a mutable, unordered collection that maps unique keys to values. It is
defined using curly braces ({}) or the dict() constructor.
Key Characteristics
Key-Value Pairs: Each entry in a dictionary consists of a key and its associated value.
You can retrieve the value by referencing its key.
Mutable: Dictionaries can be changed after creation, allowing you to add, remove, or
modify entries.
Unordered: The items in a dictionary do not have a defined order. As of Python 3.7,
insertion order is preserved in the sense that keys maintain the order in which they were
added, but this is an implementation detail rather than a language guarantee in earlier
versions.
Unique Keys: Each key in a dictionary must be unique. If a key is reused, the previous
value associated with it will be overwritten.
Creating Dictionaries:
Dictionaries can be created in several ways:
# Using curly braces
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
# Using the dict() constructor
another_dict = dict(name='Bob', age=25, city='Los Angeles')
Dictionary Methods:
Python provides several built-in methods for dictionaries:
dict.keys(): Returns a view object containing the keys of the dictionary.
dict.values(): Returns a view object containing the values of the dictionary.
dict.items(): Returns a view object containing key-value pairs as tuples.
dict.get(key): Returns the value associated with the key or a default value if the key does
not exist.
Use Cases:
Dictionaries are widely used in various scenarios, including:
Storing configuration settings.
Representing data objects (e.g., user profiles).
Implementing lookup tables and caches.
Grouping related data together.
Tuple:
A tuple is a collection that can store multiple items in a single variable. It is defined using
parentheses ((...)) and can contain elements of different data types.
Key Characteristics
Ordered: The elements in a tuple have a defined order, meaning that they can be
accessed using their index (starting from 0).
Immutable: Once a tuple is created, its contents cannot be changed. You cannot add,
remove, or modify elements within a tuple.
Heterogeneous: A tuple can store items of different data types, including integers,
strings, lists, or even other tuples.
Allow Duplicate Elements: Tuples can contain duplicate values, unlike keys in a
dictionary.
A tuple is an immutable, ordered collection of items in Python.
Tuples can store heterogeneous data types and allow duplicate elements.
They are defined using parentheses and provide various operations for access,
concatenation, and slicing.
Tuples are particularly useful for returning multiple values and as keys in dictionaries.
Set:
A set is a collection of items that are unordered and do not allow duplicate values. Sets
are defined using curly braces ({...}) or the set() constructor.
2. Key Characteristics
Unordered: The elements in a set do not have a defined order, which means that the
items cannot be accessed via indexing.
Unique Elements: A set automatically removes duplicate values. If you attempt to add a
duplicate, it will not be included.
Mutable: Sets are mutable, allowing you to add or remove elements after their creation.
Heterogeneous: Sets can store elements of different data types.
Use Cases:
Sets are useful in various scenarios, including:
Removing Duplicates: Quickly remove duplicates from a list.
my_list = [1, 2, 2, 3, 4, 4]
unique_items = set(my_list) # {1, 2, 3, 4}
Membership Testing: Sets provide efficient membership testing, which is faster than
lists.
Mathematical Operations: Easily perform mathematical operations like unions,
intersections, and differences.
A set in Python is an unordered collection of unique, mutable elements.
Sets support various operations, including addition, removal, and mathematical set
operations.
They are versatile and can be used for tasks such as removing duplicates, membership
testing, and more.
Syntax Defined using parentheses (...) Defined using square brackets [...]
Memory
Generally requires less memory Generally requires more memory
Usage
Use Cases Suitable for fixed collections, returning Suitable for dynamic collections,
Feature Tuple List
Syntax Defined using parentheses (...) Defined using curly braces {...}
Zip():-
the zip() function is a built-in function that takes multiple iterable objects (like lists, tuples, or
strings) and combines them into a single iterable of tuples. Each tuple contains elements from the
input iterables that are at the same index.
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
result = zip(list1, list2)
print(list(result)) # Output: [(1, 'a'), (2, 'b'), (3, 'c')]
UNIT 4
Types of Files:
1. Text Files:
o Contain plain text and can be opened and read with a text editor.
o Common extensions: .txt, .csv, .json, .xml.
2. Binary Files:
o Contain data in a format that is not human-readable.
o Common extensions: .bin, .jpg, .png, .exe.
3. Structured Data Files:
o Files that follow a specific format for data storage.
o Examples include .csv for comma-separated values, .json for JSON formatted
data, and .xml for XML formatted data.
4. Creating a Text File
You can create a text file using the built-in open() function in write mode ('w').
You can read a text file using the open() function in read mode ('r').
OOP:
Classes in Python
A class is defined using the class keyword. It can contain attributes (variables) and methods
(functions) that define the behavior of the objects created from the class.
Attributes and Methods
Attributes: These are variables that belong to the class. They hold the state or properties
of an object.
Methods: These are functions defined within the class that describe the behaviors of the
object.
Object: An instance of a class; contains data and methods defined in the class
Constructor method
the constructor method is a special method that is automatically called when an object of a class
is created. It is defined using the __init__ method. The primary purpose of the constructor is to
initialize the object's attributes with the values passed during object creation.
Class Attributes
Class attributes are shared across all instances of a class. They are defined directly within the
class body and belong to the class itself rather than any particular instance. This means that if
you change the value of a class attribute, it will affect all instances of that class unless they have
overridden it with an instance attribute.
Instance (Data) Attributes
Instance attributes are specific to each object created from a class. They are defined within the
constructor method (__init__) using the self keyword. Each instance can have different values
for these attributes, and changes to an instance attribute do not affect other instances.
Encapsulation:
It refers to the bundling of data (attributes) and methods (functions) that operate on that data into
a single unit, or class. In Python, encapsulation is used to restrict direct access to some of an
object's components, which can help prevent unintended interference and misuse of the data.
Data Hiding: By restricting access to certain attributes and methods, you can protect
the integrity of the object's state.
Access Modifiers: Python uses naming conventions to indicate the intended visibility
of attributes and methods:
Public: Attributes and methods that can be accessed from outside the class (default).
Protected: Attributes and methods that should be accessed only within the class and its
subclasses. In Python, this is indicated by a single underscore prefix (_).
Private: Attributes and methods that cannot be accessed from outside the class. This is
indicated by a double underscore prefix (__).
Inheritence:
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class
(child or subclass) to inherit attributes and methods from another class (parent or superclass).
This promotes code reusability and establishes a relationship between classes.
Types of Inheritance
1. Single Inheritance: A subclass inherits from one superclass.
2. Multiple Inheritance: A subclass inherits from multiple superclasses.
3. Multilevel Inheritance: A subclass inherits from a superclass, which itself is a subclass
of another superclass.
4. Hierarchical Inheritance: Multiple subclasses inherit from a single superclass.
5. Hybrid Inheritance: A combination of two or more types of inheritance
Polymorphism:
Method Overriding: Subclasses can provide a specific implementation of a method that is
already defined in the superclass. This allows you to call the same method on different objects
and have each respond in a way that is appropriate to its class.
Duck Typing: In Python, polymorphism is often achieved through "duck typing," which
means that if an object behaves like a certain type (e.g., it has certain methods), it can be treated
as that type, regardless of its actual class.
Class Bird:
def fly(self):
return “Flying high!”
class Airplane:
def fly(self):
return “Taking off!”
def let_it_fly(flyable):
print(flyable.fly())
# Creating instances
sparrow = Bird()
boeing = Airplane()
FUNCTIONAL PROGRAMMING:
First-Class Functions: Functions in Python are first-class citizens, meaning they can be
passed around as arguments, returned from other functions, and assigned to variables.
Higher-Order Functions: These are functions that can take other functions as arguments or
return them as results. Common examples include map(), filter(), and reduce().
Pure Functions: A pure function is a function where the output value is determined only by
its input values, without observable side effects (e.g., modifying a global variable).
Immutability: While Python does allow mutable data types (like lists and dictionaries),
functional programming favors immutable data types (like tuples and frozensets) to prevent state
changes.
Recursion: In functional programming, recursion is often used as a primary mechanism for
iteration instead of loops.
JSON:
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for
humans to read and write and easy for machines to parse and generate. In Python, you can work
with JSON data using the built-in json module, which provides functions for converting between
JSON and Python objects.
Basic Operations with JSON in Python
1. Parsing JSON (Loading JSON Data)
2. Generating JSON (Dumping JSON Data)
3. Working with JSON files
4. JSON is a widely-used format for data interchange.
5. Use json.loads() to parse JSON strings and json.dumps() to generate JSON
strings from Python objects.
6. Use json.load() to read JSON from a file and json.dump() to write JSON to a file.
7. Python's json module supports complex and nested JSON data structures.
XML:
XML (eXtensible Markup Language) is a markup language used to encode documents in a
format that is both human-readable and machine-readable. In Python, you can work with XML
data using several libraries, with the most commonly used being xml.etree.ElementTree for
parsing and creating XML documents.
Basic Operations with XML in Python
1. Parsing XML
2. Creating XML
3. Working with XML Files
Numpy:
Arrays:
The core feature of NumPy is the ndarray (N-dimensional array) object, which is a fast,
flexible container for large data sets in Python. Arrays are similar to lists but are more
efficient for numerical operations.
NumPy arrays can be of any dimension (1D, 2D, 3D, etc.) and can contain elements of
the same data type.
Array Creation:
You can create NumPy arrays using various methods, including:
o np.array(): Convert a list or tuple into an array.
o np.zeros(): Create an array filled with zeros.
o np.ones(): Create an array filled with ones.
o np.arange(): Create an array with a range of values.
o np.linspace(): Create an array with evenly spaced values over a specified interval.
Array Operations:
NumPy supports element-wise operations, meaning you can perform operations on arrays
without the need for explicit loops. This includes arithmetic operations, statistical
functions, and logical operations.
Broadcasting is a feature that allows NumPy to perform operations on arrays of different
shapes.
Indexing and Slicing:
NumPy allows you to access and modify elements of arrays using indexing and slicing
techniques similar to Python lists.
You can also use boolean indexing to filter arrays based on conditions.
Mathematical Functions:
NumPy provides a wide range of mathematical functions, including trigonometric,
statistical, and algebraic functions, which can be applied to arrays.
Linear Algebra:
NumPy includes support for linear algebra operations, such as matrix multiplication,
determinants, eigenvalues, and more.
Integration with Other Libraries:
NumPy is a foundational library for many other scientific computing libraries in Python,
such as SciPy, Pandas, and Matplotlib.
PANDAS:
Data Structures:
Series: A one-dimensional labeled array that can hold any data type. It is similar to a list
or an array but with additional functionalities, such as indexing.
DataFrame: A two-dimensional labeled data structure, similar to a spreadsheet or SQL
table. It consists of rows and columns, where each column can be of a different data type.
DataFrames are the primary structure for data manipulation in Pandas.
Panel: A three-dimensional data structure (though it's less commonly used).
Creating DataFrames:
You can create DataFrames from various data sources, including dictionaries, lists,
NumPy arrays, and CSV files.
Data Indexing and Selection:
Pandas provides powerful indexing capabilities for selecting and filtering data using
labels, positions, and boolean conditions.
Data Manipulation:
Pandas allows you to perform a wide range of data manipulation operations, including
adding and dropping columns, sorting, grouping, merging, and reshaping data.
Data Cleaning:
Functions for handling missing data, such as filling, dropping, or interpolating missing
values.
String operations and type conversions for data cleaning.
Data Analysis:
Pandas offers various built-in functions for descriptive statistics and data aggregation,
making it easier to analyze data.
Input and Output:
Reading from and writing to various file formats, such as CSV, Excel, JSON, SQL
databases, and more.
Time Series Analysis:
Support for working with time series data, including date range generation, frequency
conversion, and time-based indexing.