PWP Notes
PWP Notes
1) Interpreted
2) Platform- Independent
3) Object Oriented
4) Large Standard Library
5) Free and Open-Source
6) Auto-Destructive (Automatic Memory Management)
Identifier: Identifier is a user-defined name given to a variable, function, class, module, etc.
Keywords: Python Keywords are some predefined and reserved words that have special meanings.
Indentation: In Python, indentation is used to define blocks of code. It tells the Python interpreter that a group of
statements belongs to a specific block.
Variables: In Python, variables are used to store data that can be referenced and manipulated during program
execution.
Comments: Comments in python are those lines that are ignored by the interpreter during the execution of the
program.
Membership Operators: Membership operators in Python are used to check whether a value is present in a given
sequence (like a list, tuple, string, or dictionary).
not in Operator: The not in operator checks if a specific value is not present in a sequence.
Identity Operators: Identity operators in Python are used to compare the memory locations of two objects to check
whether they refer to the same object. These operators do not compare values but instead check if two variables point
to the same memory location.
is operator: Returns True if both variables refer to the same memory location (i.e., they are the same object).
is not operator: Returns True if both variables refer to different objects in memory.
break statement: The break statement immediately stops the loop, even if iterations are left.
Example
if i == 3:
Output
continue statement: The continue statement skips the current iteration and moves to the next one.
Example
if i == 3:
print(i)
Output
pass statement: The pass statement does nothing and acts as a placeholder. It is useful when a block of code is required
but we haven’t written logic yet, preventing syntax errors.
Example
if i == 3:
print(i)
Output
5
else: The else block in loops runs only if the loop completes fully without encountering a break
Example
print(i)
else:
print("Loop completed")
Output
Loop completed
List: A list is an ordered, mutable (changeable) collection of elements enclosed in square brackets ( []). It can contain
different data types.
Elements in a list can be accessed using indexing. Python indexes start at 0, so a[0] will access the first element, while
negative indexing allows us to access elements from the end of the list. Like index -1 represents the last elements of list.
List operations:
Adding Elements to a List: We know that list is mutable and updatable entity. After creating a list, we can use three
functions to add new elements in list.
append(): This function appends or add a specified element to list. It adds the element at the end of the list and
it does not modify existing elements
extend(): This function adds multiple elements from another list or iterable to the end. Unlike append(), which
adds a single element, extend() adds multiple items separately.
insert(): This function inserts an element at the specified index without replacing existing elements.
Finding the Length of a List using len(): len() returns the total number of elements present in the list. It counts all
elements, including duplicates.
Updating Elements Using Assignment Operator (=): You can modify an element by assigning a new value to a specific
index. The new value replaces the existing value at that index.
Deleting Elements from a List: We delete one or more elements from a list by using different keyword and functions
like:
del: del removes an element at the specified index. It does not return the deleted element.
remove(): remove() removes the first occurrence of the given value. If the value does not exist, it raises an error.
pop(): pop() removes and returns an element from a specific index (default is the last). If the index is not given,
it removes the last element.
clear(): clear() removes all elements from the list. The list remains but becomes empty ([]).
i) append()
ii) extend()
iii) insert()
iv) remove()
v) pop()
vi) clear()
vii) len()
viii) index(): Returns the index of the first occurrence of a value.
ix) count(): Returns the number of times an element appears in the list.
x) sort(): Sorts the list in-place (modifies the original list).
xi) reverse(): This method reverses the list order.
Tuple: A tuple is an ordered, immutable (unchangeable) collection of elements enclosed in parentheses (()). It is similar
to a list but cannot be modified after creation.
Elements in a tuple can be accessed using indexing. Python indexes start at 0, so a[0] will access the first element, while
negative indexing allows us to access elements from the end of the tuple. Like index -1 represents the last elements of
tuple.
i) Finding the Length of a tuple using len(): len() returns the total number of elements present in the tuple. It
counts all elements, including duplicates.
ii) Concatenation of Tuples: This operation is used to concatenate two tuples. It can be joined using the +
operator.
iii) Repeating Elements in a Tuple: This operation can be used to repeat the elements in a tuple. The *
operator repeats the tuple elements.
Deleting a Tuple Tuples are immutable, so individual elements cannot be deleted. However, the entire tuple can be
deleted using the del keyword.
iv) sum() : Returns the sum of all elements in the tuple (only for numeric values).
v) count() : Returns the number of times a specified element appears in the tuple.
A set is an unordered collection of unique elements in Python. It is defined using curly braces {} or the set() function.
Sets automatically remove duplicate values. Sets are mutable, meaning you can add or remove items after creation.
Basic Operations:
a) discard() Method: Removes the specified element from the set. No error occurs if the element is not found.
b) remove() Method: Removes the specified element from the set. Raises an error if the element is not found.
c) pop() Method: Removes and returns a random element from the set. Raises an error if the set is empty.
d) clear() Method: Removes all elements from the set, leaving it empty.
iv) Deleting a Set in Python: Python provides the del keyword to delete an entire set.
A dictionary in Python is an unordered, mutable collection that stores data in key-value pairs. It is defined using curly
braces {} or the dict() function.
Dictionaries in Python cannot be accessed using index numbers because they are unordered collections. Instead,
dictionary values are accessed using their keys.
Python provides two useful methods to access dictionary keys and values:
keys() Method: Returns a view object containing all the keys in the dictionary.
values() Method: Returns a view object containing all the values in the dictionary.
a) Using the update() Method: Adds new key-value pairs or updates existing keys.
b) Using the = Operator: Directly assigns a new value to a key.
a) Using pop() Method: Removes the element with the specified key and returns its value. Raises an error if the
key does not exist.
b) Using popitem() Method: Removes and returns the last inserted key-value pair. Useful for removing unknown
keys.
c) Using clear() Method: Removes all elements from the dictionary.
Python Functions is a block of statements that performs an action and returns the specific task. Functions make code
more modular which allow us to use the same code over and over again.
Required Argument: Required arguments are function parameters that must be provided during a function call.
Keyword Argument: Keyword arguments are function parameters passed using their names instead of their position.
Default Argument: Default arguments are function parameters that have predefined values.
Variable length Argument: Variable-length arguments allow a function to accept an unknown number of arguments.
Python packages are a way to organize and structure code by grouping related modules into directories.
A Class is a unit of code that describes the characteristics and behavior of group of code. A class is a collection of object.
It’s a user define data type which includes local functions as well as local data.
An object in Python is an instance of a class. It is a real-world entity that has attributes (variables) and behaviors
(methods) defined by the class.
Every member function of a class must have ‘self’ parameter. The parameter ‘self’ is a reference to the current object,
and is used to access attributes and member functions that belongs to the class. It does not have to be named ‘self’ only,
you can name it whatever you like, but it has to be the first parameter of any function
A constructor in Python is a special method used to initialize objects when they are created. It is defined using the
__init__() method inside a class.
Default Constructor: A default constructor in Python is a constructor that does not take any parameters except self.
Parameterized Constructor: A Parameterized constructor in Python is a constructor that takes arguments to initialize
object attributes
Constructor with Default Argument: A constructor with default arguments in Python allows assigning default values to
parameters.
Inheritance is the mechanism of deriving a new class from the old class. The class whose properties are being derived is
called as Base class, Super class or Parent class, and the class which derives the properties of base class is called as
Derived class, Sub class or Child class.
Single Inheritance: Single inheritance in Python is a concept where a child class inherits from a single parent class.
Multilevel Inheritance: Multilevel inheritance in Python is a concept where a class inherits from another class, which
itself is derived from another class. This forms a chain of inheritance.
Multiple Inheritance: Multiple inheritance in Python is a concept where a child class inherits from two or more parent
classes.
Hierarchical Inheritance: Hierarchical inheritance in Python is a concept where multiple child classes inherit from a
single parent class.
Hybrid Inheritance: Hybrid inheritance in Python is a concept where a class inherits from multiple types of inheritance
combined in a single program. It can be a mix of single, multiple, multilevel, or hierarchical inheritance.
Method Overriding: Method overriding in python, is a concept where a method in a child class has the same name and
parameters as the method in a parent’s class. The purpose of method overriding is to change or inherit the behavior of
parent class method. When an object of child class calls the method then the child’s version is called instead of parent’s
version. This is possible only through inheritance.
Method Overloading: In Python, method overloading is not supported in the traditional way like other languages. If you
define multiple methods with the same name, the latest one will overwrite the previous ones. However, similar behavior
can be achieved using default arguments, where parameters have default values, allowing the method to be called with
different numbers of arguments. Another way is by using *args and **kwargs, which allow a method to accept a variable
number of positional and keyword arguments.
seek() function: The seek() function in Python is used to move the file pointer to a specific position in a file.
tell() function: The tell() function in Python is used to get the current position of the file pointer.
The mkdir() function in Python is used to create a new directory (folder). It is part of the OS module.
The getcwd() function in Python returns the path of the current working directory where the Python script is running.
The chdir() function is used to change the current working directory to a different path.
The listdir() function returns a list of all files and folders present in the specified directory.
The exists() function is used to check whether a given file or directory path exists.
Exception handling in Python is a method used to manage errors that may occur while a program is running.
Python has many built-in exceptions, each representing a specific error condition. Some common ones include:
A user-defined exception is a custom error created by the programmer to handle specific conditions in a program.
Python allows users to create their own exceptions by defining a new class that inherits from the Exception class.
1. try Block: The try block is where you write the code that might cause an error.
2. except Block: The except block is used to handle the error that occurs in the try block.
3. else Block: The else block runs only if there are no errors in the try block.
4. finally Block: The finally block runs every time, whether an error occurs or not.
The read() function in Python is used to read the entire content of a file as a single string.
The readline() fun ction in Python is used to read a single line from a file.
The readlines() function in Python is used to read all the lines from a file and return them as a list of strings.
Python range is a function that returns a sequence of numbers. By default, range returns a sequence that begins at 0
and increments in steps of 1. The range function only works with integers.