From 5c3e1c2ed86b57838d16151e4d9c305eae565084 Mon Sep 17 00:00:00 2001 From: Ananyagra24 <155280507+Ananyagra24@users.noreply.github.com> Date: Sun, 12 May 2024 21:49:55 +0530 Subject: [PATCH 01/38] Create History --- contrib/History | 1 + 1 file changed, 1 insertion(+) create mode 100644 contrib/History diff --git a/contrib/History b/contrib/History new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/contrib/History @@ -0,0 +1 @@ + From b8e682d2fd427f8c76bde3bc30207cad327aec5d Mon Sep 17 00:00:00 2001 From: Ananyagra24 <155280507+Ananyagra24@users.noreply.github.com> Date: Mon, 13 May 2024 08:40:22 +0530 Subject: [PATCH 02/38] Delete contrib/History --- contrib/History | 1 - 1 file changed, 1 deletion(-) delete mode 100644 contrib/History diff --git a/contrib/History b/contrib/History deleted file mode 100644 index 8b13789..0000000 --- a/contrib/History +++ /dev/null @@ -1 +0,0 @@ - From 83809066303a7f962f2063d1613bad26f9776c1d Mon Sep 17 00:00:00 2001 From: Ananyagra24 <155280507+Ananyagra24@users.noreply.github.com> Date: Mon, 13 May 2024 21:10:18 +0530 Subject: [PATCH 03/38] Create dice_roller.md --- contrib/mini-projects/dice_roller.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 contrib/mini-projects/dice_roller.md diff --git a/contrib/mini-projects/dice_roller.md b/contrib/mini-projects/dice_roller.md new file mode 100644 index 0000000..c083934 --- /dev/null +++ b/contrib/mini-projects/dice_roller.md @@ -0,0 +1,19 @@ +``` +import random +def dice(): + dice_no = random.choice([1,2,3,4,5,6]) + return "You got " + str(dice_no) +def roll_dice(): + print("Hey Guys, you will now roll a single dice using Python!") + while True: + start=input("Type \'k\' to roll the dice: ").lower() + if start != 'k': + print("Invalid input. Please try again.") + continue + print(dice()) + roll_again = input("Do you want to reroll? (Yes/No): ").lower() + if roll_again != 'yes': + break + print("Thanks for rolling the dice.") +roll_dice() +``` From f8a67cf65dc3d70cf0a81a0cebd55770f0ffc728 Mon Sep 17 00:00:00 2001 From: Ananyagra24 <155280507+Ananyagra24@users.noreply.github.com> Date: Mon, 13 May 2024 21:11:01 +0530 Subject: [PATCH 04/38] Update index.md --- contrib/mini-projects/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/mini-projects/index.md b/contrib/mini-projects/index.md index 82596a2..f60b286 100644 --- a/contrib/mini-projects/index.md +++ b/contrib/mini-projects/index.md @@ -1,3 +1,3 @@ # List of sections -- [Section title](filename.md) +- [Dice Roller](dice_roller.md) From ea32f2bd8ce5c16960c66e72b6e886d9b260f51d Mon Sep 17 00:00:00 2001 From: Hema Sree Date: Wed, 15 May 2024 17:49:44 +0530 Subject: [PATCH 05/38] Added intro to numpy --- contrib/numpy/Introduction.md | 36 +++++++++++++++++++++++++++++++++++ contrib/numpy/index.md | 2 +- 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 contrib/numpy/Introduction.md diff --git a/contrib/numpy/Introduction.md b/contrib/numpy/Introduction.md new file mode 100644 index 0000000..59a1938 --- /dev/null +++ b/contrib/numpy/Introduction.md @@ -0,0 +1,36 @@ +# Introduction + +## What is Numpy? + +NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays. It is the fundamental package for scientific computing with Python. It is open-source software. + +## Features of NumPy + +NumPy has various features including these important ones: + +1. A powerful N-dimensional array object +2. Sophisticated (broadcasting) functions +3. Tools for integrating C/C++ and Fortran code +4. Useful linear algebra, Fourier transform, and random number capabilities + +## Install Numpy + +Before installing Numpy, ensure you have Python installed on your system. You can download and install Python from the [official Python website](https://www.python.org/). + +Numpy can be installed via the following pip command: + +```bash +pip install numpy + +``` + +# How to import NumPy + +To access NumPy and its functions import it in your Python code like this: + +```bash +import numpy as np + +``` + +We shorten the imported name to np for better readability of code using NumPy. This is a widely adopted convention that makes your code more readable for everyone working on it. We recommend to always use import numpy as np. diff --git a/contrib/numpy/index.md b/contrib/numpy/index.md index 82596a2..c6bf23c 100644 --- a/contrib/numpy/index.md +++ b/contrib/numpy/index.md @@ -1,3 +1,3 @@ # List of sections -- [Section title](filename.md) +- [Introduction](Introduction.md) From 59e79c7627db41589dc554e1440d0ee5aacf3c9c Mon Sep 17 00:00:00 2001 From: Hema Sree Date: Wed, 15 May 2024 17:57:30 +0530 Subject: [PATCH 06/38] Added numpy intro --- contrib/numpy/Introduction.md | 32 +++++++++++++------------------- 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/contrib/numpy/Introduction.md b/contrib/numpy/Introduction.md index 59a1938..c437c48 100644 --- a/contrib/numpy/Introduction.md +++ b/contrib/numpy/Introduction.md @@ -1,36 +1,30 @@ # Introduction -## What is Numpy? +## What is NumPy? -NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays. It is the fundamental package for scientific computing with Python. It is open-source software. +NumPy is a powerful array-processing library in Python, essential for scientific computing. It provides efficient data structures and tools for working with multidimensional arrays. -## Features of NumPy +## Key Features -NumPy has various features including these important ones: +1. **Efficient Arrays:** NumPy offers high-performance N-dimensional array objects for swift data manipulation. +2. **Broadcasting:** Advanced broadcasting enables seamless element-wise operations on arrays of varying shapes. +3. **Interoperability:** NumPy seamlessly integrates with C, C++, and Fortran, enhancing performance and versatility. +4. **Mathematical Tools:** Comprehensive support for linear algebra, Fourier transforms, and random number generation. -1. A powerful N-dimensional array object -2. Sophisticated (broadcasting) functions -3. Tools for integrating C/C++ and Fortran code -4. Useful linear algebra, Fourier transform, and random number capabilities +## Installation -## Install Numpy - -Before installing Numpy, ensure you have Python installed on your system. You can download and install Python from the [official Python website](https://www.python.org/). - -Numpy can be installed via the following pip command: +Ensure Python is installed in your system. If not you can install it from here([official Python website](https://www.python.org/)),then install NumPy via: ```bash pip install numpy - ``` -# How to import NumPy +# Importing NumPy -To access NumPy and its functions import it in your Python code like this: +To access NumPy functions, import it with the alias `np`: -```bash +```python import numpy as np - ``` -We shorten the imported name to np for better readability of code using NumPy. This is a widely adopted convention that makes your code more readable for everyone working on it. We recommend to always use import numpy as np. +Using `np` as an alias enhances code readability and is a widely adopted convention. From 9f482ac8181b47e80c5469025ab067bab96ae54a Mon Sep 17 00:00:00 2001 From: Hema Sree Date: Wed, 15 May 2024 17:58:33 +0530 Subject: [PATCH 07/38] intro numpy --- contrib/numpy/Introduction.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/numpy/Introduction.md b/contrib/numpy/Introduction.md index c437c48..c0f5f52 100644 --- a/contrib/numpy/Introduction.md +++ b/contrib/numpy/Introduction.md @@ -19,7 +19,7 @@ Ensure Python is installed in your system. If not you can install it from here([ pip install numpy ``` -# Importing NumPy +## Importing NumPy To access NumPy functions, import it with the alias `np`: From 2189d3914cb4194df2ca02eb33a2f0d11cd07844 Mon Sep 17 00:00:00 2001 From: Ritesh <112797055+Antiquely3059@users.noreply.github.com> Date: Wed, 15 May 2024 18:53:35 +0530 Subject: [PATCH 08/38] Create Rock Paper Scissors Game.md --- .../mini-projects/Rock Paper Scissors Game.md | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 contrib/mini-projects/Rock Paper Scissors Game.md diff --git a/contrib/mini-projects/Rock Paper Scissors Game.md b/contrib/mini-projects/Rock Paper Scissors Game.md new file mode 100644 index 0000000..ed815d5 --- /dev/null +++ b/contrib/mini-projects/Rock Paper Scissors Game.md @@ -0,0 +1,48 @@ +```python +import tkinter as tk +import random + +def determine_winner(user_choice, computer_choice): + """Determine the winner of the game.""" + if user_choice == computer_choice: + return "It's a tie!", computer_choice + elif (user_choice == "rock" and computer_choice == "scissors") or \ + (user_choice == "paper" and computer_choice == "rock") or \ + (user_choice == "scissors" and computer_choice == "paper"): + return "You win!", computer_choice + else: + return "Computer wins!", computer_choice + +def play_game(): + """Play the game and display the result.""" + user_choice = user_var.get() + computer_choice = random.choice(["rock", "paper", "scissors"]) + result, computer_pick = determine_winner(user_choice, computer_choice) + result_label.config(text=result) + computer_label.config(text=f"Computer picked: {computer_pick}") + +# Create main window +root = tk.Tk() +root.title("Rock Paper Scissors") + +# User choice options +user_var = tk.StringVar() +user_var.set("rock") # Default choice +choices = ["rock", "paper", "scissors"] +for choice in choices: + rb = tk.Radiobutton(root, text=choice, variable=user_var, value=choice) + rb.pack() + +# Play button +play_button = tk.Button(root, text="Play", command=play_game) +play_button.pack() + +# Result label +result_label = tk.Label(root, text="", font=("Helvetica", 16)) +result_label.pack() + +# Computer pick label +computer_label = tk.Label(root, text="", font=("Helvetica", 12)) +computer_label.pack() + +root.mainloop() From 8f0c49efa87011c70be9d9c89889c2d9d63b8ec1 Mon Sep 17 00:00:00 2001 From: Ritesh <112797055+Antiquely3059@users.noreply.github.com> Date: Wed, 15 May 2024 18:59:12 +0530 Subject: [PATCH 09/38] Update Rock Paper Scissors Game.md --- contrib/mini-projects/Rock Paper Scissors Game.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/contrib/mini-projects/Rock Paper Scissors Game.md b/contrib/mini-projects/Rock Paper Scissors Game.md index ed815d5..9cc17ee 100644 --- a/contrib/mini-projects/Rock Paper Scissors Game.md +++ b/contrib/mini-projects/Rock Paper Scissors Game.md @@ -1,3 +1,12 @@ + +Here's how it looks: + +# Rock Paper Scissors Game + +This is a simple implementation of the classic rock-paper-scissors game in Python. + +## Code: + ```python import tkinter as tk import random From c79f13a28c7f21033c4c85d14a15fb675ee5bd84 Mon Sep 17 00:00:00 2001 From: Ritesh <112797055+Antiquely3059@users.noreply.github.com> Date: Wed, 15 May 2024 19:02:05 +0530 Subject: [PATCH 10/38] Update Rock Paper Scissors Game.md --- contrib/mini-projects/Rock Paper Scissors Game.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/contrib/mini-projects/Rock Paper Scissors Game.md b/contrib/mini-projects/Rock Paper Scissors Game.md index 9cc17ee..b08a268 100644 --- a/contrib/mini-projects/Rock Paper Scissors Game.md +++ b/contrib/mini-projects/Rock Paper Scissors Game.md @@ -1,6 +1,3 @@ - -Here's how it looks: - # Rock Paper Scissors Game This is a simple implementation of the classic rock-paper-scissors game in Python. From 25a319ff3cb82a26ddc8f0b272713bb68a8fea77 Mon Sep 17 00:00:00 2001 From: Ritesh <112797055+Antiquely3059@users.noreply.github.com> Date: Wed, 15 May 2024 19:54:12 +0530 Subject: [PATCH 11/38] Update Rock Paper Scissors Game.md --- .../mini-projects/Rock Paper Scissors Game.md | 36 +++++++++++++++++-- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/contrib/mini-projects/Rock Paper Scissors Game.md b/contrib/mini-projects/Rock Paper Scissors Game.md index b08a268..c1a5ecf 100644 --- a/contrib/mini-projects/Rock Paper Scissors Game.md +++ b/contrib/mini-projects/Rock Paper Scissors Game.md @@ -2,8 +2,19 @@ This is a simple implementation of the classic rock-paper-scissors game in Python. -## Code: +## Code Explanation: +In this section, we import the required libraries (`tkinter` for GUI and `random` for generating computer choices) and define two functions: + +- `determine_winner(user_choice, computer_choice)`: + - This function determines the winner of the game based on the choices made by the user and the computer. + - It returns a tuple containing the result of the game and the computer's choice. + +- `play_game()`: + - This function handles the gameplay logic. + - It gets the user's choice from the radio buttons, generates a random choice for the computer, determines the winner using the `determine_winner()` function, and updates the result and computer pick labels accordingly. + +### Imports and Function Definitions: ```python import tkinter as tk import random @@ -26,7 +37,9 @@ def play_game(): result, computer_pick = determine_winner(user_choice, computer_choice) result_label.config(text=result) computer_label.config(text=f"Computer picked: {computer_pick}") - +``` +### GUI Setup: +```python # Create main window root = tk.Tk() root.title("Rock Paper Scissors") @@ -38,7 +51,14 @@ choices = ["rock", "paper", "scissors"] for choice in choices: rb = tk.Radiobutton(root, text=choice, variable=user_var, value=choice) rb.pack() - +``` +- Here, we create the main window for the game using `tkinter.Tk()`. We set the title to "Rock Paper Scissors". +- We define a StringVar to store the user's choice and set the default choice to "rock". +- We create radio buttons for the user to choose from ("rock", "paper", "scissors") and pack them into the main window. +``` +``` +### Play Button and Result Labels: +```python # Play button play_button = tk.Button(root, text="Play", command=play_game) play_button.pack() @@ -50,5 +70,15 @@ result_label.pack() # Computer pick label computer_label = tk.Label(root, text="", font=("Helvetica", 12)) computer_label.pack() +``` +- We create a "Play" button that triggers the play_game() function when clicked, using tkinter.Button. +- We create two labels to display the result of the game (result_label) and the computer's choice (computer_label). Both labels initially display no text and are packed into the main window. +``` +``` +### Mainloop: +```python root.mainloop() +``` +- Finally, we start the Tkinter event loop using root.mainloop(), which keeps the GUI window open and responsive until the user closes it. +- From 1196e6ee89d05deb8186e815838c90ab1b49caec Mon Sep 17 00:00:00 2001 From: Ritesh <112797055+Antiquely3059@users.noreply.github.com> Date: Wed, 15 May 2024 19:57:34 +0530 Subject: [PATCH 12/38] Update Rock Paper Scissors Game.md --- contrib/mini-projects/Rock Paper Scissors Game.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/contrib/mini-projects/Rock Paper Scissors Game.md b/contrib/mini-projects/Rock Paper Scissors Game.md index c1a5ecf..36326b0 100644 --- a/contrib/mini-projects/Rock Paper Scissors Game.md +++ b/contrib/mini-projects/Rock Paper Scissors Game.md @@ -53,7 +53,7 @@ for choice in choices: rb.pack() ``` - Here, we create the main window for the game using `tkinter.Tk()`. We set the title to "Rock Paper Scissors". -- We define a StringVar to store the user's choice and set the default choice to "rock". +- We define a `StringVar` to store the user's choice and set the default choice to "rock". - We create radio buttons for the user to choose from ("rock", "paper", "scissors") and pack them into the main window. ``` ``` @@ -71,8 +71,8 @@ result_label.pack() computer_label = tk.Label(root, text="", font=("Helvetica", 12)) computer_label.pack() ``` -- We create a "Play" button that triggers the play_game() function when clicked, using tkinter.Button. -- We create two labels to display the result of the game (result_label) and the computer's choice (computer_label). Both labels initially display no text and are packed into the main window. +- We create a "Play" button that triggers the `play_game()` function when clicked, using `tkinter.Button`. +- We create two labels to display the result of the game (`result_label`) and the computer's choice (`computer_label`). Both labels initially display no text and are packed into the main window. ``` ``` @@ -80,5 +80,5 @@ computer_label.pack() ```python root.mainloop() ``` -- Finally, we start the Tkinter event loop using root.mainloop(), which keeps the GUI window open and responsive until the user closes it. +- Finally, we start the Tkinter event loop using `root.mainloop()`, which keeps the GUI window open and responsive until the user closes it. - From 989278ebe3ac868d63f6f66b9461474fb2f8679e Mon Sep 17 00:00:00 2001 From: Hema Sree Date: Thu, 16 May 2024 13:08:37 +0530 Subject: [PATCH 13/38] change file name --- contrib/numpy/Introduction.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/numpy/Introduction.md b/contrib/numpy/Introduction.md index c0f5f52..eb3af67 100644 --- a/contrib/numpy/Introduction.md +++ b/contrib/numpy/Introduction.md @@ -21,7 +21,7 @@ pip install numpy ## Importing NumPy -To access NumPy functions, import it with the alias `np`: +To access NumPy functions, import it with the alias `np`. ```python import numpy as np From 7ae451cc067a73adc6068b18ddb461cea84942c6 Mon Sep 17 00:00:00 2001 From: Hema Sree Date: Thu, 16 May 2024 13:12:41 +0530 Subject: [PATCH 14/38] change file name --- contrib/numpy/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/numpy/index.md b/contrib/numpy/index.md index c6bf23c..5d3f63b 100644 --- a/contrib/numpy/index.md +++ b/contrib/numpy/index.md @@ -1,3 +1,3 @@ # List of sections -- [Introduction](Introduction.md) +- [Introduction](introduction.md) From 9bb50dcf528efb9cd1dbbd8970e5a52130c86482 Mon Sep 17 00:00:00 2001 From: HEMA SREE VEMULAMADA <109607812+Hemav009@users.noreply.github.com> Date: Thu, 16 May 2024 13:14:26 +0530 Subject: [PATCH 15/38] Rename Introduction.md to introduction.md --- contrib/numpy/{Introduction.md => introduction.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename contrib/numpy/{Introduction.md => introduction.md} (100%) diff --git a/contrib/numpy/Introduction.md b/contrib/numpy/introduction.md similarity index 100% rename from contrib/numpy/Introduction.md rename to contrib/numpy/introduction.md From 2ff1b14b5cb95f5280b709cff64dd399ce570de4 Mon Sep 17 00:00:00 2001 From: Ritesh <112797055+Antiquely3059@users.noreply.github.com> Date: Fri, 17 May 2024 08:45:09 +0530 Subject: [PATCH 16/38] Update index.md --- contrib/mini-projects/index.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/contrib/mini-projects/index.md b/contrib/mini-projects/index.md index 82596a2..37ebc9b 100644 --- a/contrib/mini-projects/index.md +++ b/contrib/mini-projects/index.md @@ -1,3 +1,4 @@ # List of sections -- [Section title](filename.md) +- [Rock Paper Scissors Game](Rock Paper Scissors Game.md) + From 7af22b698cca0a7bbf993319894d8ca69e62bf89 Mon Sep 17 00:00:00 2001 From: Ritesh <112797055+Antiquely3059@users.noreply.github.com> Date: Fri, 17 May 2024 08:45:55 +0530 Subject: [PATCH 17/38] Rename Rock Paper Scissors Game.md to Rock_Paper_Scissors_Game.md --- .../{Rock Paper Scissors Game.md => Rock_Paper_Scissors_Game.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename contrib/mini-projects/{Rock Paper Scissors Game.md => Rock_Paper_Scissors_Game.md} (100%) diff --git a/contrib/mini-projects/Rock Paper Scissors Game.md b/contrib/mini-projects/Rock_Paper_Scissors_Game.md similarity index 100% rename from contrib/mini-projects/Rock Paper Scissors Game.md rename to contrib/mini-projects/Rock_Paper_Scissors_Game.md From f0d0b515a21467b985766163a027f3a1d6cf9899 Mon Sep 17 00:00:00 2001 From: Ritesh <112797055+Antiquely3059@users.noreply.github.com> Date: Fri, 17 May 2024 08:46:20 +0530 Subject: [PATCH 18/38] Update index.md --- contrib/mini-projects/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/mini-projects/index.md b/contrib/mini-projects/index.md index 37ebc9b..7d0285a 100644 --- a/contrib/mini-projects/index.md +++ b/contrib/mini-projects/index.md @@ -1,4 +1,4 @@ # List of sections -- [Rock Paper Scissors Game](Rock Paper Scissors Game.md) +- [Rock Paper Scissors Game](Rock_Paper_Scissors_Game.md) From 04caabe01b99ba9337e158c9c1018335eed35bcc Mon Sep 17 00:00:00 2001 From: HimakarC <116370824+HimakarC@users.noreply.github.com> Date: Fri, 17 May 2024 17:06:47 +0530 Subject: [PATCH 19/38] Update index.md --- contrib/pandas/index.md | 1 + 1 file changed, 1 insertion(+) diff --git a/contrib/pandas/index.md b/contrib/pandas/index.md index 5c0f2b4..aadd970 100644 --- a/contrib/pandas/index.md +++ b/contrib/pandas/index.md @@ -1,3 +1,4 @@ # List of sections - [Pandas Series Vs NumPy ndarray](pandas_series_vs_numpy_ndarray.md) +- [Excel Operations using Pandas DataFrame](excel_with_pandas.md) From 4ffc87b269773a98dfc5824abb32117684b85211 Mon Sep 17 00:00:00 2001 From: HimakarC <116370824+HimakarC@users.noreply.github.com> Date: Fri, 17 May 2024 17:07:17 +0530 Subject: [PATCH 20/38] Create excel_with_pandas.md --- contrib/pandas/excel_with_pandas.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 contrib/pandas/excel_with_pandas.md diff --git a/contrib/pandas/excel_with_pandas.md b/contrib/pandas/excel_with_pandas.md new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/contrib/pandas/excel_with_pandas.md @@ -0,0 +1 @@ + From 56170159e1ca6e88cfcee929e3316c7dac4432da Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 17 May 2024 18:09:43 +0530 Subject: [PATCH 21/38] written --- contrib/pandas/excel_with_pandas.md | 50 +++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/contrib/pandas/excel_with_pandas.md b/contrib/pandas/excel_with_pandas.md index 8b13789..6902c3f 100644 --- a/contrib/pandas/excel_with_pandas.md +++ b/contrib/pandas/excel_with_pandas.md @@ -1 +1,51 @@ +# Pandas DataFrame + +The Pandas DataFrame is a two-dimensional, size-mutable, and possibly heterogeneous tabular data format with labelled axes. A data frame is a two-dimensional data structure in which the data can be organised in rows and columns. Pandas DataFrames are comprised of three main components: data, rows, and columns. + +In the real world, Pandas DataFrames are formed by importing datasets from existing storage, which can be a Excel file, a SQL database or CSV file. Pandas DataFrames may be constructed from lists, dictionaries, or lists of dictionaries, etc. + + +### Installation of libraries + +`pip install pandas + pip install xlrd` + + +Example for reading data from an Excel File: + +```python +import pandas as pd + +l = pd.read_excel('example.xlsx') +d = pd.DataFrame(l) +print(d) +``` +Output: +'''python + Name Age +0 John 12 +''' + +- **Note:** The above program can also be used for loading/retrieving the data. + + +Example for Inserting Data into Excel File: + +```python +import pandas as pd + +l = pd.read_excel('file_name.xlsx') +d = {'Name': ['Bob', 'John'], 'Age': [12, 28]} +d = pd.DataFrame(d) +L = pd.concat([l, d], ignore_index = True) +L.to_excel('file_name.xlsx', index = False) +print(L) +``` + +Output: +'''python + Name Age +0 Bob 12 +1 John 28 +''' From 9eb63b951d03e283aa76ee0d9ce980dc4ea509ee Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 17 May 2024 18:11:53 +0530 Subject: [PATCH 22/38] updated --- contrib/pandas/excel_with_pandas.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/contrib/pandas/excel_with_pandas.md b/contrib/pandas/excel_with_pandas.md index 6902c3f..4e67964 100644 --- a/contrib/pandas/excel_with_pandas.md +++ b/contrib/pandas/excel_with_pandas.md @@ -21,10 +21,10 @@ d = pd.DataFrame(l) print(d) ``` Output: -'''python +```python Name Age 0 John 12 -''' +``` - **Note:** The above program can also be used for loading/retrieving the data. @@ -43,9 +43,9 @@ print(L) ``` Output: -'''python +```python Name Age 0 Bob 12 1 John 28 -''' +``` From 0b6bd74a3b7daae3b28f8fc66576d23baee4bbc0 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 17 May 2024 18:12:42 +0530 Subject: [PATCH 23/38] updated --- contrib/pandas/excel_with_pandas.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/pandas/excel_with_pandas.md b/contrib/pandas/excel_with_pandas.md index 4e67964..b09b8c3 100644 --- a/contrib/pandas/excel_with_pandas.md +++ b/contrib/pandas/excel_with_pandas.md @@ -7,7 +7,7 @@ In the real world, Pandas DataFrames are formed by importing datasets from exis ### Installation of libraries -`pip install pandas +`pip install pandas
pip install xlrd` From f8044fb421f609c0ae67e65eefb4feabac914568 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 17 May 2024 18:13:28 +0530 Subject: [PATCH 24/38] updated --- contrib/pandas/excel_with_pandas.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contrib/pandas/excel_with_pandas.md b/contrib/pandas/excel_with_pandas.md index b09b8c3..af87b7b 100644 --- a/contrib/pandas/excel_with_pandas.md +++ b/contrib/pandas/excel_with_pandas.md @@ -7,8 +7,8 @@ In the real world, Pandas DataFrames are formed by importing datasets from exis ### Installation of libraries -`pip install pandas
- pip install xlrd` +`pip install pandas` +`pip install xlrd` Example for reading data from an Excel File: From 9fe61b8ec04b71037dff7506dd6169f259111bfa Mon Sep 17 00:00:00 2001 From: HimakarC <116370824+HimakarC@users.noreply.github.com> Date: Fri, 17 May 2024 18:15:20 +0530 Subject: [PATCH 25/38] Update excel_with_pandas.md --- contrib/pandas/excel_with_pandas.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/pandas/excel_with_pandas.md b/contrib/pandas/excel_with_pandas.md index af87b7b..137ef45 100644 --- a/contrib/pandas/excel_with_pandas.md +++ b/contrib/pandas/excel_with_pandas.md @@ -7,7 +7,7 @@ In the real world, Pandas DataFrames are formed by importing datasets from exis ### Installation of libraries -`pip install pandas` +`pip install pandas`
`pip install xlrd` From e4e9ad812fe87d70862390074deba405c2f9fe13 Mon Sep 17 00:00:00 2001 From: HimakarC <116370824+HimakarC@users.noreply.github.com> Date: Fri, 17 May 2024 18:16:41 +0530 Subject: [PATCH 26/38] excel_with_pandas.md --- contrib/pandas/excel_with_pandas.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/contrib/pandas/excel_with_pandas.md b/contrib/pandas/excel_with_pandas.md index 137ef45..13218d6 100644 --- a/contrib/pandas/excel_with_pandas.md +++ b/contrib/pandas/excel_with_pandas.md @@ -26,8 +26,6 @@ Output: 0 John 12 ``` -- **Note:** The above program can also be used for loading/retrieving the data. - Example for Inserting Data into Excel File: From e830336a54f5f6bce6e597df9900ee35b7a71709 Mon Sep 17 00:00:00 2001 From: HimakarC <116370824+HimakarC@users.noreply.github.com> Date: Fri, 17 May 2024 18:25:40 +0530 Subject: [PATCH 27/38] Create excel_with_pandas.md --- contrib/pandas/excel_with_pandas.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/contrib/pandas/excel_with_pandas.md b/contrib/pandas/excel_with_pandas.md index 13218d6..5798444 100644 --- a/contrib/pandas/excel_with_pandas.md +++ b/contrib/pandas/excel_with_pandas.md @@ -5,11 +5,20 @@ The Pandas DataFrame is a two-dimensional, size-mutable, and possibly heterogene In the real world, Pandas DataFrames are formed by importing datasets from existing storage, which can be a Excel file, a SQL database or CSV file. Pandas DataFrames may be constructed from lists, dictionaries, or lists of dictionaries, etc. +Features of Pandas `DataFrame`: + +- **Size mutable**: DataFrames are mutable in size, meaning that new rows and columns can be added or removed as needed. +- **Labeled axes**: DataFrames have labeled axes, which makes it easy to keep track of the data. +- **Arithmetic operations**: DataFrames support arithmetic operations on rows and columns. +- **High performance**: DataFrames are highly performant, making them ideal for working with large datasets. + + ### Installation of libraries `pip install pandas`
`pip install xlrd` +- **Note**: The `xlrd` library is used for Excel operations. Example for reading data from an Excel File: From 7fb2baf809f2cd40c0ccdd406fd75f8cb3e29d1b Mon Sep 17 00:00:00 2001 From: HimakarC <116370824+HimakarC@users.noreply.github.com> Date: Fri, 17 May 2024 18:31:22 +0530 Subject: [PATCH 28/38] Update excel_with_pandas.md --- contrib/pandas/excel_with_pandas.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/contrib/pandas/excel_with_pandas.md b/contrib/pandas/excel_with_pandas.md index 5798444..d325e46 100644 --- a/contrib/pandas/excel_with_pandas.md +++ b/contrib/pandas/excel_with_pandas.md @@ -56,3 +56,8 @@ Output: 1 John 28 ``` +### Usage of Pandas DataFrame: + +- Can be used to store and analyze financial data, such as stock prices, trading data, and economic data. +- Can be used to store and analyze sensor data, such as data from temperature sensors, motion sensors, and GPS sensors. +- Can be used to store and analyze log data, such as web server logs, application logs, and system logs From 0ad50df483d3179134a5e3551a661f6473a3500b Mon Sep 17 00:00:00 2001 From: HimakarC <116370824+HimakarC@users.noreply.github.com> Date: Fri, 17 May 2024 19:28:54 +0530 Subject: [PATCH 29/38] Update index.md --- contrib/pandas/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/pandas/index.md b/contrib/pandas/index.md index aadd970..834d1f4 100644 --- a/contrib/pandas/index.md +++ b/contrib/pandas/index.md @@ -1,4 +1,4 @@ # List of sections - [Pandas Series Vs NumPy ndarray](pandas_series_vs_numpy_ndarray.md) -- [Excel Operations using Pandas DataFrame](excel_with_pandas.md) +- [Excel using Pandas DataFrame](excel_with_pandas.md) From a758ff832d439bb225dc7f292974204e8f500643 Mon Sep 17 00:00:00 2001 From: Yogesh Vishwakarma <103316955+Yogeshkarma@users.noreply.github.com> Date: Fri, 17 May 2024 19:43:23 +0530 Subject: [PATCH 30/38] Create Regression.md --- contrib/machine-learning/Regression.md | 171 +++++++++++++++++++++++++ 1 file changed, 171 insertions(+) create mode 100644 contrib/machine-learning/Regression.md diff --git a/contrib/machine-learning/Regression.md b/contrib/machine-learning/Regression.md new file mode 100644 index 0000000..6ff6d28 --- /dev/null +++ b/contrib/machine-learning/Regression.md @@ -0,0 +1,171 @@ +# Regression + + +* Regression is a supervised machine learning technique which is used to predict continuous values. + + +> Now, Supervised learning is a category of machine learning that uses labeled datasets to train algorithms to predict outcomes and recognize patterns. + +* Regression is a statistical method used to model the relationship between a dependent variable (often denoted as 'y') and one or more independent variables (often denoted as 'x'). The goal of regression analysis is to understand how the dependent variable changes as the independent variables change. + # Types Of Regression + +1. Linear Regression +2. Polynomial Regression +3. Stepwise Regression +4. Decision Tree Regression +5. Random Forest Regression +6. Ridge Regression +7. Lasso Regression +8. ElasticNet Regression +9. Bayesian Linear Regression +10. Support Vector Regression + +But, we'll first start with Linear Regression +# Linear Regression + +* Linear regression is a fundamental statistical method used to model the relationship between a dependent variable (often denoted as +𝑌) and one or more independent variables (often denoted as +𝑋). The relationship is assumed to be linear, meaning that changes in the independent variables are associated with changes in the dependent variable in a straight-line fashion. + +The basic form of linear regression for a single independent variable is: + +**𝑌=𝛽0+𝛽1𝑋+𝜖** + +Where: + +* Y is the dependent variable. +* X is the independent variable. +* 𝛽0 is the intercept, representing the value of Y when X is zero +* 𝛽1 is the slope coefficient, representing the change in Y for a one-unit change in X +* ϵ is the error term, representing the variability in Y that is not explained by the linear relationship with X. + +# Basic Code of Linear Regression + +* This line imports the numpy library, which is widely used for numerical operations in Python. We use np as an alias for numpy, making it easier to reference functions and objects from the library. +``` +import numpy as np +``` + +* This line imports the LinearRegression class from the linear_model module of the scikit-learn library.scikit-learn is a powerful library for machine learning tasks in Python, and LinearRegression is a class provided by it for linear regression. +``` +from sklearn.linear_model import LinearRegression +``` +* This line creates a NumPy array X containing the independent variable values. In this example, we have a simple one-dimensional array representing the independent variable. The reshape(-1, 1) method reshapes the array into a column vector, necessary for use with scikit-learn + +``` +X = np.array([1, 2, 3, 4, 5]).reshape(-1, 1) +``` +* This line creates a NumPy array Y containing the corresponding dependent variable values. These are the observed values of the dependent variable corresponding to the independent variable values in X. +``` +Y = np.array([2, 4, 5, 8, 5]) +``` + +* This line creates an instance of the LinearRegression class, which represents the linear regression model. We'll use this object to train the model and make predictions. +``` +model = LinearRegression() +``` + +* This line fits the linear regression model to the data. The fit() method takes two arguments: the independent variable (X) and the dependent variable (Y). This method estimates the coefficients of the linear regression equation that best fit the given data. +``` +model.fit(X, Y) +``` +* These lines print out the intercept (beta_0) and coefficient (beta_1) of the linear regression model. model.intercept_ gives the intercept value, and model.coef_ gives an array of coefficients, where model.coef_[0] corresponds to the coefficient of the first independent variable (in this case, there's only one). +``` +print("Intercept:", model.intercept_) +print("Coefficient:", model.coef_[0]) +``` + +* These lines demonstrate how to use the trained model to make predictions for new data. +* We create a new NumPy array new_data containing the values of the independent variable for which we want to predict the dependent variable values. +* We then use the predict() method of the model to obtain the predictions for these new data points. Finally, we print out the predicted values. +``` +new_data = np.array([[6], [7]]) +predictions = model.predict(new_data) +print("Predictions:", predictions) +``` +# Assumptions of Linear Regression + +# Linearity: + +* To assess the linearity assumption, we can visually inspect a scatter plot of the observed values versus the predicted values. +* If the relationship between them appears linear, it suggests that the linearity assumption is reasonable. +``` +import matplotlib.pyplot as plt +predictions = model.predict(X) +plt.scatter(predictions,Y) +plt.xlabel("Predicted Values") +plt.ylabel("Observed Values") +plt.title("Linearity Check: Observed vs Predicted") +plt.show() +``` +# Homoscedasticity: +* Homoscedasticity refers to the constant variance of the residuals across all levels of the independent variable(s). We can visually inspect a plot of residuals versus predicted values to check for homoscedasticity. +``` +residuals = Y - predictions +plt.scatter(predictions, residuals) +plt.xlabel("Predicted Values") +plt.ylabel("Residuals") +plt.title("Homoscedasticity Check: Residuals vs Predicted Values") +plt.axhline(y=0, color='red', linestyle='--') # Add horizontal line at y=0 +plt.show() + +``` +# Normality of Residuals: +* To assess the normality of residuals, we can visually inspect a histogram or a Q-Q plot of the residuals. +``` +import seaborn as sns + +sns.histplot(residuals, kde=True) +plt.xlabel("Residuals") +plt.ylabel("Frequency") +plt.title("Normality of Residuals: Histogram") +plt.show() + +import scipy.stats as stats + +stats.probplot(residuals, dist="norm", plot=plt) +plt.title("Normal Q-Q Plot") +plt.show() + +``` +# Metrics for Regression + + +# Mean Absolute Error (MAE) + +* MAE measures the average magnitude of the errors in a set of predictions, without considering their direction. It is the average of the absolute differences between predicted and actual values. +``` +from sklearn.metrics import mean_absolute_error + +mae = mean_absolute_error(Y, predictions) +print(f"Mean Absolute Error (MAE): {mae}") + +``` +# Mean Squared Error (MSE) + +* MSE measures the average of the squares of the errors. It gives more weight to larger errors, making it sensitive to outliers. +``` +from sklearn.metrics import mean_squared_error + +mse = mean_squared_error(Y, predictions) +print(f"Mean Squared Error (MSE): {mse}") +``` +# Root Mean Squared Error (RMSE) +* RMSE is the square root of the MSE. It provides an error metric that is in the same units as the dependent variable, making it more interpretable. +``` +rmse = np.sqrt(mse) +print(f"Root Mean Squared Error (RMSE): {rmse}") + +``` +# R-squared (Coefficient of Determination) +* R-squared measures the proportion of the variance in the dependent variable that is predictable from the independent variables. It ranges from 0 to 1, where 1 indicates a perfect fit. +``` +from sklearn.metrics import r2_score + +r2 = r2_score(Y, predictions) +print(f"R-squared (R^2): {r2}") +``` + +> In this tutorial, The sample dataset is there for learning purpose only + + From d51207d7c9966ee7122fc687661d6dc271742435 Mon Sep 17 00:00:00 2001 From: Yogesh Vishwakarma <103316955+Yogeshkarma@users.noreply.github.com> Date: Fri, 17 May 2024 19:44:58 +0530 Subject: [PATCH 31/38] Update index.md --- contrib/machine-learning/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/machine-learning/index.md b/contrib/machine-learning/index.md index 82596a2..094b211 100644 --- a/contrib/machine-learning/index.md +++ b/contrib/machine-learning/index.md @@ -1,3 +1,3 @@ # List of sections -- [Section title](filename.md) +- [Regression in Machine Learning](Regression.md) From 4be728eb4764637fa8072aeebcaa9965e619d578 Mon Sep 17 00:00:00 2001 From: Ananyagra24 <155280507+Ananyagra24@users.noreply.github.com> Date: Sun, 19 May 2024 09:44:37 +0530 Subject: [PATCH 32/38] Update dice_roller.md --- contrib/mini-projects/dice_roller.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/contrib/mini-projects/dice_roller.md b/contrib/mini-projects/dice_roller.md index c083934..6e1b793 100644 --- a/contrib/mini-projects/dice_roller.md +++ b/contrib/mini-projects/dice_roller.md @@ -1,8 +1,15 @@ +Dice Roller +
+The aim of this project is to replicate a dice and generate a random number from the numbers 1 to 6.

+For this first we will import the random library which will help make random choices. ``` import random def dice(): dice_no = random.choice([1,2,3,4,5,6]) return "You got " + str(dice_no) +``` +The above snippet of code defines a function called "dice( )" which makes the random choice and returns the number that is generated. +``` def roll_dice(): print("Hey Guys, you will now roll a single dice using Python!") while True: @@ -17,3 +24,6 @@ def roll_dice(): print("Thanks for rolling the dice.") roll_dice() ``` +The above code defines a function called "roll_dice( )" which interacts with the user.
+It prompts the user to give an input and if the input is k,the code proceeds further to generate a random number or gives the message of invalid input and asks the user to try again.
+After the dice has been rolled once, the function asks the user whether they want a reroll in the form of a yes or no question.The dice is rolled again if the user gives 'yes' as an answer and exits the code if the user replies with anything other than yes. From 4ee5b32b8e217eac48799391a2f8182ac2abae35 Mon Sep 17 00:00:00 2001 From: Pradnya <116059908+PradnyaGaitonde@users.noreply.github.com> Date: Tue, 21 May 2024 21:51:48 +0530 Subject: [PATCH 33/38] Create dates_and_times.md Added content for Working with dates & times in python --- contrib/advanced-python/dates_and_times.md | 129 +++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 contrib/advanced-python/dates_and_times.md diff --git a/contrib/advanced-python/dates_and_times.md b/contrib/advanced-python/dates_and_times.md new file mode 100644 index 0000000..f599e26 --- /dev/null +++ b/contrib/advanced-python/dates_and_times.md @@ -0,0 +1,129 @@ +## Working with Dates and Times in Python +Handling dates and times is an essential aspect of many programming tasks. +Python provides robust modules to work with dates and times, making it easier to perform operations like formatting, parsing, and arithmetic. +This guide provides an overview of these modules and their key functionalities. + +## 1. 'datetime' Module +The datetime module supplies classes for manipulating dates and times. The main classes in the datetime module are: + +* date: Represents a date (year, month, day). +* time: Represents a time (hour, minute, second, microsecond). +* datetime: Combines date and time information. +* timedelta: Represents the difference between two dates or times. +* tzinfo: Provides time zone information objects. + +**Key Concepts:** + +* Naive vs. Aware: Naive datetime objects do not contain time zone information, while aware datetime objects do. +* Immutability: date and time objects are immutable; once created, they cannot be changed. + +Example: +```bash +python +Copy code +import datetime +# Get the current date and time +now = datetime.datetime.now() +print("Current date and time:", now) +``` + +## 2. Formatting Dates and Times +Formatting involves converting datetime objects into human-readable strings. This is achieved using the strftime method, which stands for "string format time." +You can specify various format codes to dictate how the output string should be structured. + +**Common Format Codes:** + +* %Y: Year with century (e.g., 2024) +* %m: Month as a zero-padded decimal number (e.g., 01) +* %d: Day of the month as a zero-padded decimal number (e.g., 15) +* %H: Hour (24-hour clock) as a zero-padded decimal number (e.g., 13) +* %M: Minute as a zero-padded decimal number (e.g., 45) +* %S: Second as a zero-padded decimal number (e.g., 30) + +Example: +```bash +python +Copy code +import datetime + +now = datetime.datetime.now() +formatted_now = now.strftime("%Y-%m-%d %H:%M:%S") +print("Formatted current date and time:", formatted_now) +``` + +## 3. Parsing Dates and Times +Parsing is the process of converting strings representing dates and times into datetime objects. The strptime method, which stands for "string parse time," +allows you to specify the format of the input string. + +Example: +```bash +python +Copy code +import datetime + +date_string = "2024-05-15 13:45:30" +date_object = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S") +print("Parsed date and time:", date_object) +``` + +## 4. Working with Time Differences +The timedelta class is used to represent the difference between two datetime objects. This is useful for calculations involving durations, such as finding the +number of days between two dates or adding a certain period to a date. + +Example: +```bash +python +Copy code +import datetime + +date1 = datetime.datetime(2024, 5, 15, 12, 0, 0) +date2 = datetime.datetime(2024, 5, 20, 14, 30, 0) + +difference = date2 - date1 +print("Difference:", difference) +print("Days:", difference.days) +print("Total seconds:", difference.total_seconds()) +``` + +## 5. Time Zones +Time zone handling in Python is facilitated by the pytz library. It allows you to convert naive datetime objects into timezone-aware objects and perform +operations across different time zones. + +**Key Concepts:** + +* Timezone-aware: A datetime object that includes timezone information. +* Localization: The process of associating a naive datetime with a time zone. + +Example: +```bash +python +Copy code +import datetime +import pytz + +# Define a timezone +tz = pytz.timezone('Asia/Kolkata') + +# Get the current time in a specific timezone +now = datetime.datetime.now(tz) +print("Current time in Asia/Kolkata:", now) +``` + +## 6. Date Arithmetic +Date arithmetic involves performing operations like addition or subtraction on date or datetime objects using timedelta. This is useful for calculating future +or past dates based on a given date. + +Example: +```bash +python +Copy code +import datetime + +today = datetime.date.today() +future_date = today + datetime.timedelta(days=10) +print("Date after 10 days:", future_date) +``` + +## Summary +Python’s datetime module and the pytz library provide comprehensive tools for working with dates, times, and time zones. They enable you to perform a wide range +of operations, from basic date manipulations to complex time zone conversions. From affc013943c380df51e90c08553573a6da46a143 Mon Sep 17 00:00:00 2001 From: Pradnya <116059908+PradnyaGaitonde@users.noreply.github.com> Date: Tue, 21 May 2024 21:55:23 +0530 Subject: [PATCH 34/38] Update index.md Added index for dates and times --- contrib/advanced-python/index.md | 1 + 1 file changed, 1 insertion(+) diff --git a/contrib/advanced-python/index.md b/contrib/advanced-python/index.md index 5ea5081..bf377fc 100644 --- a/contrib/advanced-python/index.md +++ b/contrib/advanced-python/index.md @@ -1,3 +1,4 @@ # List of sections - [Decorators/\*args/**kwargs](decorator-kwargs-args.md) +- [Working with Dates & Times in Python](dates_and_times.md) From 2967206c16c69227da131aa560efe0831148bc12 Mon Sep 17 00:00:00 2001 From: Pradnya <116059908+PradnyaGaitonde@users.noreply.github.com> Date: Tue, 21 May 2024 22:01:17 +0530 Subject: [PATCH 35/38] Create regular_expressions.md Added content for regular expressions in python --- .../advanced-python/regular_expressions.md | 96 +++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 contrib/advanced-python/regular_expressions.md diff --git a/contrib/advanced-python/regular_expressions.md b/contrib/advanced-python/regular_expressions.md new file mode 100644 index 0000000..65ff2c2 --- /dev/null +++ b/contrib/advanced-python/regular_expressions.md @@ -0,0 +1,96 @@ +## Regular Expressions in Python +Regular expressions (regex) are a powerful tool for pattern matching and text manipulation. +Python's re module provides comprehensive support for regular expressions, enabling efficient text processing and validation. + +## 1. Introduction to Regular Expressions +A regular expression is a sequence of characters defining a search pattern. Common use cases include validating input, searching within text, and extracting +specific patterns. + +## 2. Basic Syntax +Literal Characters: Match exact characters (e.g., abc matches "abc"). +Metacharacters: Special characters like ., *, ?, +, ^, $, [ ], and | used to build patterns. + +**Common Metacharacters:** + +* .: Any character except newline. +* ^: Start of the string. +* $: End of the string. +* *: 0 or more repetitions. +* +: 1 or more repetitions. +* ?: 0 or 1 repetition. +* []: Any one character inside brackets (e.g., [a-z]). +* |: Either the pattern before or after. + +## 3. Using the re Module + +**Key functions in the re module:** + +* re.match(): Checks for a match at the beginning of the string. +* re.search(): Searches for a match anywhere in the string. +* re.findall(): Returns a list of all matches. +* re.sub(): Replaces matches with a specified string. + +Examples: +```bash +import re + +# Match at the beginning +print(re.match(r'\d+', '123abc').group()) # Output: 123 + +# Search anywhere +print(re.search(r'\d+', 'abc123').group()) # Output: 123 + +# Find all matches +print(re.findall(r'\d+', 'abc123def456')) # Output: ['123', '456'] + +# Substitute matches +print(re.sub(r'\d+', '#', 'abc123def456')) # Output: abc#def# +``` + +## 4. Compiling Regular Expressions +Compiling regular expressions improves performance for repeated use. + +Example: +```bash +import re + +pattern = re.compile(r'\d+') +print(pattern.match('123abc').group()) # Output: 123 +print(pattern.search('abc123').group()) # Output: 123 +print(pattern.findall('abc123def456')) # Output: ['123', '456'] +``` + +## 5. Groups and Capturing +Parentheses () group and capture parts of the match. + +Example: +```bash +import re + +match = re.match(r'(\d{3})-(\d{2})-(\d{4})', '123-45-6789') +if match: + print(match.group()) # Output: 123-45-6789 + print(match.group(1)) # Output: 123 + print(match.group(2)) # Output: 45 + print(match.group(3)) # Output: 6789 +``` + +## 6. Special Sequences +Special sequences are shortcuts for common patterns: + +* \d: Any digit. +* \D: Any non-digit. +* \w: Any alphanumeric character. +* \W: Any non-alphanumeric character. +* \s: Any whitespace character. +* \S: Any non-whitespace character. +Example: +```bash +import re + +print(re.search(r'\w+@\w+\.\w+', 'Contact: support@example.com').group()) # Output: support@example.com +``` + +## Summary +Regular expressions are a versatile tool for text processing in Python. The re module offers powerful functions and metacharacters for pattern matching, +searching, and manipulation, making it an essential skill for handling complex text processing tasks. From d44f8fc253ae6a74af3894ecd77ceb2ef5f01adf Mon Sep 17 00:00:00 2001 From: Pradnya <116059908+PradnyaGaitonde@users.noreply.github.com> Date: Tue, 21 May 2024 22:03:27 +0530 Subject: [PATCH 36/38] Update index.md added index for regular --- contrib/advanced-python/index.md | 1 + 1 file changed, 1 insertion(+) diff --git a/contrib/advanced-python/index.md b/contrib/advanced-python/index.md index 5ea5081..ebb567a 100644 --- a/contrib/advanced-python/index.md +++ b/contrib/advanced-python/index.md @@ -1,3 +1,4 @@ # List of sections - [Decorators/\*args/**kwargs](decorator-kwargs-args.md) +- [Regular Expressions in Python](regular_expressions.md) From d7dc67b678124cd54a93c5b917af9d7a903fb82d Mon Sep 17 00:00:00 2001 From: Pradnya <116059908+PradnyaGaitonde@users.noreply.github.com> Date: Tue, 21 May 2024 22:05:01 +0530 Subject: [PATCH 37/38] Update dates_and_times.md --- contrib/advanced-python/dates_and_times.md | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/contrib/advanced-python/dates_and_times.md b/contrib/advanced-python/dates_and_times.md index f599e26..983f6b2 100644 --- a/contrib/advanced-python/dates_and_times.md +++ b/contrib/advanced-python/dates_and_times.md @@ -19,8 +19,6 @@ The datetime module supplies classes for manipulating dates and times. The main Example: ```bash -python -Copy code import datetime # Get the current date and time now = datetime.datetime.now() @@ -42,8 +40,6 @@ You can specify various format codes to dictate how the output string should be Example: ```bash -python -Copy code import datetime now = datetime.datetime.now() @@ -57,8 +53,6 @@ allows you to specify the format of the input string. Example: ```bash -python -Copy code import datetime date_string = "2024-05-15 13:45:30" @@ -72,8 +66,6 @@ number of days between two dates or adding a certain period to a date. Example: ```bash -python -Copy code import datetime date1 = datetime.datetime(2024, 5, 15, 12, 0, 0) @@ -96,8 +88,6 @@ operations across different time zones. Example: ```bash -python -Copy code import datetime import pytz @@ -115,8 +105,6 @@ or past dates based on a given date. Example: ```bash -python -Copy code import datetime today = datetime.date.today() From 5e95059765b6cb99498c1302b94f68c8d5ee482c Mon Sep 17 00:00:00 2001 From: Ankit Mahato Date: Thu, 23 May 2024 02:57:11 +0530 Subject: [PATCH 38/38] Update dice_roller.md --- contrib/mini-projects/dice_roller.md | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/contrib/mini-projects/dice_roller.md b/contrib/mini-projects/dice_roller.md index 6e1b793..0f4e5f9 100644 --- a/contrib/mini-projects/dice_roller.md +++ b/contrib/mini-projects/dice_roller.md @@ -1,14 +1,18 @@ -Dice Roller -
-The aim of this project is to replicate a dice and generate a random number from the numbers 1 to 6.

+## Dice Roller + +The aim of this project is to replicate a dice and generate a random number from the numbers 1 to 6. + For this first we will import the random library which will help make random choices. + ``` import random def dice(): dice_no = random.choice([1,2,3,4,5,6]) return "You got " + str(dice_no) ``` -The above snippet of code defines a function called "dice( )" which makes the random choice and returns the number that is generated. + +The above snippet of code defines a function called `dice()` which makes the random choice and returns the number that is generated. + ``` def roll_dice(): print("Hey Guys, you will now roll a single dice using Python!") @@ -24,6 +28,9 @@ def roll_dice(): print("Thanks for rolling the dice.") roll_dice() ``` -The above code defines a function called "roll_dice( )" which interacts with the user.
-It prompts the user to give an input and if the input is k,the code proceeds further to generate a random number or gives the message of invalid input and asks the user to try again.
-After the dice has been rolled once, the function asks the user whether they want a reroll in the form of a yes or no question.The dice is rolled again if the user gives 'yes' as an answer and exits the code if the user replies with anything other than yes. + +The above code defines a function called `roll_dice()` which interacts with the user. + +It prompts the user to give an input and if the input is `k`,the code proceeds further to generate a random number or gives the message of invalid input and asks the user to try again. + +After the dice has been rolled once, the function asks the user whether they want a reroll in the form of a `yes` or `no` question. The dice is rolled again if the user gives `yes` as an answer and exits the code if the user replies with anything other than yes.