Merge branch 'animator:main' into main

pull/579/head
Lingamuneni Santhosh Siddhardha 2024-05-25 10:46:54 +05:30 zatwierdzone przez GitHub
commit 4893612a98
Nie znaleziono w bazie danych klucza dla tego podpisu
ID klucza GPG: B5690EEEBB952194
6 zmienionych plików z 707 dodań i 2 usunięć

Wyświetl plik

@ -1,7 +1,8 @@
# List of sections
- [OOPs](OOPs.md)
- [Decorators/\*args/**kwargs](decorator-kwargs-args.md)
- [Lambda Function](lambda-function.md)
- [Working with Dates & Times in Python](dates_and_times.md)
- [Regular Expressions in Python](regular_expressions.md)
- [JSON module](json-module.md)
- [OOPs](OOPs.md)

Wyświetl plik

@ -0,0 +1,88 @@
# Lambda Function
Lambda functions in Python are small, anonymous functions that can be created on-the-fly. They are defined using the `lambda` keyword instead of the `def` keyword used for regular functions. Lambda functions are typically used for simple tasks where a full-blown function definition is not necessary.
Here's an example of a lambda function that adds two numbers:
```python
add = lambda x, y: x + y
print(add(3, 5)) # Output: 8
```
The above lambda function is equivalent to the following regular function:
```python
def add(x, y):
return x + y
print(add(3, 5)) # Output: 8
```
The difference between a regular function and a lambda function lies mainly in syntax and usage. Here are some key distinctions:
1. **Syntax**: Lambda functions are defined using the `lambda` keyword, followed by parameters and a colon, while regular functions use the `def` keyword, followed by the function name, parameters, and a colon.
2. **Name**: Lambda functions are anonymous; they do not have a name like regular functions. Regular functions are defined with a name.
3. **Complexity**: Lambda functions are suitable for simple, one-liner tasks. They are not meant for complex operations or tasks that require multiple lines of code. Regular functions can handle more complex logic and can contain multiple statements and lines of code.
4. **Usage**: Lambda functions are often used in situations where a function is needed as an argument to another function (e.g., sorting, filtering, mapping), or when you want to write concise code without defining a separate function.
Lambda functions are used primarily for convenience and brevity in situations where a full function definition would be overkill or too cumbersome. They are handy for tasks that require a small, one-time function and can improve code readability when used judiciously.
## Use Cases
1. **Sorting**: Lambda functions are often used as key functions for sorting lists, dictionaries, or other data structures based on specific criteria. For example:
```python
students = [
{"name": "Alice", "age": 20},
{"name": "Bob", "age": 18},
{"name": "Charlie", "age": 22}
]
sorted_students = sorted(students, key=lambda x: x["age"])
```
2. **Filtering**: Lambda functions can be used with filter() to selectively include elements from a collection based on a condition. For instance:
```python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
```
3. **Mapping**: Lambda functions are useful with map() to apply a transformation to each element of a collection. For example:
```python
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
```
4. **Event Handling**: In GUI programming or event-driven systems, lambda functions can be used as event handlers to execute specific actions when an event occurs. For instance:
```python
button.clicked.connect(lambda: self.on_button_click(argument))
```
5. **Callback Functions**: Lambda functions can be passed as callback functions to other functions, especially when a simple operation needs to be performed in response to an event. For example:
```python
def process_data(data, callback):
# Process data
result = ...
# Execute callback function
callback(result)
process_data(data, lambda x: print("Result:", x))
```
6. **Anonymous Functions in Higher-Order Functions**: Lambda functions are commonly used with higher-order functions such as reduce(), which applies a rolling computation to sequential pairs of values in a list. For example:
```python
from functools import reduce
numbers = [1, 2, 3, 4, 5]
sum_of_numbers = reduce(lambda x, y: x + y, numbers)
```
These are just a few examples of how lambda functions can be applied in Python to simplify code and make it more expressive. They are particularly useful in situations where a small, one-time function is needed and defining a separate named function would be excessive.
In conclusion, **lambda functions** in Python offer a concise and powerful way to handle simple tasks without the need for full function definitions. Their versatility, especially in scenarios like sorting, filtering, and event handling, makes them valuable tools for improving code readability and efficiency. By mastering lambda functions, you can enhance your Python programming skills and tackle various tasks with elegance and brevity.

Wyświetl plik

@ -1,3 +1,3 @@
# List of sections
- [Section title](filename.md)
- [Introduction to MySQL and Queries](intro_mysql_queries.md)

Wyświetl plik

@ -0,0 +1,371 @@
# Introduction to MySQL Queries
MySQL is a widely-used open-source relational database management system (RDBMS) that utilizes SQL (Structured Query Language) for managing and querying data. In Python, the **mysql-connector-python** library allows you to connect to MySQL databases and execute SQL queries, providing a way to interact with the database from within a Python program.
## Prerequisites
* Python and MySQL Server must be installed and configured.
* The library: **mysql-connector-python** must be installed.
## Establishing connection with server
To establish a connection with the MySQL server, you need to import the **mysql.connector** module and create a connection object using the **connect()** function by providing the prompt server details as mentioned.
```python
import mysql.connector
con = mysql.connector.connect(
host ="localhost",
user ="root",
passwd ="12345"
)
print((con.is_connected()))
```
Having established a connection with the server, you get the following output :
```
True
```
## Creating a Database [CREATE]
To create a database, you need to execute the **CREATE DATABASE** query. The following code snippet demonstrates how to create a database named **GSSOC**.
```python
import mysql.connector
# Establish the connection
conn = mysql.connector.connect(
host="localhost",
user="root",
password="12345"
)
# Create a cursor object
cursor = conn.cursor()
# Execute the query to show databases
cursor.execute("SHOW DATABASES")
# Fetch and print the databases
databases = cursor.fetchall()
for database in databases:
print(database[0])
# Execute the query to create database GSSOC
cursor.execute("CREATE DATABASE GSSOC")
print("\nAfter creation of the database\n")
# Execute the query to show databases
cursor.execute("SHOW DATABASES")
# Fetch and print the databases
databases = cursor.fetchall()
for database in databases:
print(database[0])
cursor.close()
conn.close()
```
You can observe in the output below, after execution of the query a new database named **GSSOC** has been created.
#### Output:
```
information_schema
mysql
performance_schema
sakila
sys
world
After creation of the database
gssoc
information_schema
mysql
performance_schema
sakila
sys
world
```
## Creating a Table in the Database [CREATE]
Now, we will create a table in the database. We will create a table named **example_table** in the database **GSSOC**. We will execute **CREATE TABLE** query and provide the fields for the table as mentioned in the code below:
```python
import mysql.connector
# Establish the connection
conn = mysql.connector.connect(
host="localhost",
user="root",
password="12345"
)
# Create a cursor object
cursor = conn.cursor()
# Execute the query to show tables
cursor.execute("USE GSSOC")
cursor.execute("SHOW TABLES")
# Fetch and print the tables
tables = cursor.fetchall()
print("Before creation of table\n")
for table in tables:
print(table[0])
create_table_query = """
CREATE TABLE example_table (
name VARCHAR(255) NOT NULL,
age INT NOT NULL,
email VARCHAR(255)
)
"""
# Execute the query
cursor.execute(create_table_query)
# Commit the changes
conn.commit()
print("\nAfter creation of Table\n")
# Execute the query to show tables in GSSOC
cursor.execute("SHOW TABLES")
# Fetch and print the tables
tables = cursor.fetchall()
for table in tables:
print(table[0])
cursor.close()
conn.close()
```
#### Output:
```
Before creation of table
After creation of Table
example_table
```
## Inserting Data [INSERT]
To insert data in an existing table, the **INSERT INTO** query is used, followed by the name of the table in which the data needs to be inserted. The following code demonstrates the insertion of multiple records in the table by **executemany()**.
```python
import mysql.connector
# Establish the connection
conn = mysql.connector.connect(
host="localhost",
user="root",
password="12345"
)
# Create a cursor object
cursor = conn.cursor()
cursor.execute("USE GSSOC")
# SQL query to insert data
insert_data_query = """
INSERT INTO example_table (name, age, email)
VALUES (%s, %s, %s)
"""
# Data to be inserted
data_to_insert = [
("John Doe", 28, "john.doe@example.com"),
("Jane Smith", 34, "jane.smith@example.com"),
("Sam Brown", 22, "sam.brown@example.com")
]
# Execute the query for each data entry
cursor.executemany(insert_data_query, data_to_insert)
conn.commit()
cursor.close()
conn.close()
```
## Displaying Data [SELECT]
To display the data from a table, the **SELECT** query is used. The following code demonstrates the display of data from the table.
```python
import mysql.connector
# Establish the connection
conn = mysql.connector.connect(
host="localhost",
user="root",
password="12345"
)
# Create a cursor object
cursor = conn.cursor()
cursor.execute("USE GSSOC")
# SQL query to display data
display_data_query = "SELECT * FROM example_table"
# Execute the query for each data entry
cursor.execute(display_data_query)
# Fetch all the rows
rows = cursor.fetchall()
# Print the column names
column_names = [desc[0] for desc in cursor.description]
print(column_names)
# Print the rows
for row in rows:
print(row)
cursor.close()
conn.close()
```
#### Output :
```
['name', 'age', 'email']
('John Doe', 28, 'john.doe@example.com')
('Jane Smith', 34, 'jane.smith@example.com')
('Sam Brown', 22, 'sam.brown@example.com')
```
## Updating Data [UPDATE]
To update data in the table, **UPDATE** query is used. In the following code, we will be updating the email and age of the record where the name is John Doe.
```python
import mysql.connector
# Establish the connection
conn = mysql.connector.connect(
host="localhost",
user="root",
password="12345"
)
# Create a cursor object
cursor = conn.cursor()
cursor.execute("USE GSSOC")
# SQL query to display data
display_data_query = "SELECT * FROM example_table"
# SQL Query to update data of John Doe
update_data_query = """
UPDATE example_table
SET age = %s, email = %s
WHERE name = %s
"""
# Data to be updated
data_to_update = (30, "new.email@example.com", "John Doe")
# Execute the query
cursor.execute(update_data_query, data_to_update)
# Commit the changes
conn.commit()
# Execute the query for each data entry
cursor.execute(display_data_query)
# Fetch all the rows
rows = cursor.fetchall()
# Print the column names
column_names = [desc[0] for desc in cursor.description]
print(column_names)
# Print the rows
for row in rows:
print(row)
cursor.close()
conn.close()
```
#### Output:
```
['name', 'age', 'email']
('John Doe', 30, 'new.email@example.com')
('Jane Smith', 34, 'jane.smith@example.com')
('Sam Brown', 22, 'sam.brown@example.com')
```
## Deleting Data [DELETE]
In this segment, we will Delete the record named "John Doe" using the **DELETE** and **WHERE** statements in the query. The following code explains the same and the observe the change in output.
```python
import mysql.connector
# Establish the connection
conn = mysql.connector.connect(
host="localhost",
user="root",
password="12345"
)
# Create a cursor object
cursor = conn.cursor()
cursor.execute("USE GSSOC")
# SQL query to display data
display_data_query = "SELECT * FROM example_table"
# SQL query to delete data
delete_data_query = "DELETE FROM example_table WHERE name = %s"
# Data to be deleted
data_to_delete = ("John Doe",)
# Execute the query
cursor.execute(delete_data_query, data_to_delete)
# Commit the changes
conn.commit()
# Execute the query for each data entry
cursor.execute(display_data_query)
# Fetch all the rows
rows = cursor.fetchall()
# Print the column names
column_names = [desc[0] for desc in cursor.description]
print(column_names)
# Print the rows
for row in rows:
print(row)
cursor.close()
conn.close()
```
#### Output:
```
['name', 'age', 'email']
('Jane Smith', 34, 'jane.smith@example.com')
('Sam Brown', 22, 'sam.brown@example.com')
```
## Deleting the Table/Database [DROP]
For deleting a table, you can use the **DROP** query in the following manner:
```python
import mysql.connector
# Establish the connection
conn = mysql.connector.connect(
host="localhost",
user="root",
password="12345"
)
# Create a cursor object
cursor = conn.cursor()
cursor.execute("USE GSSOC")
# SQL query to delete the table
delete_table_query = "DROP TABLE IF EXISTS example_table"
# Execute the query
cursor.execute(delete_table_query)
# Verify the table deletion
cursor.execute("SHOW TABLES LIKE 'example_table'")
result = cursor.fetchone()
cursor.close()
conn.close()
if result:
print("Table deletion failed.")
else:
print("Table successfully deleted.")
```
#### Output:
```
Table successfully deleted.
```
Similarly, you can delete the database also by using the **DROP** and accordingly changing the query to be executed.

Wyświetl plik

@ -1,5 +1,6 @@
# List of sections
- [Pandas Introduction and Dataframes in Pandas](introduction.md)
- [Pandas Series Vs NumPy ndarray](pandas_series_vs_numpy_ndarray.md)
- [Pandas Descriptive Statistics](Descriptive_Statistics.md)
- [Group By Functions with Pandas](GroupBy_Functions_Pandas.md)

Wyświetl plik

@ -0,0 +1,244 @@
# Introduction_to_Pandas_Library_and_DataFrames
**As you have learnt Python Programming , now it's time for some applications.**
- Machine Learning and Data Science is the emerging field of today's time , to work in this this field your first step should be `Data Science` as Machine Learning is all about data.
- To begin with Data Science your first tool will be `Pandas Library`.
## Introduction of Pandas Library
Pandas is a data analysis and manipulation tool, built on top of the python programming language. Pandas got its name from the term Panel data (Pa from Panel and da from data). Panel data is a data which have rows and columns in it like excel spreadsheets, csv files etc.
**To use Pandas, first weve to import it.**
## Why pandas?
* Pandas provides a simple-to-use but very capable set of functions that you can use on your data.
* It is also associate with other machine learning libraries , so it is important to learn it.
* For example - It is highly used to transform tha data which will be use by machine learning model during the training.
```python
# Importing the pandas
import pandas as pd
```
*To import any module in Python use “import 'module name' ” command, I used “pd” as pandas abbreviation because we dont need to type pandas every time only type “pd” to use pandas.*
```python
# To check available pandas version
print(f"Pandas Version is : {pd.__version__}")
```
Pandas Version is : 2.1.4
## Understanding Pandas data types
Pandas has two main data types : `Series` and `DataFrames`
* `pandas.Series` is a 1-dimensional column of data.
* `pandas.DataFrames` is 2 -dimensional data table having rows and columns.
### 1. Series datatype
**To creeate a series you can use `pd.Series()` and passing a python list inside()**.
Note: S in Series is capital if you use small s it will give you an error.
> Let's create a series
```python
# Creating a series of car companies
cars = pd.Series(["Honda","Audi","Thar","BMW"])
cars
```
0 Honda
1 Audi
2 Thar
3 BMW
dtype: object
The above code creates a Series of cars companies the name of series is “cars” the code “pd.Series([“Honda” , “Audi” , “Thar”, "BMW"])” means Hey! pandas (pd) create a Series of cars named "Honda" , "Audi" , "Thar" and "BMW".
The default index of a series is 0,1,2….(Remember it starts from 0)
To change the index of any series set the “index” parameter accordingly. It takes the list of index values:
```python
cars = pd.Series(["Honda","Audi","Thar","BMW"],index = ["A" , "B" , "C" ,"D"])
cars
```
A Honda
B Audi
C Thar
D BMW
dtype: object
You can see that the index has been changed from numbers to A, B ,C and D.
And the mentioned dtype tells us about the type of data we have in the series.
### 2. DataFrames datatype
DataFrame contains rows and columns like a csv file have.
You can also create a DataFrame by using `pd.DataFrame()` and passing it a Python dictionary.
```python
# Let's create
cars_with_colours = pd.DataFrame({"Cars" : ["BMW","Audi","Thar","Honda"],
"Colour" : ["Black","White","Red","Green"]})
print(cars_with_colours)
```
Cars Colour
0 BMW Black
1 Audi White
2 Thar Red
3 Honda Green
The dictionary key is the `column name` and value are the `column data`.
*You can also create a DataFrame with the help of series.*
```python
# Let's create two series
students = pd.Series(["Ram","Mohan","Krishna","Shivam"])
age = pd.Series([19,20,21,24])
students
```
0 Ram
1 Mohan
2 Krishna
3 Shivam
dtype: object
```python
age
```
0 19
1 20
2 21
3 24
dtype: int64
```python
# Now let's create a dataframe with the help of above series
# pass the series name to the dictionary value
record = pd.DataFrame({"Student_Name":students ,
"Age" :age})
print(record)
```
Student_Name Age
0 Ram 19
1 Mohan 20
2 Krishna 21
3 Shivam 24
```python
# To print the list of columns names
record.columns
```
Index(['Student_Name', 'Age'], dtype='object')
### Describe Data
**The good news is that pandas has many built-in functions which allow you to quickly get information about a DataFrame.**
Let's explore the `record` dataframe
#### 1. Use `.dtypes` to find what datatype a column contains
```python
record.dtypes
```
Student_Name object
Age int64
dtype: object
#### 2. use `.describe()` for statistical overview.
```python
print(record.describe()) # It only display the results for numeric data
```
Age
count 4.000000
mean 21.000000
std 2.160247
min 19.000000
25% 19.750000
50% 20.500000
75% 21.750000
max 24.000000
#### 3. Use `.info()` to find information about the dataframe
```python
record.info()
```
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Student_Name 4 non-null object
1 Age 4 non-null int64
dtypes: int64(1), object(1)
memory usage: 196.0+ bytes