Skip to content

Commit be2ee50

Browse files
authored
Merge branch 'main' into PradnyaGaitonde-patch-8
2 parents 294afa2 + ca385f3 commit be2ee50

File tree

149 files changed

+14213
-50
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

149 files changed

+14213
-50
lines changed

CONTRIBUTING.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ The list of topics for which we are looking for content are provided below along
2424
- Web Scrapping - [Link](https://github.com/animator/learn-python/tree/main/contrib/web-scrapping)
2525
- API Development - [Link](https://github.com/animator/learn-python/tree/main/contrib/api-development)
2626
- Data Structures & Algorithms - [Link](https://github.com/animator/learn-python/tree/main/contrib/ds-algorithms)
27-
- Python Mini Projects - [Link](https://github.com/animator/learn-python/tree/main/contrib/mini-projects)
28-
- Python Question Bank - [Link](https://github.com/animator/learn-python/tree/main/contrib/question-bank)
27+
- Python Mini Projects - [Link](https://github.com/animator/learn-python/tree/main/contrib/mini-projects) **(Not accepting)**
28+
- Python Question Bank - [Link](https://github.com/animator/learn-python/tree/main/contrib/question-bank) **(Not accepting)**
2929

3030
You can check out some content ideas below.
3131

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
## Working with Dates and Times in Python
2+
Handling dates and times is an essential aspect of many programming tasks.
3+
Python provides robust modules to work with dates and times, making it easier to perform operations like formatting, parsing, and arithmetic.
4+
This guide provides an overview of these modules and their key functionalities.
5+
6+
## 1. 'datetime' Module
7+
The datetime module supplies classes for manipulating dates and times. The main classes in the datetime module are:
8+
9+
* date: Represents a date (year, month, day).
10+
* time: Represents a time (hour, minute, second, microsecond).
11+
* datetime: Combines date and time information.
12+
* timedelta: Represents the difference between two dates or times.
13+
* tzinfo: Provides time zone information objects.
14+
15+
**Key Concepts:**
16+
17+
* Naive vs. Aware: Naive datetime objects do not contain time zone information, while aware datetime objects do.
18+
* Immutability: date and time objects are immutable; once created, they cannot be changed.
19+
20+
Example:
21+
```bash
22+
import datetime
23+
# Get the current date and time
24+
now = datetime.datetime.now()
25+
print("Current date and time:", now)
26+
```
27+
28+
## 2. Formatting Dates and Times
29+
Formatting involves converting datetime objects into human-readable strings. This is achieved using the strftime method, which stands for "string format time."
30+
You can specify various format codes to dictate how the output string should be structured.
31+
32+
**Common Format Codes:**
33+
34+
* %Y: Year with century (e.g., 2024)
35+
* %m: Month as a zero-padded decimal number (e.g., 01)
36+
* %d: Day of the month as a zero-padded decimal number (e.g., 15)
37+
* %H: Hour (24-hour clock) as a zero-padded decimal number (e.g., 13)
38+
* %M: Minute as a zero-padded decimal number (e.g., 45)
39+
* %S: Second as a zero-padded decimal number (e.g., 30)
40+
41+
Example:
42+
```bash
43+
import datetime
44+
45+
now = datetime.datetime.now()
46+
formatted_now = now.strftime("%Y-%m-%d %H:%M:%S")
47+
print("Formatted current date and time:", formatted_now)
48+
```
49+
50+
## 3. Parsing Dates and Times
51+
Parsing is the process of converting strings representing dates and times into datetime objects. The strptime method, which stands for "string parse time,"
52+
allows you to specify the format of the input string.
53+
54+
Example:
55+
```bash
56+
import datetime
57+
58+
date_string = "2024-05-15 13:45:30"
59+
date_object = datetime.datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
60+
print("Parsed date and time:", date_object)
61+
```
62+
63+
## 4. Working with Time Differences
64+
The timedelta class is used to represent the difference between two datetime objects. This is useful for calculations involving durations, such as finding the
65+
number of days between two dates or adding a certain period to a date.
66+
67+
Example:
68+
```bash
69+
import datetime
70+
71+
date1 = datetime.datetime(2024, 5, 15, 12, 0, 0)
72+
date2 = datetime.datetime(2024, 5, 20, 14, 30, 0)
73+
74+
difference = date2 - date1
75+
print("Difference:", difference)
76+
print("Days:", difference.days)
77+
print("Total seconds:", difference.total_seconds())
78+
```
79+
80+
## 5. Time Zones
81+
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
82+
operations across different time zones.
83+
84+
**Key Concepts:**
85+
86+
* Timezone-aware: A datetime object that includes timezone information.
87+
* Localization: The process of associating a naive datetime with a time zone.
88+
89+
Example:
90+
```bash
91+
import datetime
92+
import pytz
93+
94+
# Define a timezone
95+
tz = pytz.timezone('Asia/Kolkata')
96+
97+
# Get the current time in a specific timezone
98+
now = datetime.datetime.now(tz)
99+
print("Current time in Asia/Kolkata:", now)
100+
```
101+
102+
## 6. Date Arithmetic
103+
Date arithmetic involves performing operations like addition or subtraction on date or datetime objects using timedelta. This is useful for calculating future
104+
or past dates based on a given date.
105+
106+
Example:
107+
```bash
108+
import datetime
109+
110+
today = datetime.date.today()
111+
future_date = today + datetime.timedelta(days=10)
112+
print("Date after 10 days:", future_date)
113+
```
114+
115+
## Summary
116+
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
117+
of operations, from basic date manipulations to complex time zone conversions.
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# Understanding the `eval` Function in Python
2+
## Introduction
3+
4+
The `eval` function in Python allows you to execute a string-based Python expression dynamically. This can be useful in various scenarios where you need to evaluate expressions that are not known until runtime.
5+
6+
## Syntax
7+
```python
8+
eval(expression, globals=None, locals=None)
9+
```
10+
11+
### Parameters:
12+
13+
* expression: String is parsed and evaluated as a Python expression
14+
* globals [optional]: Dictionary to specify the available global methods and variables.
15+
* locals [optional]: Another dictionary to specify the available local methods and variables.
16+
17+
## Examples
18+
Example 1:
19+
```python
20+
result = eval('2 + 3 * 4')
21+
print(result) # Output: 14
22+
```
23+
Example 2:
24+
25+
```python
26+
x = 10
27+
expression = 'x * 2'
28+
result = eval(expression, {'x': x})
29+
print(result) # Output: 20
30+
```
31+
Example 3:
32+
```python
33+
x = 10
34+
def multiply(a, b):
35+
return a * b
36+
expression = 'multiply(x, 5) + 2'
37+
result = eval(expression)
38+
print("Result:",result) # Output: Result:52
39+
```
40+
Example 4:
41+
```python
42+
expression = input("Enter a Python expression: ")
43+
result = eval(expression)
44+
print("Result:", result)
45+
#input= "3+2"
46+
#Output: Result:5
47+
```
48+
49+
Example 5:
50+
```python
51+
import numpy as np
52+
a=np.random.randint(1,9)
53+
b=np.random.randint(1,9)
54+
operations=["*","-","+"]
55+
op=np.random.choice(operations)
56+
57+
expression=str(a)+op+str(b)
58+
correct_answer=eval(expression)
59+
given_answer=int(input(str(a)+" "+op+" "+str(b)+" = "))
60+
61+
if given_answer==correct_answer:
62+
print("Correct")
63+
else:
64+
print("Incorrect")
65+
print("correct answer is :" ,correct_answer)
66+
67+
#2 * 1 = 8
68+
#Incorrect
69+
#correct answer is : 2
70+
#or
71+
#3 * 2 = 6
72+
#Correct
73+
```
74+
## Conclusion
75+
The eval function is a powerful tool in Python that allows for dynamic evaluation of expressions.
Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
# Exception Handling in Python
2+
3+
Exception Handling is a way of managing the errors that may occur during a program execution. Python's exception handling mechanism has been designed to avoid the unexpected termination of the program, and offer to either regain control after an error or display a meaningful message to the user.
4+
5+
- **Error** - An error is a mistake or an incorrect result produced by a program. It can be a syntax error, a logical error, or a runtime error. Errors are typically fatal, meaning they prevent the program from continuing to execute.
6+
- **Exception** - An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Exceptions are typically unexpected and can be handled by the program to prevent it from crashing or terminating abnormally. It can be runtime, input/output or system exceptions. Exceptions are designed to be handled by the program, allowing it to recover from the error and continue executing.
7+
8+
## Python Built-in Exceptions
9+
10+
There are plenty of built-in exceptions in Python that are raised when a corresponding error occur.
11+
We can view all the built-in exceptions using the built-in `local()` function as follows:
12+
13+
```python
14+
print(dir(locals()['__builtins__']))
15+
```
16+
17+
|**S.No**|**Exception**|**Description**|
18+
|---|---|---|
19+
|1|SyntaxError|A syntax error occurs when the code we write violates the grammatical rules such as misspelled keywords, missing colon, mismatched parentheses etc.|
20+
|2|TypeError|A type error occurs when we try to perform an operation or use a function with objects that are of incompatible data types.|
21+
|3|NameError|A name error occurs when we try to use a variable, function, module or string without quotes that hasn't been defined or isn't used in a valid way.|
22+
|4|IndexError|A index error occurs when we try to access an element in a sequence (like a list, tuple or string) using an index that's outside the valid range of indices for that sequence.|
23+
|5|KeyError|A key error occurs when we try to access a key that doesn't exist in a dictionary. Attempting to retrieve a value using a non-existent key results this error.|
24+
|6|ValueError|A value error occurs when we provide an argument or value that's inappropriate for a specific operation or function such as doing mathematical operations with incompatible types (e.g., dividing a string by an integer.)|
25+
|7|AttributeError|An attribute error occurs when we try to access an attribute (like a variable or method) on an object that doesn't possess that attribute.|
26+
|8|IOError|An IO (Input/Output) error occurs when an operation involving file or device interaction fails. It signifies that there's an issue during communication between your program and the external system.|
27+
|9|ZeroDivisionError|A ZeroDivisionError occurs when we attempt to divide a number by zero. This operation is mathematically undefined, and Python raises this error to prevent nonsensical results.|
28+
|10|ImportError|An import error occurs when we try to use a module or library that Python can't find or import succesfully.|
29+
30+
## Try and Except Statement - Catching Exception
31+
32+
The `try-except` statement allows us to anticipate potential errors during program execution and define what actions to take when those errors occur. This prevents the program from crashing unexpectedly and makes it more robust.
33+
34+
Here's an example to explain this:
35+
36+
```python
37+
try:
38+
# Code that might raise an exception
39+
result = 10 / 0
40+
except:
41+
print("An error occured!")
42+
```
43+
44+
Output
45+
46+
```markdown
47+
An error occured!
48+
```
49+
50+
In this example, the `try` block contains the code that you suspect might raise an exception. Python attempts to execute the code within this block. If an exception occurs, Python jumps to the `except` block and executes the code within it.
51+
52+
## Specific Exception Handling
53+
54+
You can specify the type of expection you want to catch using the `except` keyword followed by the exception class name. You can also have multiple `except` blocks to handle different exception types.
55+
56+
Here's an example:
57+
58+
```python
59+
try:
60+
# Code that might raise ZeroDivisionError or NameError
61+
result = 10 / 0
62+
name = undefined_variable
63+
except ZeroDivisionError:
64+
print("Oops! You tried to divide by zero.")
65+
except NameError:
66+
print("There's a variable named 'undefined_variable' that hasn't been defined yet.")
67+
```
68+
69+
Output
70+
71+
```markdown
72+
Oops! You tried to divide by zero.
73+
```
74+
75+
If you comment on the line `result = 10 / 0`, then the output will be:
76+
77+
```markdown
78+
There's a variable named 'undefined_variable' that hasn't been defined yet.
79+
```
80+
81+
## Important Note
82+
83+
In this code, the `except` block are specific to each type of expection. If you want to catch both exceptions with a single `except` block, you can use of tuple of exceptions, like this:
84+
85+
```python
86+
try:
87+
# Code that might raise ZeroDivisionError or NameError
88+
result = 10 / 0
89+
name = undefined_variable
90+
except (ZeroDivisionError, NameError):
91+
print("An error occured!")
92+
```
93+
94+
Output
95+
96+
```markdown
97+
An error occured!
98+
```
99+
100+
## Try with Else Clause
101+
102+
The `else` clause in a Python `try-except` block provides a way to execute code only when the `try` block succeeds without raising any exceptions. It's like having a section of code that runs exclusively under the condition that no errors occur during the main operation in the `try` block.
103+
104+
Here's an example to understand this:
105+
106+
```python
107+
def calculate_average(numbers):
108+
if len(numbers) == 0: # Handle empty list case seperately (optional)
109+
return None
110+
try:
111+
total = sum(numbers)
112+
average = total / len(numbers)
113+
except ZeroDivisionError:
114+
print("Cannot calculate average for a list containing zero.")
115+
else:
116+
print("The average is:", average)
117+
return average #Optionally return the average here
118+
119+
# Example usage
120+
numbers = [10, 20, 30]
121+
result = calculate_average(numbers)
122+
123+
if result is not None: # Check if result is available (handles empty list case)
124+
print("Calculation succesfull!")
125+
```
126+
127+
Output
128+
129+
```markdown
130+
The average is: 20.0
131+
```
132+
133+
## Finally Keyword in Python
134+
135+
The `finally` keyword in Python is used within `try-except` statements to execute a block of code **always**, regardless of whether an exception occurs in the `try` block or not.
136+
137+
To understand this, let us take an example:
138+
139+
```python
140+
try:
141+
a = 10 // 0
142+
print(a)
143+
except ZeroDivisionError:
144+
print("Cannot be divided by zero.")
145+
finally:
146+
print("Program executed!")
147+
```
148+
149+
Output
150+
151+
```markdown
152+
Cannot be divided by zero.
153+
Program executed!
154+
```
155+
156+
## Raise Keyword in Python
157+
158+
In Python, raising an exception allows you to signal that an error condition has occured during your program's execution. The `raise` keyword is used to explicity raise an exception.
159+
160+
Let us take an example:
161+
162+
```python
163+
def divide(x, y):
164+
if y == 0:
165+
raise ZeroDivisionError("Can't divide by zero!") # Raise an exception with a message
166+
result = x / y
167+
return result
168+
169+
try:
170+
division_result = divide(10, 0)
171+
print("Result:", division_result)
172+
except ZeroDivisionError as e:
173+
print("An error occured:", e) # Handle the exception and print the message
174+
```
175+
176+
Output
177+
178+
```markdown
179+
An error occured: Can't divide by zero!
180+
```
181+
182+
## Advantages of Exception Handling
183+
184+
- **Improved Error Handling** - It allows you to gracefully handle unexpected situations that arise during program execution. Instead of crashing abruptly, you can define specific actions to take when exceptions occur, providing a smoother experience.
185+
- **Code Robustness** - Exception Handling helps you to write more resilient programs by anticipating potential issues and providing approriate responses.
186+
- **Enhanced Code Readability** - By seperating error handling logic from the core program flow, your code becomes more readable and easier to understand. The `try-except` blocks clearly indicate where potential errors might occur and how they'll be addressed.
187+
188+
## Disadvantages of Exception Handling
189+
190+
- **Hiding Logic Errors** - Relying solely on exception handling might mask underlying logic error in your code. It's essential to write clear and well-tested logic to minimize the need for excessive exception handling.
191+
- **Performance Overhead** - In some cases, using `try-except` blocks can introduce a slight performance overhead compared to code without exception handling. Howerer, this is usually negligible for most applications.
192+
- **Overuse of Exceptions** - Overusing exceptions for common errors or control flow can make code less readable and harder to maintain. It's important to use exceptions judiciously for unexpected situations.

0 commit comments

Comments
 (0)