Complete Python Revision

Complete Python Revision from Fundamentals to Advanced Topics

 

 

Introduction to Python: Python is a high-level programming language that is widely used for web development, scientific computing, data analysis, artificial intelligence, and more. It is known for its simple and easy-to-read syntax, making it a popular choice for beginners. Python also has a large and active community, which means there are many resources and libraries available for use.

Features of Python: Some of the key features of Python include its dynamic typing, automatic memory management, and support for multiple programming paradigms. Python also has built-in data structures such as lists, dictionaries, and sets, as well as a large number of modules and libraries. Additionally, Python has a built-in garbage collector that automatically frees up memory that is no longer needed.

Execution of a Python Program: To execute a Python program, you can use the command line, an IDE, or a code editor. The command line can be used to run Python scripts by simply typing “python” followed by the name of the script. For example, if you have a script named “hello.py,” you would type “python hello.py” to run it.

Viewing the Byte Code: In Python, you can view the byte code of a program by using the “dis” module. This module allows you to see the byte code that is generated by the Python interpreter when it runs a program. To view the byte code of a program, you would first import the “dis” module and then call the “dis” function with the name of the program as an argument.

Flavors of Python: There are several different versions of Python available, each with its own set of features and capabilities. The most commonly used versions are Python 2 and Python 3. Python 2 is the older version of the language and is still widely used, but Python 3 is the recommended version for new projects.

Python Virtual Machine (PVM): The Python Virtual Machine (PVM) is the software that runs Python programs. It is responsible for interpreting the byte code generated by the Python interpreter and executing it on the computer. The PVM is designed to be highly efficient and can run multiple programs at the same time.

Frozen Binaries: Frozen binaries are pre-compiled versions of Python programs that can be run without the need for the Python interpreter. This can be useful in situations where you need to distribute a Python program to others, but do not want to include the interpreter along with it.

Memory Management in Python: Python uses automatic memory management, which means that the language takes care of allocating and deallocating memory as needed. This is done through the use of a garbage collector, which automatically frees up memory that is no longer needed.

Garbage Collection in Python: The garbage collector in Python is responsible for freeing up memory that is no longer needed by a program. It works by keeping track of all the objects that are currently in use by a program and periodically checking for objects that are no longer being used. If an object is no longer being used, the garbage collector will free up the memory associated with it.

Comparisons between C and Python: C and Python are both popular programming languages, but they have some key differences. C is a low-level language that is known for its speed and efficiency, whereas Python is a high-level language that is known for its simplicity and ease of use. Additionally, C requires manual memory management, whereas Python has automatic memory management.

Comparisons between Java and Python: Java and Python are both popular programming languages, but they have some key differences. Java is a strongly typed language, meaning that variables must be declared with a specific data type, whereas Python is a dynamically typed language, meaning that the data type is determined at runtime. Additionally, Java is known for its robust object-oriented programming capabilities, whereas Python is known for its simplicity and ease of use. Java also has a built-in garbage collector, like Python.

Writing Our First Python Program: To start writing Python programs, you will first need to install Python on your computer. This can be done by downloading the Python installer from the official website and following the instructions. Once Python is installed, you can verify the installation by running the “python” command in the command line.

Installing Python for Windows: To install Python on a Windows computer, you can download the Python installer from the official website and run it. The installer will guide you through the installation process, which includes choosing the location to install Python and adding Python to the system path.

Testing the Installation in Windows 10: To test the installation of Python on a Windows 10 computer, you can open the command prompt and type “python.” If Python is installed correctly, this will open the Python interpreter and you will be able to run Python commands.

Verifying the Path to Python: To verify the path to Python on a Windows computer, you can open the command prompt and type “where python.” This will display the location of the Python executable on your computer.

Installing numpy, pandas, xlrd and matplotlib: In order to use certain libraries and modules in Python, you will need to install them separately. Some popular libraries include numpy for scientific computing, pandas for data analysis, xlrd for working with Excel files, and matplotlib for plotting and visualization. These libraries can be installed using pip, the package installer for Python.

Verifying Installed Packages: To verify that a library or module has been installed correctly, you can use the “pip list” command, which will display a list of all the packages currently installed on your system.

Writing Our First Python Program: To write your first Python program, you can use a code editor or IDE. A simple program can be written using the “print” function, which will output a message to the screen. For example, the following code will print “Hello World” to the screen: print(“Hello World”)

Executing a Python Program: To execute a Python program, you can use the command line, an IDE, or a code editor. You can also run a Python program directly from the system prompt by typing the name of the script and the “.py” extension.

Using Python’s Command Line Window: The command line window can be used to run Python scripts by simply typing “python” followed by the name of the script. For example, if you have a script named “hello.py,” you would type “python hello.py” to run it.

Using Python’s IDLE Graphics Window: Python’s IDLE (Integrated Development and Learning Environment) provides a graphical user interface for writing and executing Python code. It includes features such as syntax highlighting, code completion, and debugging tools.

Running Directly from System Prompt: You can also run a Python program directly from the system prompt by typing the name of the script and the “.py” extension. For example, if you have a script named “hello.py,” you would type “hello.py” in the prompt to run it. This method is useful for running scripts without the need for an IDE or code editor.

Getting Help in Python: To get help in Python, you can use the built-in “help” function or consult the Python documentation. The “help” function can be used to access information about specific functions and modules, while the documentation provides a comprehensive overview of the language and its features.

Getting Python Documentation Help: The Python documentation can be accessed online and provides a wealth of information about the language and its features. This includes tutorials, examples, and reference material for various modules and libraries. Additionally, the Python community provides many resources, such as forums and blogs, where you can get help and learn more about the language.

Datatypes in Python: In Python, there are several built-in datatypes that can be used to store different types of data. These include numeric types (such as integers and floating-point numbers), sequences (such as strings and lists), and mappings (such as dictionaries).

Comments in Python: Comments are used in Python to add notes and explanations to code. There are two types of comments: single line comments and multi-line comments. Single line comments start with a “#” symbol and  to the end of the line, while multi-line comments are enclosed in triple quotes (“””).

Single line comments: Single line comments in Python start with a “#” symbol and  to the end of the line. For example, the following code is a single line comment:

1. # This is a single line comment

 

Multi line comments: Multi-line comments in Python are enclosed in triple quotes (“””). They can be used to add multiple lines of comments to code. For example, the following code is a multi-line comment:

1. """

2. This is a

3. multi-line comment

4. """

5.  

 

Docstrings: Docstrings are a special type of multi-line comment that are used to document functions, classes, and modules. They are enclosed in triple quotes (“””) and are placed at the beginning of the code block. For example, the following code is a docstring:

1. def my_function():

2.     """

3.     This is a docstring for the my_function

4.     """

5.     pass

6.  

 

How Python Sees Variables: In Python, variables are references to objects in memory. The variable does not store the value itself, but instead stores a reference to the location in memory where the value is stored. This means that when a variable is assigned a new value, it is simply pointing to a new location in memory.

Datatypes in Python: Python has several built-in datatypes including numeric types (such as integers and floating-point numbers), sequences (such as strings and lists), and mappings (such as dictionaries). Each datatype has its own specific characteristics and uses.

Built-in datatypes: Python has several built-in datatypes including numeric types (such as integers and floating-point numbers), sequences (such as strings and lists), and mappings (such as dictionaries). Examples of built-in datatypes are int, float, str, list, dict, etc.

The None Type: The None type is a special datatype in Python that represents the absence of a value. It is commonly used to initialize variables that do not have a value yet or to represent the end of a loop. For example, the following code assigns the variable x to None: x = None

Numeric Types: Numeric types in Python include integers (int), floating-point numbers (float), and complex numbers (complex). These types can be used to store and manipulate numerical data in Python. For example, the following code assigns the variable x to the value 5: x = 5

Representing Binary, Octal and Hexadecimal Numbers: In Python, you can represent numbers in binary, octal, and hexadecimal format using the prefixes 0b, 0o, and 0x respectively. For example, the following code assigns the variable x to the binary value 10: x = 0b10

Converting the Datatypes Explicitly: In Python, you can explicitly convert one datatype to another using built-in functions such as int(), float(), and str(). For example, the following code converts the float value 5.5 to an integer: x = int(5.5)

bool Datatype: The bool datatype is used to represent Boolean values in Python. It can have two values: True or False. This datatype is commonly used in control flow statements such as if-else statements. For example, the following code assigns the variable x to the Boolean value True: x = True

Sequences in Python: Sequences in Python include the str, bytes, bytearray, list, tuple, and range datatypes. These datatypes are used to store and manipulate sequences of values. For example, the following code creates a list of numbers: x = [1, 2, 3]

str Datatype: The str datatype is used to store and manipulate strings of characters in Python. Strings can be enclosed in single quotes (‘ ‘) or double quotes (” “) and can include any combination of letters, numbers, and special characters. For example, the following code creates a string variable: x = “Hello World”

bytes Datatype: The bytes datatype is used to store and manipulate sequences of bytes. It is similar to the str datatype but is used for binary data. For example, the following code creates a bytes variable: x = b’Hello World’

bytearray Datatype: The bytearray datatype is similar to the bytes datatype but is mutable, meaning it can be modified after it is created. For example, the following code creates a bytearray variable: x = bytearray(b’Hello World’)

list Datatype: The list datatype is used to store and manipulate sequences of values. Lists are enclosed in square brackets [] and can include any combination of datatypes. For example, the following code creates a list of numbers: x = [1, 2, 3]

tuple Datatype: The tuple datatype is similar to the list datatype but is immutable, meaning it cannot be modified after it is created. Tuples are enclosed in parentheses () and can include any combination of datatypes. For example, the following code creates a tuple of numbers: x = (1, 2, 3)

range Datatype: The range datatype is used to create a sequence of numbers. It is commonly used in for loops and can be specified by providing a start, stop, and step value. For example, the following code creates a range of numbers: x = range(1, 5)

Sets: Sets in Python include the set and frozenset datatypes. These datatypes are used to store and manipulate sets of unique values. For example, the following code creates a set of numbers: x = set([1, 2, 3])

Mapping Types: Mapping types in Python include the dict datatype. This datatype is used to store and manipulate key-value pairs. For example, the following code creates a dictionary: x = {‘a’: 1, ‘b’: 2, ‘c’: 3}

Literals in Python: Literals in Python are used to represent specific values of a given datatype. Examples of literals include numeric literals, Boolean literals, and string literals. For example, the following code assigns the variable x to the numeric

1. literal 5: x = 5

2.  

 

Numeric Literals: Numeric literals in Python include integers and floating-point numbers. For example, the following code assigns the variable x to the integer literal 5: x = 5

Boolean Literals: Boolean literals in Python include the values True and False. For example, the following code assigns the variable x to the Boolean literal True: x = True

String Literals: String literals in Python are enclosed in single quotes (‘ ‘) or double quotes (” “) and can include any combination of letters, numbers, and special characters. For example, the following code assigns the variable x to the string literal “Hello World”: x = “Hello World”

Determining the Datatype of a Variable: In Python, you can determine the datatype of a variable using the built-in function type(). For example, the following code determines the datatype of the variable x: print(type(x))

Characters: In Python, characters are represented using the str datatype and enclosed in single quotes (‘ ‘). For example, the following code assigns the variable x to the character ‘a’: x = ‘a’

User-defined Datatypes: In Python, you can also define your own datatypes using classes. These classes can have their own attributes and methods, and can be used to create objects. For example, the following code defines a custom class called “Person”:

1. class Person:

2.     def __init__(self, name):

3.         self.name = name

4.  

 

Constants in Python: Constants in Python are variables whose values are not intended to change throughout the program. These values are often used to represent fixed values, such as pi or the speed of light. In Python, constants are typically represented using all uppercase letters and are defined using the “constant” naming convention. For example, the following code defines a constant PI: PI = 3.14

Identifiers and Reserved words: Identifiers in Python are used to name variables, functions, and other objects in the program. They must start with a letter or underscore and can only contain letters, numbers, and underscores. Reserved words in Python are keywords that have a specific meaning and cannot be used as identifiers. Examples of reserved words include “if,” “else,” and “for.”

Naming Conventions in Python: Naming conventions in Python are guidelines for naming variables, functions, and other objects in the program. These conventions help to make the code more readable and maintainable. One of the most common conventions is the “snake_case” convention, which uses underscores between words. Another common convention is the “camelCase” convention, which uses no spaces between words and capitalizes the first letter of each new word.

Operators in Python: Operators are special symbols in Python that perform specific operations on one or more operands (values or variables). There are several types of operators in Python, including arithmetic, assignment, relational, logical, bitwise, and membership operators.

Arithmetic Operators: Arithmetic operators are used to perform mathematical operations such as addition, subtraction, multiplication, and division. These operators include +, -, *, /, % (modulus), and ** (exponent). For example, the following code uses the + operator to add two numbers: x = 5 + 6

Using Python Interpreter as Calculator: The Python interpreter can also be used as a calculator by typing in arithmetic expressions and hitting enter. For example, the following code uses the Python interpreter to calculate the value of 5 + 6: >>> 5 + 6

Assignment Operators: Assignment operators are used to assign values to variables. The most common assignment operator is the “=” operator, which assigns a value to a variable. For example, the following code assigns the value 5 to the variable x: x = 5

Unary Minus Operator: The unary minus operator is used to negate the value of a variable or number. For example, the following code negates the value of the variable x: x = -x

Relational Operators: Relational operators are used to compare the values of two operands and return a Boolean value. These operators include >, <, >=, <=, == (equal to), and != (not equal to). For example, the following code uses the > operator to compare the values of x and y: x > y

Logical Operators: Logical operators are used to combine multiple relational expressions and return a Boolean value. These operators include and, or, and not. For example, the following code uses the and operator to check if both x is greater than 5 and y is less than 10: x > 5 and y < 10

Boolean Operators: Boolean operators are used to perform logical operations on Boolean values. These operators include and, or, and not. For example, the following code uses the and operator to check if both x is true and y is false: x and not y

Bitwise Operators: Bitwise operators are used to perform operations on the binary representation of numbers. These operators include & (and), | (or), ^ (xor), ~ (complement), << (left shift), and >> (right shift). For example, the following code uses the & operator to perform a bitwise and operation on the values of x and y: x & y

Bitwise Complement Operator (~): The bitwise complement operator is used to invert the binary representation of a number. For example, the following code uses the ~ operator to invert the binary representation of the variable x: ~x

Bitwise AND Operator (&): The bitwise AND operator is used to perform a logical and operation on the binary representations of two numbers. For example, the following code uses the & operator to perform a bitwise and operation on the values of x and y: x & y

Bitwise OR Operator (|): The bitwise OR operator is used to perform a logical or operation on the binary representations of two numbers. For example, the following code uses the | operator to perform a bitwise or operation on the values of x and y: x | y

Bitwise XOR Operator (^): The bitwise XOR operator is used to perform a logical xor operation on the binary representations of two numbers. For example, the following code uses the ^ operator to perform a bitwise xor operation on the values of x and y: x ^ y

Bitwise Left Shift Operator (<<): The bitwise left shift operator is used to shift the binary representation of a number to the left a specified number of times. For example, the following code uses the << operator to shift the binary representation of the variable x to the left by 2: x << 2

Bitwise Right Shift Operator (>>): The bitwise right shift operator is used to shift the binary representation of a number to the right a specified number of times. For example, the following code uses the >> operator to shift the binary representation of the variable x to the right by 2: x >> 2

Membership Operators: Membership operators are used to check if a value is a member of a sequence. These operators include in and not in. For example, the following code uses the in operator to check if the value 5 is in the list x: 5 in x

The in Operator: The in operator is used to check if a value is a member of a sequence. It returns a Boolean value. For example, the following code uses the in operator to check if the value 5 is in the list x: 5 in x

The not in Operator: The not in operator is used to check if a value is not a member of a sequence. It returns a Boolean value. For example, the following code uses the not in operator to check if the value 5 is not in the list x: 5 not in x

Identity Operators: Identity operators are used to compare the memory locations of two objects. These operators include is and is not. For example, the following code uses the is operator to check if the variables x and y refer to the same object in memory: x is y

The is Operator: The is operator is used to check if two variables refer to the same object in memory. It returns a Boolean value. For example, the following code uses the is operator to check if the variables x and y refer to the same object in memory: x is y

The is not Operator: The is not operator is used to check if two variables do not refer to the same object in memory. It returns a Boolean value. For example, the following code uses the is not operator to check if the variables x and y do not refer to the same object in memory: x is not y

Operator Precedence and Associativity: In Python, operators have a specific order of precedence and associativity. This determines the order in which operations are performed in an expression. For example, multiplication and division are performed before addition and subtraction.

Mathematical Functions: Python has several built-in mathematical functions that can be used to perform various mathematical operations. Examples include the math.sqrt() function for square root and the math.pow() function for exponentiation. For example, the following code uses the math.sqrt() function to calculate the square root of 9: import math; math.sqrt(9)

Using IDLE Window: Python programs can be written and executed using the IDLE window, which is a built-in IDE (Integrated Development Environment) for Python. Programs can be written in the editor and executed by pressing F5 or running the code from the Run menu.

Using Command Line Window: Python programs can also be written and executed using the command line window. Programs can be written in a text editor and executed by running the command python filename.py in the command line.

Executing at System Prompt: Python programs can also be executed directly from the system prompt by navigating to the directory where the program is located and running the command python filename.py. This method allows for the program to be run from any location on the system.

Output statements: Output statements in Python are used to display information to the user. The most commonly used output statement is the print() statement, which displays text or variables to the console.

The print() Statement: The basic print() statement is used to display text or variables to the console. For example, the following code uses the print() statement to display the string “Hello World”: print(“Hello World”)

The print(“string”) Statement: The print() statement can also be used to display text enclosed in quotation marks. For example, the following code uses the print() statement to display the string “Hello World”: print(“Hello World”)

The print(variables list) Statement: The print() statement can also be used to display the values of multiple variables. For example, the following code uses the print() statement to display the values of the variables x and y: print(x, y)

The print(object) Statement: The print() statement can also be used to display the value of an object. For example, the following code uses the print() statement to display the value of the list x: print(x)

The print(“string”, variables list) Condition: The print() statement can also be used to display a combination of text and variables. For example, the following code uses the print() statement to display the string “The value of x is” and the value of the variable x: print(“The value of x is”, x)

The print(formatted string) Condition: The print() statement can also be used to display a formatted string. This allows for the insertion of variables or expressions into a string using placeholders. For example, the following code uses the print() statement to display a formatted string with the variable x: print(“The value of x is: {}”.format(x))

Input Statements: Input statements in Python are used to receive information from the user. The most commonly used input statement is the input() statement, which prompts the user for input and stores the input as a string. For example, the following code uses the input() statement to prompt the user for their name and stores the input in the variable x: x = input(“What is your name? “)

Command Line Arguments: Command line arguments are used to pass information to a program at runtime. In Python, command line arguments are passed as a list of strings to the program. For example, the following code uses the sys.argv list to access command line arguments: import sys; print(sys.argv)

Parsing Command Line Arguments: In order to use command line arguments effectively, they must be parsed and processed within the program. This can be done using the argparse module in Python, which allows for the creation of command line argument parser objects. For example, the following code uses the argparse module to create a parser object and add an argument for a file name:

1. import argparse

2. parser = argparse.ArgumentParser()

3. parser.add_argument("file_name")

4. args = parser.parse_args()

5. print(args.file_name)

6.  

 

Control Statements: Control statements in Python are used to control the flow of execution of a program. These statements include the if, while, and for statements, as well as the break, , and return statements.

The if Condition: The if condition is used to perform an action if a certain condition is met. The syntax for the if statement is as follows:

if condition:

1. # code to execute if condition is true

2. For example, the following code uses the if statement to check if a variable x is greater    than 5 and, if so, prints x is greater than 5”:

3. x = 7

4. if x > 5:

5.     print("x is greater than 5")

6.  

 

A Word on Indentation: In Python, indentation is used to indicate the level of nested code blocks. Therefore, it is important to maintain proper indentation when using control statements.

The if…else Condition: The if…else condition is used to perform a different action if the condition of the if statement is not met. The syntax for the if…else statement is as follows:

1. if condition:

2.     # code to execute if condition is true

3. else:

4.     # code to execute if condition is false

5.  

 

For example, the following code uses the if…else statement to check if a variable x is greater than 5 and, if so, prints “x is greater than 5” and if not, prints “x is less than or equal to 5”:

1. x = 3

2. if x > 5:

3.     print("x is greater than 5")

4. else:

5.     print("x is less than or equal to 5")

6.  

The if… elif … else Condition: The if…elif…else condition is used to check multiple conditions and perform different actions based on the outcome. The syntax for the if…elif…else statement is as follows:

 1. if condition1:

 2.     # code to execute if condition1 is true

 3. elif condition2:

 4.     # code to execute if condition2 is true

 5. else:

 6.     # code to execute if neither condition1 nor condition2 is true

 7. For example, the following code uses the ifelifelse statement to check if a variable x is greater than 5, equal to 5, or less than 5 and performs different actions based on the outcome:

 8. x = 5

 9. if x > 5:

10.     print("x is greater than 5")

11. elif x == 5:

12.     print("x is equal to 5")

13. else:

14.     print("x is less than 5")

15.  

 

The while Loop: The while loop is used to repeatedly execute a block of code as long as a certain condition is met. The syntax for the while loop is as follows:

1. while condition:

2.     # code to execute while condition is true

3. For example, the following code uses the while loop to repeatedly print Hello World while the variable x is less than 5:

4. x = 0

5. while x < 5:

6.     print("Hello World")

7.     x += 1

8.  

 

The for Loop: The for loop is used to iterate over a sequence of items, such as a list or string. The syntax for the for loop is as follows:

1. for item in sequence:

2.     # code to execute for each item in the sequence

3. For example, the following code uses the for loop to iterate over a list of numbers and print each number:

4. numbers = [1, 2, 3, 4, 5]

5. for num in numbers:

6.     print(num)

7.  

 

Infinite Loops: Infinite loops occur when a loop’s condition is always true and can cause a program to crash. These can be avoided by including a breaking condition within the loop.

Nested Loops: Nested loops occur when one loop is included within another loop. This allows for the execution of multiple loops at the same time.

The else Suite: The else suite can be used in conjunction with the for and while loops to execute a block of code when the loop has finished executing.

The break Condition: The break condition is used to exit a loop prematurely. When the break statement is executed, the program s to execute the next line of code after the loop.

The  Condition: The  condition is used to skip an iteration of a loop. When the  statement is executed, the program s to the next iteration of the loop.

The pass Condition: The pass condition is used as a placeholder when a statement is required but no action needs to be taken.

The assert Condition: The assert condition is used to check if a certain condition is met and, if not, raises an error.

The return Condition: The return condition is used to exit a function and return a value. The return statement can also be used to exit a program completely. For example, the following code uses the return statement to exit a function and return the value of the variable x: def my_function(): x = 5 return x result = my_function() print(result)

Array: An array is a data structure that stores a collection of elements, which can be of the same data type. In Python, arrays can be created using the array module or the numpy library.

Advantages of Arrays: Arrays are efficient for storing and manipulating large amounts of data. They also allow for easy indexing and slicing, which makes it easy to access and manipulate specific elements within the array.

Creating an Array: An array can be created using the array module in Python. The syntax for creating an array is as follows:

1. from array import array

2. my_array = array("i", [1, 2, 3, 4, 5])

3. This creates an array of integers with the values 1, 2, 3, 4, and 5.

4.  

 

Importing the Array Module: In order to use the array module, it must first be imported using the following code:

1. from array import array

2. Indexing and Slicing on Arrays: Indexing and slicing can be used to access specific elements within an array. For example, the following code uses indexing to access the first element of an array:

3. my_array = array("i", [1, 2, 3, 4, 5])

4. print(my_array[0])

5. And the following code uses slicing to access a range of elements within an array:

6. my_array = array("i", [1, 2, 3, 4, 5])

7. print(my_array[1:3])

8.  

 

Processing the Arrays: Arrays can be processed using various methods, such as sorting and reversing. For example, the following code sorts an array:

1. my_array = array("i", [3, 2, 1, 5, 4])

2. my_array.sort()

3. print(my_array)

4.  

1.  

Types of Arrays: In Python, arrays can be of different types, such as integer, float, and character arrays. These types are specified when creating the array using the array module.

Working with Arrays using numpy: The numpy library in Python provides a more efficient and convenient way of working with arrays. It offers a wide range of functions and methods for creating, manipulating and processing arrays.

Creating Arrays using array(): The array() function in numpy can be used to create an array from a list or tuple. For example, the following code creates an array of integers:

1. import numpy as np

2. my_array = np.array([1, 2, 3, 4, 5])

3.  

 

Creating Arrays using linspace(): The linspace() function in numpy can be used to create an array of evenly spaced values within a given range. For example, the following code creates an array of 10 values between 0 and 1:

1. import numpy as np

2. my_array = np.linspace(0, 1, 10)

3.  

 

Creating Arrays using logspace(): The logspace() function in numpy can be used to create an array of logarithmically spaced values within a given range. For example, the following code creates an array of 10 values between 1 and 100:

1. import numpy as np

2. my_array = np.logspace(1, 2, 10)

3.  

 

Creating Arrays using arange() Function: The arange() function in numpy can be used to create an array of values with a specified step size within a given range. For example, the following code creates an array of integers between 0 and 10 with a step size of 2:

1. import numpy as np

2. my_array = np.arange(0, 10, 2)

3.  

 

Creating Arrays using zeros() and ones() Functions: The zeros() and ones() functions in numpy can be used to create arrays of zeros and ones with a specified shape. For example, the following code creates an array of 5 zeros:

1. import numpy as np

2. my_array = np.zeros(5)

3.  

 

Mathematical Operations on Arrays: Numpy allows for various mathematical operations to be performed on arrays, such as addition, subtraction, multiplication, and division. These operations can be performed using the standard mathematical operators (+, -, *, /) or using numpy’s built-in functions such as np.add(), np.subtract(), np.multiply(), and np.divide(). For example, the following code multiplies two arrays:

1. import numpy as np

2. array1 = np.array([1, 2, 3])

3. array2 = np.array([4, 5, 6])

4. result = np.multiply(array1, array2)

5. print(result)

6.  

 

Comparing Arrays: Numpy allows for the comparison of arrays using the standard comparison operators (==, !=, >, <, >=, <=) or using numpy’s built-in functions such as np.equal(), np.not_equal(), np.greater(), np.less(), np.greater_equal(), and np.less_equal(). For example, the following code compares two arrays:

1. import numpy as np

2. array1 = np.array([1, 2, 3])

3. array2 = np.array([1, 2, 3])

4. result = np.equal(array1, array2)

5. print(result)

6.  

 

Aliasing the Arrays: Aliasing occurs when a new variable is assigned to an existing array, allowing for the same array to be referenced by multiple variables. This can be useful for creating multiple views of the same array.

Viewing and Copying Arrays: In numpy, arrays can be viewed or copied using the view() and copy() methods. The view() method creates a new view of the array, allowing for changes made to the new view to be reflected in the original array. The copy() method creates a new copy of the array, independent of the original array.

Slicing and Indexing in numpy Arrays: Slicing and indexing can be used to access specific elements within an array. For example, the following code uses indexing to access the first element of an array:

1. import numpy as np

2. my_array = np.array([1, 2, 3, 4, 5])

3. print(my_array[0])

4. And the following code uses slicing to access a range of elements within an array:

5. import numpy as np

6. my_array = np.array([1, 2, 3, 4, 5])

7. print(my_array[1:3])

8.  

 

Dimensions of Arrays: In numpy, arrays can have one or multiple dimensions. The number of dimensions can be determined using the ndim attribute.

Attributes of an Array: Numpy provides several attributes that can be used to determine the properties of an array, such as the ndim attribute, shape attribute, size attribute, itemsize attribute, dtype attribute, and nbytes attribute.

The reshape() Method: The reshape() method in numpy can be used to change the shape of an array. For example, the following code reshapes an array from 1D to 2D:

1. import numpy as np

2. my_array = np.array([1, 2, 3, 4, 5])

3. my_array = my_array.reshape(5, 1)

4. The flatten() Method: The flatten() method in numpy can be used to convert a multidimensional array into a 1D array. For example, the following code flattens a 2D array:

5. import numpy as np

6. my_array = np.array([[1, 2], [3, 4], [5, 6]])

7. my_array = my_array.flatten()

8.  

 

Working with Multi-dimensional Arrays: Numpy allows for the creation and manipulation of multi-dimensional arrays using the array() function, ones() and zeros() functions, and the reshape() function.

The eye() Function: The eye() function in numpy can be used to create an identity matrix with a specified number of rows and columns.

Indexing in Multi-dimensional Arrays: In multi-dimensional arrays, indexing can be used to access specific elements within the array. The indexes are separated by commas, with the first index representing the row and the second index representing the column.

Slicing the Multi-dimensional Arrays: In multi-dimensional arrays, slicing can be used to access specific ranges of elements within the array. The slices are separated by commas, with the first slice representing the rows and the second slice representing the columns.

Matrices in numpy: Numpy allows for the creation and manipulation of matrices using the matrix() function and various matrix operations such as getting diagonal elements, finding maximum and minimum elements, finding sum and average of elements, products of elements, sorting the matrix, transpose of a matrix, matrix addition and multiplication, and random numbers.

Getting Diagonal Elements of a Matrix: The diagonal() function in numpy can be used to get the diagonal elements of a matrix.

Finding Maximum and Minimum Elements: The max() and min() functions in numpy can be used to find the maximum and minimum elements within an array or matrix.

Finding Sum and Average of Elements: The sum() and mean() functions in numpy can be used to find the sum and average of elements within an array or matrix.

Products of Elements: The prod() function in numpy can be used to find the product of elements within an array or matrix.

Sorting the Matrix: The sort() function in numpy can be used to sort the elements of a matrix in ascending or descending order.

Transpose of a Matrix: The transpose() function in numpy can be used to find the transpose of a matrix, which flips the rows and columns of the matrix. For example, the following code finds the transpose of a matrix:

1. import numpy as np

2. my_matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

3. my_matrix = my_matrix.transpose()

4.  

 

Matrix Addition and Multiplication: The addition and multiplication of matrices can be performed using the standard mathematical operators (+, *) or using numpy’s built-in functions such as np.add() and np.multiply(). For example, the following code adds two matrices:

1. import numpy as np

2. matrix1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

3. matrix2 = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])

4. result = np.add(matrix1, matrix2)

5. print(result)

6.  

 

Random Numbers: The random() function in numpy can be used to generate random numbers within a given range. This is useful for creating random arrays or matrices for testing and simulation purposes.

Creating Strings: Strings in Python can be created using single or double quotes. For example, the following code creates a string using single quotes:

1. my_string = ‘Hello, World!’

2. And the following code creates a string using double quotes:

3. my_string = "Hello, World!"

4.  

 

Length of a String: The len() function can be used to determine the length of a string, which is the number of characters within the string. For example, the following code returns the length of a string:

1. my_string = "Hello, World!"

2. string_length = len(my_string)

3. print(string_length)

4.  

 

Indexing in Strings: Indexing can be used to access specific characters within a string. The first character has an index of 0, and the last character has an index of -1. For example, the following code accesses the first character of a string:

1. my_string = "Hello, World!"

2. first_character = my_string[0]

3. print(first_character)

4.  

 

Slicing the Strings: Slicing can be used to access a range of characters within a string. The start and end index of the slice are separated by a colon. For example, the following code accesses the characters from index 2 to index 5 of a string:

1. my_string = "Hello, World!"

2. substring = my_string[2:6]

3. print(substring)

4.  

 

Repeating the Strings: The * operator can be used to repeat a string a specified number of times. For example, the following code repeats a string 3 times:

1. my_string = "Hello, World!"

2. repeated_string = my_string * 3

3. print(repeated_string)

4.  

Concatenation of Strings: The + operator can be used to concatenate (join) two or more strings. For example, the following code concatenates two strings:

1. string1 = Hello, string2 = World!” concatenated_string = string1 + string2 print(concatenated_string)

2.  

 

Checking Membership: The in operator can be used to check if a specific character or substring is present within a string. For example, the following code checks if the character "W" is present in a string:

1. my_string = Hello, World!” result = W in my_string print(result)

2.  

 

Comparing Strings: Strings can be compared using the standard comparison operators (==, !=, >, <, >=, <=). For example, the following code compares two strings:

1. string1 = Hello, World!” string2 = Hello, World!” result = string1 == string2 print(result)

2.  

 

Removing Spaces from a String: The strip(), lstrip(), and rstrip() functions can be used to remove spaces from the beginning, end, or both of a string. For example, the following code removes spaces from the beginning and end of a string:

1. my_string = Hello, World! stripped_string = my_string.strip() print(stripped_string)

2.  

3.  

 

Finding Sub Strings: The find() and index() functions can be used to find the index of a specific substring within a string. The find() function returns -1 if the substring is not found, while the index() function raises an exception.

Counting Substrings in a String: The count() function can be used to count the number of occurrences of a specific substring within a string. For example, the following code counts the number of occurrences of the substring "l" in a string:

1. my_string = Hello, World!” substring = l count = my_string.count(substring) print(count)

2.  

3.  

 

Strings are Immutable: Strings in Python are immutable, which means that their values cannot be modified once they are created.

Replacing a String with another String: The replace() function can be used to replace a specific substring within a string with another substring. For example, the following code replaces the

1. substring World with Universe in a string:

2. my_string = "Hello, World!"

3. new_string = my_string.replace("World", "Universe")

4. print(new_string)

5.  

Splitting and Joining Strings: The split() function can be used to split a string into a list of substrings based on a specified delimiter. The join() function can be used to join a list of strings into a single string, using a specified delimiter. For example, the following code splits a string by the delimiter “,”:

1. my_string = "Hello, World!"

2. split_string = my_string.split(",")

3. print(split_string)

4. And the following code joins a list of strings using the delimiter “:

5. my_list = ["Hello", "World!"]

6. joined_string = " ".join(my_list)

7. print(joined_string)

8.  

 

Changing Case of a String: The upper() and lower() functions can be used to convert a string to uppercase or lowercase letters. For example, the following code converts a string to uppercase letters:

1. my_string = "Hello, World!"

2. uppercase_string = my_string.upper()

3. print(uppercase_string)

4.  

 

Checking Starting and Ending of a String: The startswith() and endswith() functions can be used to check if a string starts or ends with a specific substring. For example, the following code checks if a string starts with “Hello”:

1. my_string = "Hello, World!"

2. result = my_string.startswith("Hello")

3. print(result)

4.  

 

String Testing Methods: Python provides various string testing methods such as isalpha(), isdigit(), isalnum(), etc. These methods can be used to check if a string contains only alphabets, digits, or alphanumeric characters.

Formatting the Strings: The format() method can be used to insert values into a string, using placeholders. For example, the following code formats a string with a placeholder for a name:

1. my_string = "Hello, {}!"

2. formatted_string = my_string.format("John")

3. print(formatted_string)

4.  

 

Working with Characters: Characters in Python can be treated as strings of length 1, and can be manipulated using string methods and operations.

Sorting Strings: The sorted() function can be used to sort the characters within a string in ascending or descending order.

Searching in the Strings: The find() and index() functions can be used to find the index of a specific character within a string.

Finding Number of Characters and Words: The len() function can be used to find the number of characters within a string, and the split() function can be

used to find the number of words within a string by splitting the string on spaces. For example, the following code finds the number of characters and words in a string:

1. my_string = "Hello, World!"

2. characters = len(my_string)

3. words = len(my_string.split())

4. print("Number of characters: ", characters)

5. print("Number of words: ", words)

6.  

 

Inserting Sub String into a String: The join() function can be used to insert a substring into a string. For example, the following code inserts a substring “John” into a string:

1. my_string = "Hello, {}!"

2. substring = "John"

3. formatted_string = my_string.format(substring)

4. print(formatted_string)

5.  

 

Difference between a Function and a Method: In Python, a function is a block of code that performs a specific task and can be called by other code, while a method is a function that is associated with an object and can be called on that object.

Defining a Function: A function is defined using the def keyword, followed by the function name and a set of parentheses that may contain parameters. For example, the following code defines a function called “greet” that takes a single parameter “name”:

1. def greet(name):

2.     print("Hello, {}!".format(name))

3.  

 

Calling a Function: A function is called by its name, followed by a set of parentheses that may contain arguments. For example, the following code calls the “greet” function and passes in the argument “John”:greet("John")

Returning Results from a Function: A function can return a value using the return keyword. For example, the following code defines a function that calculates the square of a number and returns the result:

1. def square(x):

2.     return x*x

3.  

 

Returning Multiple Values from a Function: A function can return multiple values by separating them with a comma. These values will be returned as a tuple. For example, the following code defines a function that returns two values:

1. def multiple_values():

2.     return 1, 2

3.  

Functions are First Class Objects: Functions in Python are treated as first-class objects, which means that they can be assigned to variables, passed as arguments to other functions, and returned as values from functions.

Pass by ObjectReference: In Python, arguments are passed to functions by reference, which means that the function can modify the original object.

Formal and Actual Arguments: Formal arguments are the parameters declared in the function definition, while actual arguments are the values passed to the function when it is called.

Positional Arguments: Positional arguments are arguments that are passed to a function in a specific order, corresponding to the order of the formal arguments.

Keyword Arguments: Keyword arguments are arguments that are passed to a function using the name of the formal argument, along with the value. This allows for the order of the arguments to be different from the order of the formal arguments. For example, the following code calls a function with keyword arguments:

1. def greet(name, age):

2.     print("Hello, {}. You are {} years old.".format(name, age))

3.  

4. greet(age=25, name="John")

5.  

 

Default Arguments: Default arguments are arguments that have a pre-defined value in the function definition. If a value for that argument is not provided when the function is called, the default value is used. For example, the following code defines a function with a default argument:

1. def greet(name, age=18):

2.     print("Hello, {}. You are {} years old.".format(name, age))

3.  

4. greet("John")

5.  

 

Variable Length Arguments: Variable length arguments allow a function to accept any number of arguments. The * operator is used to define variable length positional arguments, and the ** operator is used to define variable length keyword arguments. For example, the following code defines a function that accepts variable length arguments:

1. def print_args(*args, **kwargs):

2.     print("Positional arguments:", args)

3.     print("Keyword arguments:", kwargs)

4.  

5. print_args(1, 2, 3, name="John", age=25)

6.  

 

Local and Global Variables: Variables defined within a function are local to that function and cannot be accessed outside of it, while variables defined outside of a function are global and can be accessed by any function.

The Global Keyword: The global keyword can be used to access a global variable within a function. For example, the following code defines a global variable and accesses it within a function:

1. x = 5

2.  

3. def increment():

4.     global x

5.     x += 1

6.     print(x)

7.  

8. increment()

9.  

 

Passing a Group of Elements to a Function: A function can accept a group of elements as an input using the * operator. For example, the following code defines a function that accepts a group of elements and prints them:

1. def print_elements(*elements):

2.     for element in elements:

3.         print(element)

4.  

5. print_elements(1, 2, 3, 4, 5)

6.  

 

Recursive Functions: A recursive function is a function that calls itself. This allows for a problem to be broken down into smaller subproblems that can be solved by the same function.

Anonymous Functions or Lambdas: Anonymous functions, also known as lambdas, are functions that are defined without a name. They are useful for short, simple functions that are used only once. For example, the following code defines a lambda function that squares a number:

1. square = lambda x: x*x

2. print(square(5))

3.  

 

Using Lambdas with filter() Function: The filter() function can be used with a lambda function to filter elements from a list based on a certain condition. For example, the following code filters even numbers from a list:

1. numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

2. even_numbers = filter(lambda x: x%2 == 0, numbers)

3. print(list(even_numbers))

4.  

 

Using Lambdas with map() Function: The map() function can be used with a lambda function to apply a function to each element of a list. For example, the following code squares each element of a list:

1. numbers = [1, 2, 3, 4, 5]

2. squared_numbers = map(lambda x: x*x, numbers)

3. print(list(squared_numbers))

4.  

 

Using Lambdas with reduce() Function: The reduce() function can be used with a lambda function to apply a function to a list of elements in a cumulative manner. For example, the following code finds the product of all elements in a list:

1. from functools import reduce

2. numbers = [1, 2, 3, 4, 5]

3. product = reduce(lambda x, y: x*y, numbers) print(product)

4.  

 

Function Decorators: Function decorators are a way to modify the behavior of a function using another function. They are defined using the @ symbol, followed by the decorator function. For example, the following code defines a decorator function that adds a prefix to the result of a function:

1. def prefix_decorator(function): def wrapper(name): return Mr. + function(name) return wrapper

2. @prefix_decorator def greet(name): return name

3. print(greet(“John”))

4.  

 

Generators: Generators are a way to create iterators in Python. They are defined using the yield keyword, and can be used to generate a sequence of values on the fly. For example, the following code defines a generator function that generates the Fibonacci sequence:

1. def fibonacci(n): a, b = 0, 1 for i in range(n): yield a a, b = b, a+b

2. for number in fibonacci(10): print(number)

3.  

 

Structured Programming: Structured programming is a programming paradigm that emphasizes the use of functions and control structures to break down a problem into smaller, manageable parts. This allows for a program to be more modular and easier to understand.

Creating our Own Modules in Python: A module is a file that contains Python definitions and statements. Users can create their own modules in Python and import them into their programs. For example, the following code defines a module called "my_module" and imports it into the main program:

1. my_module.py

2. def greet(name): print(Hello, {}!”.format(name))

3. main.py

4. import my_module my_module.greet(“John”)

5.  

 

The Special Variable name: The special variable `__name__` is used to determine if a Python file is being run as the main program or if it is being imported as a module. The value of `__name__` is set to "__main__" if the file is being run as the main program, and the name of the module if it is being imported.

Additionally, the __name__ variable can be used to implement conditional logic that only runs certain code when the file is run as the main program and not when it is imported as a module. For example, the following code only runs the code block inside the if statement when the file is run as the main program:

1. def my_function():

2.     print("This is my function.")

3.  

4. if __name__ == "__main__":

5.     print("This code only runs when the file is run as the main program.")

6.     my_function()

7.  

 

List: A list is a collection of items that are ordered and changeable. Lists are defined using square brackets [] and items are separated by commas. For example, the following code creates a list of numbers:

1. numbers = [1, 2, 3, 4, 5]

2.  

 

Creating Lists using range() Function: The range() function can be used to create a list of numbers within a specified range. For example, the following code creates a list of numbers from 1 to 10:

1. numbers = list(range(1, 11))

2. print(numbers)

3.  

 

Updating the Elements of a List: Elements of a list can be updated by assigning a new value to the index of that element. For example, the following code updates the first element of a list:

1. numbers = [1, 2, 3, 4, 5]

2. numbers[0] = 10

3. print(numbers)

4.  

 

Concatenation of Two Lists: Two lists can be concatenated using the + operator. For example, the following code concatenates two lists:

1. list1 = [1, 2, 3]

2. list2 = [4, 5, 6]

3. list3 = list1 + list2

4. print(list3)

5.  

 

Repetition of Lists: A list can be repeated using the * operator. For example, the following code repeats a list 3 times:

1. numbers = [1, 2, 3]

2. numbers = numbers * 3

3. print(numbers)

4.  

 

Membership in Lists: The in and not in operators can be used to check if an element is present in a list. For example, the following code checks if the number 3 is present in a list:

1. numbers = [1, 2, 3, 4, 5]

2. if 3 in numbers:

3.     print("3 is present in the list.")

4.  

Lists and Tuples are both data structures in Python that are used to store a collection of items. However, there are some key differences between the two. Lists are mutable, meaning their elements can be changed, while tuples are immutable, meaning their elements cannot be changed once they are created.

Here is an example of creating a list using the range() function in Python:

 1. # Creating a list of numbers from 1 to 10

 2. numbers = list(range(1, 11))

 3. print(numbers) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

 4. Updating the elements of a list can be done using the assignment operator:

 5.  

 6.  

 7. # Updating the 3rd element of the list

 8. numbers[2] = 20

 9. print(numbers) # Output: [1, 2, 20, 4, 5, 6, 7, 8, 9, 10]

10. Concatenation of two lists can be done using the + operator:

11.  

12.  

13. # Concatenating two lists

14. list1 = [1, 2, 3]

15. list2 = [4, 5, 6]

16. result = list1 + list2

17. print(result) # Output: [1, 2, 3, 4, 5, 6]

18. Repetition of lists can be done using the * operator:

19.  

20. # Repetition of lists

21. list1 = [1, 2, 3]

22. result = list1 * 3

23. print(result) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]

24. Checking for membership in a list can be done using the in keyword:

25.  

26. # Membership in lists

27. list1 = [1, 2, 3, 4, 5]

28. print(3 in list1) # Output: True

29. print(6 in list1) # Output: False

30. Aliasing and cloning lists can be done using the assignment operator and the copy() method:

31.  

32. # Aliasing and cloning lists

33. list1 = [1, 2, 3]

34. list2 = list1 # Aliasing

35. list3 = list1.copy() # Cloning

36. list1[0] = 10

37. print(list2) # Output: [10, 2, 3]

38. print(list3) # Output: [1, 2, 3]

39.  

 

Methods to process lists include append(), insert(), remove(), count(), index(), and reverse():

 1. # Methods to process lists

 2. list1 = [1, 2, 3, 4, 5]

 3. list1.append(6) # Adding an element to the end of the list

 4. list1.insert(2, 7) # Inserting an element at index 2

 5. list1.remove(4) # Removing the element 4 from the list

 6. print(list1.count(3)) # Counting the number of occurrences of 3 in the list

 7. print(list1.index(5)) # Finding the index of the element 5 in the list

 8. list1.reverse() # Reversing the elements of the list

 9. print(list1) # Output: [6, 5, 7, 3, 2, 1]

10.  

 

Finding the biggest and smallest elements in a list can be done using the max() and min() functions:

 

1. # Finding biggest and smallest elements in a list

2. list1 = [3, 2, 5, 1, 4]

3. print(max(list1)) # Output: 5

4. print(min(list1)) # Output: 1

5.  

6.  

 

Sorting the elements of a list can be done using the sort() method:

1. “`python

2. # Sorting the elements of a list

3. list1 = [3, 2, 5, 1, 4]

4. list1.sort()

5. print(list1) # Output: [1, 2, 3, 4, 5]

6.  

 

Finding the number of occurrences of an element in the list can be done using the count() method:

1. # Number of occurrences of an element in the list

2. list1 = [1, 2, 3, 4, 5, 2, 3, 2]

3. print(list1.count(2)) # Output: 3

4.  

 

Finding common elements in two lists can be done using the intersection() method of the set data type:

1. # Finding common elements in two lists

2. list1 = [1, 2, 3, 4, 5]

3. list2 = [4, 5, 6, 7, 8]

4. print(set(list1).intersection(list2)) # Output: {4, 5}

5.  

 

Storing different types of data in a list is possible as Python is a dynamically typed language:

1. # Storing different types of data in a list

2. list1 = [1, "hello", 3.14, True]

3.  

 

Nested lists can be used to create matrices:

1. # Nested lists as matrices

2. matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

3.  

 

List comprehensions are a concise way to create a new list based on an existing one:

1. # List comprehension

2. list1 = [1, 2, 3, 4, 5]

3. list2 = [x*2 for x in list1]

4. print(list2) # Output: [2, 4, 6, 8, 10]

5.  

 

Creating tuples can be done by enclosing elements in parentheses:

1. # Creating tuples

2. tuple1 = (1, 2, 3)

3.  

 

Accessing the elements of a tuple can be done using indexing:

1. # Accessing the elements of a tuple

2. tuple1 = (1, 2, 3)

3. print(tuple1[1]) # Output: 2

4. Basic operations on tuples include concatenation and repetition, similar to lists:

5.  

 

1. # Basic operations on tuples

2. tuple1 = (1, 2, 3)

3. tuple2 = (4, 5, 6)

4. result = tuple1 + tuple2

5. print(result) # Output: (1, 2, 3, 4, 5, 6)

6. result = tuple1 * 3

7. print(result) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)

8.  

 

Nested tuples can be created by enclosing tuples within tuples:

# Nested tuples

tuple1 = (1, 2, (3, 4))

Inserting, modifying, and deleting elements from tuples is not possible as they are immutable.

 

In summary, lists and tuples are both data structures that can be used to store collections of items, but

Dictionaries are a built-in data structure in Python that are used to store key-value pairs. They are also known as associative arrays or hash maps.

Creating a dictionary can be done by enclosing key-value pairs in curly braces {} or by using the dict() constructor:

1. # Creating a dictionary using curly braces

2. dict1 = {‘key1’: ‘value1’, ‘key2’: ‘value2’}

3. print(dict1) # Output: {‘key1’: ‘value1’, ‘key2’: ‘value2’}

4.  

5. # Creating a dictionary using the dict() constructor

6. dict2 = dict(key1=‘value1’, key2=‘value2’)

7. print(dict2) # Output: {‘key1’: ‘value1’, ‘key2’: ‘value2’}

8.  

 

Operations on dictionaries include adding, updating, and deleting elements:

 

 1. # Adding an element to a dictionary

 2. dict1 = {‘key1’: ‘value1’, ‘key2’: ‘value2’}

 3. dict1[‘key3’] = ‘value3’

 4. print(dict1) # Output: {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

 5.  

 6. # Updating an element in a dictionary

 7. dict1[‘key1’] = new_value

 8. print(dict1) # Output: {‘key1’: ‘new_value‘, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

 9.  

10. # Deleting an element from a dictionary

11. del dict1[‘key1’]

12. print(dict1) # Output: {‘key2’: ‘value2’, ‘key3’: ‘value3’}

13. Dictionary methods include keys(), values(), items(), and get():

14.  

15. # Dictionary methods

16. dict1 = {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

17. print(dict1.keys()) # Output: dict_keys([‘key1’, ‘key2’, ‘key3’])

18. print(dict1.values()) # Output: dict_values([‘value1’, ‘value2’, ‘value3’])

19. print(dict1.items()) # Output: dict_items([(‘key1’, ‘value1’), (‘key2’, ‘value2’), (‘key3’, ‘value3’)])

20. print(dict1.get(‘key1’)) # Output: ‘value1’

21. Using a for loop with dictionaries can be done by using the keys() or items() methods:

22.  

23. # Using a for loop with dictionaries

24. dict1 = {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

25.  

26. # Using the keys() method

27. for key in dict1.keys():

28.     print(key) # Output: ‘key1’, ‘key2’, ‘key3’

29.  

30. # Using the items() method

31. for key, value in dict1.items():

32.     print(key, value) # Output: ‘key1’, ‘value1’, ‘key2’, ‘value2’, ‘key3’, ‘value3’

33.  

 

Sorting the elements of a dictionary can be done using the sorted() function and a lambda function:

 1. # Sorting the elements of a dictionary

 2. dict1 = {‘key1’: ‘value1’, ‘key2

 3. : ‘value2’, ‘key3’: ‘value3’}

 4.  

 5. Sorting by keys

 6. sorted_dict = dict(sorted(dict1.items(), key=lambda x: x[0]))

 7. print(sorted_dict) # Output: {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

 8.  

 9. Sorting by values

10. sorted_dict = dict(sorted(dict1.items(), key=lambda x: x[1]))

11. print(sorted_dict) # Output: {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

12.  

 

Converting lists into dictionaries can be done using the zip() function and the dict() constructor:

1. “`python

2. # Converting lists into a dictionary

3. keys = [‘key1’, ‘key2’, ‘key3’]

4. values = [‘value1’, ‘value2’, ‘value3’]

5. dict1 = dict(zip(keys, values))

6. print(dict1) # Output: {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

7.  

 

Converting strings into dictionaries can be done by using the json library:

1. # Converting strings into a dictionary

2. import json

3. string = ‘{"key1": "value1", "key2": "value2"}’

4. dict1 = json.loads(string)

5. print(dict1) # Output: {‘key1’: ‘value1’, ‘key2’: ‘value2’}

6.  

Passing dictionaries to functions can be done by passing them as arguments:

1. # Passing dictionaries to functions

2. def print_dict(d):

3.     for key, value in d.items():

4.         print(key, value)

5.  

6. dict1 = {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

7. print_dict(dict1) # Output: ‘key1’, ‘value1’, ‘key2’, ‘value2’, ‘key3’, ‘value3’

8.  

 

An ordered dictionary is a subclass of the built-in dict class that maintains the order of elements. It can be created using the collections library:

1. # Creating an ordered dictionary

2. from collections import OrderedDict

3. dict1 = OrderedDict()

4. dict1[‘key1’] = ‘value1’

5. dict1[‘key2’] = ‘value2’

6. dict1[‘key3’] = ‘value3’

7. print(dict1) # Output: OrderedDict([(‘key1’, ‘value1’), (‘key2’, ‘value2’), (‘key3’, ‘value3’)])

8.  

 

Object Oriented Programming (OOP) is a programming paradigm that focuses on using objects and classes to represent real-world entities. It is a method of programming that provides the ability to encapsulate data and methods inside objects, and to create new objects based on existing ones.

Problems in Procedure Oriented Approach are:

Global variables can be changed by any function, leading to unexpected behavior.

Functions are tightly coupled with one another, making it difficult to make changes.

Functions can only operate on data that is passed to them as arguments, making it difficult to maintain state.

Specialty of Python Language in OOP is that it is a dynamically typed language, which means that the data type of a variable is determined at runtime, rather than at compile time. This allows for greater flexibility when creating objects and classes.

Features of Object Oriented Programming System (OOPS) include:

Encapsulation: the ability to hide the internal state and behavior of an object from the outside world.

Abstraction: the ability to focus on the essential features of an object, rather than its implementation details.

Inheritance: the ability to create new classes that inherit properties and methods from existing classes.

Polymorphism: the ability for objects of different classes to be used interchangeably, based on their shared interface.

Creating a class in Python is done using the class keyword, followed by the class name and a colon:

 

 

1. class MyClass:

2.     pass

3.  

 

The self variable is a reference to the current instance of the class, and is used to access the properties and methods of the class.

The constructor in Python is a special method named __init__, which is called when a new object of the class is created:

1. class MyClass:

2.     def __init__(self, arg1, arg2):

3.         self.property1 = arg1

4.         self.property2 = arg2

5.  

6. my_object = MyClass(1, 2)

7. print(my_object.property1) # Output: 1

8. print(my_object.property2) # Output: 2

9.  

 

In Python, classes can have different types of variables, such as class variables and instance variables. Class variables are shared among all instances of the class, while instance variables have separate values for each instance.

Namespaces in Python are used to organize the variables and functions in a program and prevent naming conflicts. Each class has its own namespace, and instances of a class also have their own namespace.

Classes in Python can have different types of methods, such as instance methods, class methods, and static methods

Instance methods are methods that are called on instances of a class and can access and modify the instance’s properties and state. They take the self parameter as their first argument:

 1. class MyClass:

 2.     def __init__(self, arg1):

 3.         self.property = arg1

 4.  

 5.     def instance_method(self):

 6.         return self.property * 2

 7.  

 8. my_object = MyClass(10)

 9. print(my_object.instance_method()) # Output: 20

10.  

 

Class methods are methods that are called on the class itself, and not on instances of the class. They are defined using the @classmethod decorator and take the cls parameter as their first argument:

1. class MyClass:

2.     class_var = 10

3.  

4.     @classmethod

5.     def class_method(cls):

6.         return cls.class_var * 2

7. print(MyClass.class_method()) # Output: 20

8.  

 

Static methods are methods that are associated with a class, but do not have access to the class or instance state. They are defined using the @staticmethod decorator and do not take any special first argument:

1. class MyClass:

2.     @staticmethod

3.     def static_method(arg1, arg2):

4.         return arg1 + arg2

5.  

6. print(MyClass.static_method(1, 2)) # Output: 3

7.  

 

Inheritance in Python allows a new class to inherit properties and methods from an existing class, called the superclass. This can be done by including the superclass name in parentheses after the class name:

1. class SuperClass:

2.     def method1(self):

3.         pass

4.  

5. class SubClass(SuperClass):

6.     def method2(self):

7.         pass

8.  

 

Polymorphism in Python allows objects of different classes to be used interchangeably, as long as they have the same interface. This is often achieved through inheritance, where a subclass can override or extend the methods of its superclass.

Python also allows for operator overloading, where the behavior of built-in operators can be redefined for user-defined classes. This is done by defining special methods, such as __add__ for the + operator, in the class.

Similarly, method overloading and overriding can be achieved in Python by defining methods with the same name in different classes or subclass, but with different arguments or implementation

This is just a brief overview of the concepts, if you have any specific question or want more information please let me know.

Sure, here are a few more examples and details on the topics I just covered.

Operator overloading in Python is done by defining special methods in a class, such as __add__ for the + operator, __sub__ for the – operator, and so on. Here’s an example of how operator overloading can be used to create a class that represents a complex number:

 1. class Complex:

 2.     def __init__(self, real, imag):

 3.         self.real = real

 4.         self.imag = imag

 5.  

 6.     def __add__(self, other):

 7.         return Complex(self.real + other.real, self.imag + other.imag)

 8.  

 9.     def __sub__(self, other):

10.         return Complex(self.real other.real, self.imag other.imag)

11.  

12.     def __str__(self):

13.         return f"{self.real} + {self.imag}i"

14.  

15. c1 = Complex(1, 2)

16. c2 = Complex(3, 4)

17. print(c1 + c2) # Output: 4 + 6i

18. print(c1 c2) # Output: -2 – 2i

19.  

 

Method overloading and overriding can be achieved in Python by defining methods with the same name in different classes or subclasses, but with different arguments or implementation.

Method overloading is a feature of some programming languages in which a method can have multiple implementations depending on the number or type of arguments passed to the method.

1. class MyClass:

2.     def method(self, arg1):

3.         pass

4.     def method(self, arg1, arg2):

5.         pass

6.  

 

This is not possible in Python due to lack of support for method overloading.

Method overriding is when a subclass provides a specific implementation of a method that is already provided by its superclass. The subclass’ implementation will be called instead of the superclass’ implementation when the method is called on an instance of the subclass.

 1. class SuperClass:

 2.     def method(self):

 3.         print("SuperClass method")

 4.  

 5. class SubClass(SuperClass):

 6.     def method(self):

 7.         print("SubClass method")

 8.  

 9. obj = SubClass()

10. obj.method() # Output: "SubClass method"

11.  

 

These are just a few examples of how classes and objects can be used in Python to create powerful and reusable code. I hope that this information helps you understand how to use these concepts in your own programs. If you have any more specific question, let me know.

Abstract Classes and Interfaces are two important concepts in object-oriented programming that allow for creating reusable and extensible code.

An abstract class is a class that contains one or more abstract methods, which are methods that have a signature but no implementation. They are intended to be overridden by subclasses, but cannot be instantiated on their own.

 1. from abc import ABC, abstractmethod

 2. class MyAbstractClass(ABC):

 3.     @abstractmethod

 4.     def my_abstract_method(self):

 5.         pass

 6.  

 7. class MyConcreteClass(MyAbstractClass):

 8.     def my_abstract_method(self):

 9.         print("I am a concrete implementation of an abstract method.")

10.  

11. my_object = MyConcreteClass()

12. my_object.my_abstract_method() # Output: "I am a concrete implementation of an abstract method."

13.  

 

Interfaces in Python are a way to define a contract of what methods and properties a class should have, without providing an implementation. They are not built-in in python but can be implemented using abstract classes and annotations.

 1. from typing import List

 2.  

 3. class MyInterface:

 4.     def my_method(self,arg:str)->str:

 5.         pass

 6.  

 7. class MyConcreteClass(MyInterface):

 8.     def my_method(self,arg:str)->str:

 9.         return arg

10.  

11. my_object = MyConcreteClass()

12. print(my_object.my_method("Hello")) # Output: "Hello"

13.  

 

Abstract classes and interfaces are similar in that they both define contracts that classes must adhere to, but they differ in how they achieve this. Abstract classes provide a partial implementation and can contain concrete methods, while interfaces only define the contract and cannot contain any implementation.

Exceptions are events that are triggered by errors or exceptional conditions in a program. They are used to handle errors and exceptional conditions in a structured and predictable way, rather than allowing them to cause the program to crash.

Errors in a Python program can be divided into three categories:

Compile-time errors: errors that are detected by the interpreter when the program is being compiled

Runtime errors: errors that are detected by the interpreter when the program is running, such as divide by zero or file not found

Logical errors: errors that are caused by the program’s logic, such as a variable not being initialized or a loop not terminating

Exceptions are a way to handle runtime errors and exceptional conditions in a structured and predictable way. The try and except blocks are used to catch and handle exceptions:

1. try:

2.     x = 1 / 0

3. except ZeroDivisionError:

4.     print("Cannot divide by zero.")

5.  

There are various built-in exceptions in python like ZeroDivisionError, FileNotFoundError, IndexError etc.

The assert statement can also be used to check for conditions that should be true, and trigger an exception if the condition is not met.

x = -1

assert x >= 0, "x should be non-negative"

You can also create your own exception classes by creating a new class that inherits from the built-in Exception class:

 

1. class MyException(Exception):

2.     pass

3.  

4. raise MyException("My custom exception message.")

5.  

 

Logging exceptions is an important part of the exception handling process. Logging the exception can help you track down the problem and understand what went wrong. This can be done using the built-in logging module in python.

1. import logging

2.  

3. try:

4.     x = 1 / 0

5. except ZeroDivisionError:

6.     logging.exception("Error dividing by zero")

7.  

 

Files in python are used to store and retrieve data on a computer’s storage devices. Python provides built-in functions and classes to work with different types of files, such as text files and binary files.

To open a file, you can use the built-in open() function, which takes the file name and mode as arguments. The mode can be ‘r’ for reading, ‘w’ for writing, or ‘a’ for appending.

1. f = open(‘myfile.txt’, ‘w’)

2. f.write("Hello, world!")

3. f.close()

4.  

 

It is important to close the file after you are done working with it, this can be done by calling the close() method on the file object.

Working with text files containing strings is a common task, Python provides a built-in read() and write() methods to read and write strings to text files.

1. with open(‘myfile.txt’, ‘r’) as f:

2.     data = f.read()

3.     print(data) # Output: "Hello, world!"

4.  

 

You can use the os module in python to check if a file exists or not before opening it.

1. import os

2. if os.path.exists("myfile.txt"):

3.     with open("myfile.txt") as f:

4.         data = f.read()

5.         print(data)

6.  

 

Working with binary files is similar to working with text files, but you need to open the file in binary mode and use the read() and write() methods that work with bytes.

1. with open(myfile.bin, wb) as f:

2.     f.write(b‘Hello, world!’)

3.  

4. with open(myfile.bin, rb) as f:

5.     data = f.read()

6.     print(data) # Output: b’Hello, world!’

7.  

 

The with statement is a way to ensure that a file is properly closed even if an exception is raised while working with it.

pickle is a module in python that allows you to serialize and deserialize python objects to and from binary data. This can be useful for storing complex data structures or for sending data over a network.

 1. import pickle

 2.  

 3. data = {‘a’: 1, ‘b’: 2}

 4. with open(mydata.pickle, wb) as f:

 5.     pickle.dump(data, f)

 6.  

 7. with open(mydata.pickle, rb) as f:

 8.     data = pickle.load(f)

 9.     print(data) # Output: {‘a’: 1, ‘b’: 2}

10.  

 

The seek() and tell() methods can be used to move the position of the file pointer to a specific location in the file and retrieve the current position of the file pointer.

1. with open(‘myfile.txt’, ‘r’) as f:

2.     print(f.tell()) # Output: 0

3.     f.seek(5)

4.     print(f.tell())

5. Output: 5

6.  

7. data = f.read()

8. print(data)

9.  

 

Random Accessing of Binary files allows you to read and write specific parts of a binary file without reading the entire file into memory. This can be done using the mmap module in python, which allows you to create a memory-mapped file object.

 

 1. import mmap

 2. with open(myfile.bin, wb) as f:

 3.     f.write(b‘Hello, world!’)

 4.  

 5. with open(myfile.bin, r+b) as f:

 6.     # memory-map the file, size 0 means whole file

 7.     mmapped_file = mmap.mmap(f.fileno(), 0)

 8.     mmapped_file[6:12] = b‘Python

 9.     mmapped_file.seek(0)  # rewind

10.     data = mmapped_file.read()

11.     print(data) # Output: b’Hello, Python!’

12.     mmapped_file.close()

13.  

 

Zipping and unzipping files can be done using the zipfile module in python, which provides classes for creating and extracting ZIP files.

1. import zipfile

2. with zipfile.ZipFile(‘myfiles.zip’, ‘w’) as z:

3.     z.write(‘myfile1.txt’)

4.     z.write(‘myfile2.txt’)

5. with zipfile.ZipFile(‘myfiles.zip’, ‘r’) as z:

6.     z.extractall()

7.  

 

Working with directories in python can be done using the os and os.path modules which provide functions for creating, renaming, and deleting directories and files.

 1. import os

 2.  

 3. # Create a directory

 4. os.mkdir(mydir)

 5.  

 6. # Rename a directory

 7. os.rename(mydir, mynewdir)

 8.  

 9. # Delete a directory

10. os.rmdir(mynewdir)

11.  

 

Running other programs from a python program can be done using the subprocess module, which allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

 1. import subprocess

 2.  

 3. # run a shell command

 4. subprocess.run([‘ls’, ‘-l’])

 5.  

 6. # run a shell command and capture the output

 7. result = subprocess.run([‘ls’, ‘-l’], capture_output=True)

 8. print(result.stdout)

 9.  

10.  

 

You can also use the subprocess.Popen class to create a new process and interact with it directly, rather than waiting for it to complete.

 

1. import subprocess

2.  

3. # start a new process

4. p = subprocess.Popen([‘ls’, ‘-l’], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

5.  

6. # read the output

7. stdout, stderr = p.communicate()

8. print(stdout)

9.  

 

It is also possible to redirect the input and output of a process to a file or a pipe using the subprocess.Popen class.

1. import subprocess

2. with open(‘output.txt’, ‘w’) as f:

3.     subprocess.Popen([‘ls’, ‘-l’], stdout=f)

4.  

 

Regular expressions, or regex for short, are a powerful tool for matching patterns in strings. They are widely used in many programming languages, including Python.

A regular expression is a sequence of characters that defines a search pattern. You can use regular expressions to search for specific characters, words, or patterns in a string, and to extract or replace parts of the string that match the pattern.

In Python, you can use the re module to work with regular expressions. The search() and findall() functions are commonly used to search for patterns in a string, while the sub() function is used to replace parts of the string that match the pattern.

 1. import re

 2. text = "The quick brown fox jumps over the lazy dog."

 3.  

 4. # Search for a pattern in the string

 5. match = re.search("fox", text)

 6. if match:

 7.     print("Found", match.group())

 8. else:

 9.     print("Not found")

10.  

11. # Find all occurrences of a pattern in the string

12. matches = re.findall("o", text)

13. print(matches) # Output: [‘o’, ‘o’, ‘o’]

14.  

15. # Replace all occurrences of a pattern in the string

16. new_text = re.sub("dog", "cat", text)

17. print(new_text) # Output: "The quick brown fox jumps over the lazy cat."

18.  

 

Regular expressions use special characters and quantifiers to define the search pattern. Some of the most commonly used special characters are:

 

.: matches any single character except a newline

*: matches zero or more of the preceding character or group

+: matches one or more of the preceding character or group

?: makes the preceding character or group optional

[]: matches any single character in the set

^ and $: match the start and end of a line, respectively

{}: specifies the number of repetitions of the preceding character or group

For example, the regular expression a.*z matches any string that starts with an ‘a’, followed by zero or more characters, and ends with a ‘z’.

 

1. import re

2. text = "The quick brown fox jumps over the lazy dog."

3.  

4. # Find all words that starts with ‘o

5. matches = re.findall("o\w+", text)

6. print(matches) # Output: [‘over’, ‘over’, ‘og‘]

7.  

 

Regular expressions can also be used to work with files. You can use the `re` module to search for patterns in a file, or to extract or replace parts of the file that match the pattern.

 1. import re

 2.  

 3. # Search for a pattern in a file

 4. with open("file.txt", "r") as f:

 5.     for line in f:

 6.         match = re.search("pattern", line)

 7.         if match:

 8.             print("Found", match.group())

 9.  

10. # Replace all occurrences of a pattern in a file

11. with open("file.txt", "r") as f:

12.     text = f.read()

13.  

14. new_text = re.sub("old_pattern", "new_pattern", text)

15.  

16. with open("file.txt", "w") as f:

17.     f.write(new_text)

18.  

 

Regular expressions can also be used to extract information from a HTML file. The beautifulsoup module can be used to parse the HTML file and navigate the HTML tree.

 1. from bs4 import BeautifulSoup

 2. import re

 3. with open("file.html", "r") as f:

 4.     soup = BeautifulSoup(f, "html.parser")

 5.  

 6. # Find all links in the HTML file

 7. links = soup.find_all("a", href=re.compile("^http"))

 8. for link in links:

 9.     print(link["href"])

10.  

 

Regular expressions are a powerful tool, but they can also be complex and difficult to read. It’s important to take the time to test and debug your regular expressions to ensure that they match the desired patterns.

In addition to regular expressions, Python provides several data structures such as Linked Lists, Stacks, Queues, and Deques to store data and perform various operations on them.

A Linked List is a sequence of data elements, which are connected together via links. Each data element contains a connection to another data element in form of a reference. Linked List is a dynamic data structure, which can grow or shrink at runtime.

 1. class Node:

 2.     def __init__(self, data=None):

 3.         self.data = data

 4.         self.next = None

 5.  

 6. class LinkedList:

 7.     def __init__(self):

 8.         self.head = None

 9.         

10.     def append(self, data):

11.         new_node = Node(data)

12.         if self.head is None:

13.             self.head = new_node

14.             return

15.         current_node = self.head

16.         while current_node.next:

17.             current_node = current_node.next

18.         current_node.next = new_node

19.         

20.     def prepend(self, data):

21.         new_node = Node(data)

22.         new_node.next = self.head

23.         self.head = new_node

24.         

25.     def delete_with_value(self, data):

26.         if self.head is None:

27.             return

28.         if self.head.data == data:

29.             self.head = self.head.next

30.             return

31.         current_node = self.head

32.         while current_node.next:

33.             if current_node.next

34.  

35. .data == data:

36. current_node.next = current_node.next.next

37. return

38. current_node = current_node.next

39.  

40. Creating a linked list and adding elements

41. ll = LinkedList()

42. ll.append(1)

43. ll.append(2)

44. ll.append(3)

45.  

46. Removing an element

47. ll.delete_with_value(2)

48.  

49.  

 

A Stack is a linear data structure that follows a last-in-first-out (LIFO) rule. It can be implemented using an array or a linked list. The main operations that can be performed on a stack are push and pop.

 1. class Stack:

 2.     def __init__(self):

 3.         self.items = []

 4.  

 5.     def push(self, item):

 6.         self.items.append(item)

 7.  

 8.     def pop(self):

 9.         return self.items.pop()

10.  

11.     def peek(self):

12.         return self.items[-1]

13.  

14.     def is_empty(self):

15.         return len(self.items) == 0

16.  

17. # Creating a stack and adding elements

18. s = Stack()

19. s.push(1)

20. s.push(2)

21. s.push(3)

22.  

23. # Removing elements

24. print(s.pop()) # Output: 3

25. print(s.pop()) # Output: 2

26.  

 

A Queue is a linear data structure that follows a first-in-first-out (FIFO) rule. It can be implemented using an array or a linked list. The main operations that can be performed on a queue are enqueue and dequeue.

 1. “`python

 2. class Queue:

 3.     def __init__(self):

 4.         self.items = []

 5.  

 6.     def enqueue(self, item):

 7.         self.items.append(item)

 8.  

 9.     def dequeue(self):

10.         return self.items.pop(0)

11.  

12.     def is_empty(self):

13.         return len(self.items) == 0

14.  

15. # Creating a queue and adding elements

16. q = Queue()

17. q.enqueue(1)

18. q.enqueue(2)

19. q.enqueue(3)

20.  

21. # Removing elements

22. print(q.dequeue()) # Output: 1

23. print(q.dequeue()) # Output: 2

24.  

 

A Deque (Double Ended Queue) is a linear data structure that allows insertion and removal of elements from both the front and the back. It can be implemented using an array or a linked list. The main operations that can be performed on a deque are add_front, add_rear, remove_front and remove_rear.

 

 1. class Deque:

 2.     def __init__(self):

 3.         self.items = []

 4.  

 5.     def add_front(self, item):

 6.         self.items.append(item)

 7.  

 8.     def add_rear(self, item):

 9.         self.items.insert(0, item)

10.  

11.     def remove_front(self):

12.         return self.items.pop()

13.  

14.     def remove_rear(self):

15.         return self.items.pop(0)

16.  

17.     def is_empty(self):

18.         return len(self.items) == 0

19.  

20. # Creating a deque and adding elements

21. d = Deque()

22. d.add_front(1)

23. d.add_front(2)

24. d.add_re

25.  

26. ar(3)

27.  

28. Removing elements

29. print(d.remove_front()) # Output: 2

30. print(d.remove_rear()) # Output: 3

31.  

 

These are just a few examples of the data structures available in Python, and how they can be used to store and manipulate data. Each data structure has its own advantages and disadvantages, and the choice of which one to use depends on the specific requirements of the problem.

In addition to data structures, Python also provides built-in modules to work with date and time, such as the datetime module.

 1. from datetime import datetime

 2.  

 3. # Current date and time

 4. now = datetime.now()

 5. print(now) # Output: 2022-11-17 12:55:32.630958

 6.  

 7. # Extracting specific parts of the date and time

 8. print(now.year) # Output: 2022

 9. print(now.month) # Output: 11

10. print(now.day) # Output: 17

11.  

12. # Creating a date object

13. birthday = datetime(1998, 11, 17)

14. print(birthday) # Output: 1998-11-17 00:00:00

15.  

16. # Calculating the duration between two dates

17. duration = now birthday

18. print(duration) # Output: 12422 days, 12:55:32.630958

19.  

Python also provides the time module to work with time related functions, such as delays and time measurements.

 

 1. import time

 2. # Waiting for 2 seconds

 3. time.sleep(2)

 4.  

 5. # Measuring the time taken for a function to execute

 6. start_time = time.time()

 7. # Function to execute

 8. end_time = time.time()

 9. print("Time taken:", end_time start_time)

10.  

 

Threads are a way to achieve concurrent execution in Python, by allowing multiple threads to run simultaneously. Python’s threading module provides a way to create and manage threads.

 1. import threading

 2. def print_numbers():

 3.     for i in range(10):

 4.         print(i)

 5.  

 6. # Creating a new thread

 7. t = threading.Thread(target=print_numbers)

 8.  

 9. # Starting the thread

10. t.start()

11.  

12. # Main thread s to execute

13. print("Thread finished execution")

14.  

 

Threading can also be used for parallel processing, where multiple threads run simultaneously to complete a task faster. However, Python’s Global Interpreter

Lock (GIL) can limit the performance benefits of threading in certain cases. To overcome this limitation, Python provides the concurrent.futures module which allows for the use of multiple processes instead of threads.

 

 1. import concurrent.futures

 2.  

 3. def print_numbers():

 4.     for i in range(10):

 5.         print(i)

 6.  

 7. with concurrent.futures.ProcessPoolExecutor() as executor:

 8.     executor.submit(print_numbers)

 9.  

10. # Main process s to execute

11. print("Process finished execution")

12.  

 

Threads can also be synchronized to prevent race conditions, where multiple threads access and modify shared data simultaneously. Python’s threading module provides several synchronization primitives such as locks, semaphores and conditions.

 

 1. import threading

 2.  

 3. shared_data = 0

 4. lock = threading.Lock()

 5.  

 6. def increment():

 7.     global shared_data

 8.     with lock:

 9.         for i in range(1000000):

10.             shared_data += 1

11.  

12. # Creating two threads that increment the shared_data variable

13. t1 = threading.Thread(target=increment)

14. t2 = threading.Thread(target=increment)

15.  

16. # Starting the threads

17. t1.start()

18. t2.start()

19.  

20. # Waiting for the threads to finish execution

21. t1.join()

22. t2.join()

23.  

24. print(shared_data) # Output: 2000000

25.  

 

Threading can also be used for communication between threads, using Queues or Event objects.

 1.  

 2. import threading

 3. from queue import Queue

 4.  

 5. q = Queue()

 6.  

 7. def worker():

 8.     while True:

 9.         item = q.get()

10.         if item is None:

11.             break

12.         print("Processing:", item)

13.         q.task_done()

14.  

15. # Creating a worker thread

16. t = threading.Thread(target=worker)

17. t.start()

18.  

19. # Adding items to the queue

20. for item in range(5):

21.     q.put(item)

22.  

23. # Waiting for the worker thread to finish processing the items

24. q.join()

25.  

26. # Sending a signal to the worker thread to stop execution

27. q.put(None)

28. t.join()

29.  

30.  

 

GUI in Python: Python provides several libraries for creating Graphical User Interface (GUI) applications, such as Tkinter, PyQt, wxPython, etc. These libraries provide a way to create windows, buttons, labels, text fields, etc. and to arrange them in a layout.

 

 1. import tkinter as tk

 2.  

 3. # Creating the main window

 4. root = tk.Tk()

 5. root.title("My GUI Application")

 6.  

 7. # Creating a label

 8. label = tk.Label(root, text="Hello World!")

 9. label.pack()

10.  

11. # Creating a button

12. button = tk.Button(root, text="Click Me!")

13. button.pack()

14.  

15. # Running the main loop

16. root.mainloop()

17.  

 

Networking in Python: Python provides several libraries for working with network protocols, such as sockets, urllib, etc. These libraries can be used to create clients and servers for communication over a network using the TCP/IP and UDP protocols.

 1. import socket

 2.  

 3. # Creating a socket

 4. s = socket.socket()

 5.  

 6. # Connecting to a server

 7. s.connect(("www.google.com", 80))

 8.  

 9. # Sending a request to the server

10. s.send("GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n".encode())

11.  

12. # Receiving data from the server

13. data = s.recv(1024)

14. print(data.decode())

15.  

16. # Closing the socket

17. s.close()

18.  

 

Database Connectivity in Python: Python provides several libraries for connecting to databases, such as MySQLdb, cx_Oracle, etc. These libraries can be used to perform CRUD (Create, Read, Update, Delete) operations on a database and to execute stored procedures.

 1. import MySQLdb

 2.  

 3. # Connecting to a MySQL database

 4. db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="test")

 5.  

 6. # Creating a cursor

 7. cursor = db.cursor()

 8.  

 9. # Executing a SQL query

10. cursor.execute("SELECT * FROM employees")

11.  

12. # Fetching the result

13. result = cursor.fetchall()

14.  

15. # Printing the result

16. for row in result:

17.     print(row)

18.  

19. # Closing the cursor and the connection

20. cursor.close()

21. db.close()

22.  

 

Data Science in Python: Python provides several libraries for data science, such as pandas, numpy, matplotlib, scikit-learn, etc. These libraries can be used for data cleaning, transformation, visualization, analysis and machine learning.

 

 1. import pandas as pd

 2.  

 3. # Reading a csv file into a dataframe

 4. df = pd.read_csv("data.csv")

 5.  

 6. # Checking the first 5 rows of the dataframe

 7. print(df.head())

 8.  

 9. # Calculating the mean of a column

10. mean = df["column_name"].mean()

11. print(mean)

12.  

13. # Plotting a bar graph

14. df.plot(kind="bar", x="column_name", y="column_name")

15.  

 

These are just a few examples of the functionality provided by these libraries, and it is important to understand the use cases and limitations of each library before using it in a project.

 

Leave a Reply

Your email address will not be published. Required fields are marked *