Merge branch 'main' into main

pull/291/head
Ankit Mahato 2024-05-23 03:04:37 +05:30 zatwierdzone przez GitHub
commit df687e1748
Nie znaleziono w bazie danych klucza dla tego podpisu
ID klucza GPG: B5690EEEBB952194
7 zmienionych plików z 283 dodań i 2 usunięć

Wyświetl plik

@ -0,0 +1,117 @@
## 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
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
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
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
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
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
import datetime
today = datetime.date.today()
future_date = today + datetime.timedelta(days=10)
print("Date after 10 days:", future_date)
```
## Summary
Pythons 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.

Wyświetl plik

@ -1,3 +1,5 @@
# List of sections
- [Decorators/\*args/**kwargs](decorator-kwargs-args.md)
- [Working with Dates & Times in Python](dates_and_times.md)
- [Regular Expressions in Python](regular_expressions.md)

Wyświetl plik

@ -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.

Wyświetl plik

@ -0,0 +1,36 @@
## 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:
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()
```
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.

Wyświetl plik

@ -1,4 +1,4 @@
# List of sections
- [Dice Roller](dice_roller.md)
- [Rock Paper Scissors Game](Rock_Paper_Scissors_Game.md)

Wyświetl plik

@ -1,3 +1,3 @@
# List of sections
- [Section title](filename.md)
- [Introduction](introduction.md)

Wyświetl plik

@ -0,0 +1,30 @@
# Introduction
## What is NumPy?
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.
## Key Features
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.
## Installation
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
```
## Importing NumPy
To access NumPy functions, import it with the alias `np`.
```python
import numpy as np
```
Using `np` as an alias enhances code readability and is a widely adopted convention.