Skip to content

Update 09.Dict.md #63

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 19 additions & 3 deletions 09.Dict.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ my_dict = {

# Option 2: Pass keyword parameters
my_dict = dict(name='John', age=30, occupation='developer')

print(my_dict)
```

#### Output
Expand Down Expand Up @@ -97,7 +99,7 @@ John

The `min()` and `max()` functions can be used with dictionaries to find the minimum or maximum key or value.

***Note***: By default, these functions operate on the dictionary keys, but you can specify to operate on the values by using the `key` parameter.
***Note***: By default, these functions operate on the dictionary keys, but you can specify to operate on the values by using the `values()` method.

#### Example

Expand Down Expand Up @@ -307,7 +309,7 @@ True

***NOTE***: Although `dict_a` and `dict_b` were defined in different orders, they are considered equal.

***NOTE***: Order does not matterm since Python 3.7, dictionaries maintain the insertion order of items. However, the order does not influence the outcome of equality comparisons.
***NOTE***: Order does not matter since Python 3.7, dictionaries maintain the insertion order of items. However, the order does not influence the outcome of equality comparisons.

### 4.2 Inequality (`!=`)

Expand Down Expand Up @@ -348,6 +350,7 @@ family = {
}

print(family['john']['job'])
print(family.get('jane').get('age'))
```

#### Output
Expand Down Expand Up @@ -385,6 +388,11 @@ This can be done using the `.setdefault()` method or checking for the existence
#### Example

```python
family = {
'john': {'age': 30, 'job': 'developer'},
'jane': {'age': 28, 'job': 'designer'}
}

# Adding a new key-value pair for John
family['john']['hobby'] = 'painting'

Expand Down Expand Up @@ -434,9 +442,17 @@ To remove items either from default or a nested dictionary, use the `del` statem
#### Example

```python
family = {
'john': {'age': 30, 'job': 'developer', 'hobby': 'painting'},
'jane': {'age': 28, 'job': 'designer'},
'alice': {'age': 24, 'job': 'engineer'}
}

# Deleting a key-value pair
del family['john']['hobby']

print(family)

# Removing an entire nested dictionary
removed_person = family.pop('alice', None)
print(f"Removed: {removed_person}")
Expand All @@ -445,7 +461,7 @@ print(f"Removed: {removed_person}")
#### Output

```
{'john': {'age': 30, 'job': 'developer'}, 'jane': {'age': 28, 'job': 'designer'}}
{'john': {'age': 30, 'job': 'developer'}, 'jane': {'age': 28, 'job': 'designer'}, 'alice': {'age': 24, 'job': 'engineer'}}
Removed: {'age': 28, 'job': 'designer'}
```

Expand Down
22 changes: 11 additions & 11 deletions 10.Functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ Let's write the same code, but **with functions** this time.
In Python functions are defined by `def` keyword <span style="color: orange">_followed by the name_</span> of the function
, then curly brackets `()` and semicolon `:`.

***NOTE***: Take a look at **_indentation_**, in case it's wrong the `Pyhton` interpreter will not be able to compile the
***NOTE***: Take a look at **_indentation_**, in case it's wrong the `Python` interpreter will not be able to compile the
code.

#### Example
Expand All @@ -93,7 +93,7 @@ print_cake_recipe()

#### Explanation

We created a function `print_cake_recipe()` and then called it 4 times, lets see what
We created a function `print_cake_recipe()` and then called it 4 times, let's see what
happens when we run it.

#### Output
Expand Down Expand Up @@ -152,15 +152,15 @@ addition(1, 3)

#### Explanation

Define function `addition` and in curly brackets we declared the parameters: `a` and `b`.
We defined function `addition` and inside parentheses we declared the parameters: `a` and `b`.

Then we called the function and passed arguments `1` and `3`, as `a` and `b` accordingly
Then we called the function and passed arguments `1` and `3`, as `a` and `b` accordingly.

### 2.2 Parameters vs Arguments

As irrelevant as it might seem, there is a difference between these two key terms. The function <span style="color:orange">***parameters*** are the names listed in the function's definition</span> and the function <span style="color:green">***arguments*** are the real values passed to the function</span>.

You just need to understand that once you pass value `11` to the parameter `a` into the function, it becomes and argument.
You just need to understand that once you pass value `11` to the parameter `a` into the function, it becomes an argument.

## 3. Positional vs Key Arguments

Expand Down Expand Up @@ -218,7 +218,7 @@ Here, even though the order of arguments is ***different*** from the order of
parameters in the function definition, Python knows which argument corresponds
to which parameter, thanks to the keyword parameters.

Personally I prefer the following approach, following it, your codebase becomes much cleaner.
Personally I prefer the following (????) approach, following it, your codebase becomes much cleaner.

## 4. Scopes

Expand Down Expand Up @@ -267,7 +267,7 @@ NameError: name 'summ' is not defined.
#### Explanation

In this case we declare variable `suma` and since we created it **inside** the function
it has **local** scope, therefore we wouldn't be able to call it from outside:
it has **local** scope, therefore we wouldn't be able to call it from outside.


### 4.2 Global scope
Expand Down Expand Up @@ -434,7 +434,7 @@ Good morning, Bob!
In the `greet` function above, `name` is a **mandatory** parameter, while `message` is **optional** with a *<u>default value</u>* of `"Hello"`. If no `message` is provided when the function is called, it uses the *<u>default value</u>*.


***Important***: You can only assign default values to parameters ***After*** you have declared your positional arguments, more on this in ***args/kwargs*** section
***Important***: You can only assign default values to parameters ***after*** you have declared your positional arguments, more on this in ***args/kwargs*** section

## 7. `Args` and `Kwargs`

Expand Down Expand Up @@ -466,8 +466,8 @@ positional arguments into a tuple called `numbers`.

### 7.1.1 Unpacking parameters

As we learned previously in data types, you can use `*` to unpack the elements of an iterable, it is relevant as if you
will try to pass an iterable to a function without unpacking it, it will be treated as a whole object.
As we learned previously in data types, you can use `*` to unpack the elements of an iterable. Be aware that if you
pass an iterable to a function without unpacking it, you will pass the iterable as a whole unpacked object (rather than passing the individual elements in the iterable).

***NOTE***: Same applies for `**kwargs`

Expand Down Expand Up @@ -772,7 +772,7 @@ x = 10

def print_number():
x = 5
print("Inside function:", x)
print("Inside function:", x, end=", ")

print_number()
print("Outside function:", x)
Expand Down
14 changes: 7 additions & 7 deletions 11.Exceptions.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@

Error handling is an important component of programming that provides opportunity for code to adequately respond to unexpected situations. In Python, errors are managed through the use of exceptions, which are special objects that represent error conditions.

When Python interpreter stumbles upon a situation, it cannot cope with, it raises an exception. If the exception isn't handled, the program will terminate abruptly, which can lead to a poor user experience or even loss of data.
When Python interpreter stumbles upon a situation it cannot cope with, it raises an exception. If the exception isn't handled, the program will terminate abruptly, which can lead to a poor user experience or even loss of data.

## 2 The `try` & `except` Block

In python, error handling is managed with the use of `try` and `except` keywords.
In Python, error handling is managed with the use of `try` and `except` keywords.

### 2.1 How do `try` and `except` work?

Expand Down Expand Up @@ -163,7 +163,7 @@ In this example, the code inside the `try` block successfully completes without
The `else` block is useful when you want to separate the code that might raise an exception from the code that should
only be executed if no exceptions occur. This separation can improve the readability of your code and make it easier to understand the flow of execution.

Though, I must admit that the following approach is not really popular among Python society. Have no idea why, to be honest...
Though, I must admit that the following approach (??? huh what approach) is not really popular among Python society. Have no idea why, to be honest...

### 3.2 Note

Expand Down Expand Up @@ -215,7 +215,7 @@ Where `ExceptionType` is the class of the exception you want to raise (e.g., `Va

### 5.3 Use Cases

1.**Input Validation**: If a function requires inputs to meet certain conditions, you can raise an exception if the provided inputs are invalid.
1. **Input Validation**: If a function requires inputs to meet certain conditions, you can raise an exception if the provided inputs are invalid.

```python
def set_age(age):
Expand All @@ -227,7 +227,7 @@ Where `ExceptionType` is the class of the exception you want to raise (e.g., `Va
print(e)
```

2.**Enforcing Constraints**: When certain states or conditions must not occur within a program, raising exceptions can enforce these constraints explicitly.
2. **Enforcing Constraints**: When certain states or conditions must not occur within a program, raising exceptions can enforce these constraints explicitly.

```python
inventory = {'apple': 10, 'banana': 5}
Expand All @@ -240,7 +240,7 @@ Where `ExceptionType` is the class of the exception you want to raise (e.g., `Va
inventory[item] -= quantity
```

3.**Signaling Unimplemented Features**: If a part of your code is not yet implemented, you can raise a `NotImplementedError` as a placeholder.
3. **Signaling Unimplemented Features**: If a part of your code is not yet implemented, you can raise a `NotImplementedError` as a placeholder.
```python
def future_feature():
raise NotImplementedError("This feature is coming soon!")
Expand All @@ -254,7 +254,7 @@ There are no limits for your imagination in terms of handling errors, again this

### 5.5 Best Practices

- **Be Specific**: Prefer raising and catching specific exceptions rather than the general `Exception` class. This makes error handling more predictable, robust and optimised.
- **Be Specific**: Prefer raising and catching specific exceptions rather than the general `Exception` class. This makes error handling more predictable, robust, and optimised.

- **Provide Useful Messages**: When raising exceptions, include a clear, descriptive message to make it easier to understand the cause of the error.

Expand Down
20 changes: 11 additions & 9 deletions 12.Imports.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ The module name is the same as the file name with the `.py` extension added at t

### 1.1 Why do we need modules?

Generally, if we were to write everything into one file, we wouldn't be able to maintain our application, making it hard for other developers to use.
Generally, if we were to write everything into one file, we wouldn't be able to maintain our application, making it hard for other developers to use it.

Using modules helps us to do the following:

- **Organizing Code**: By dividing a program into modules you can separate parts and concerns making it easier to manage and understand the program.
- **Organizing Code**: By dividing a program into modules, you can separate parts and concerns making it easier to manage and understand the program.

- **Reusable Components**: Functions, classes and variables defined in a module can be easily reused across sections of a program or different programs.
- **Reusable Components**: Functions, classes, and variables defined in a module can be easily reused across sections of a program or in different programs.

- **Managing Namespaces**: Modules help prevent conflicts between names by providing a separate namespace, for each module.

Expand All @@ -43,6 +43,8 @@ In `Python`, a simple `.py` file can be considered and used as a module to store
2. **Add Code to the File**: Write the necessary functions, classes, and variables in the file. Here’s an example of what `mymodule.py` might look like:

```python
# mymodule.py

def say_hello(name):
print(f"Hello, {name}!")

Expand Down Expand Up @@ -185,7 +187,7 @@ Thanks to `as` you can use `time` from both `x` and `y` modules, without any con

## 4. `if __name__ == "__main__"`

When writing Python scripts, you'll often see a code block guarded by at the bottom:
When writing Python scripts, you'll often see a code block at the bottom guarded by:

```
if __name__ == "__main__"
Expand Down Expand Up @@ -241,7 +243,7 @@ Instead of raw theory, let's take a look at the real application and try to come

#### Example

Consider a package named `finance` designed to handle various financial calculations and data processing
Consider a package named `finance` designed to handle various financial calculations and data processing.

***Strucure***

Expand All @@ -262,7 +264,7 @@ finance/
# Specify the public API for convenience
__all__ = ['calculator', 'taxes', 'investments']

# You may also initialize some package-wide constants or setup code, though its not a common practice nowdays
# You may also initialize some package-wide constants or setup code, though it's not a common practice nowdays
DEFAULT_TAX_BRACKET = '25%'
```

Expand Down Expand Up @@ -298,7 +300,7 @@ Sub-packages enable even more granular organization within a package, grouping t

For instance, `finance/investments` is a sub-package grouping financial investment-related modules like `stocks.py` and `bonds.py`.

When the project becomes extremely big, think about how you could re-structure to make it more maintainable, reusable and readable.
When the project becomes extremely big, think about how you could re-structure to make it more maintainable, reusable, and readable.

### 5.3 Importing from Packages

Expand Down Expand Up @@ -407,11 +409,11 @@ source venv/bin/activate
pip install requests
```

Let's create an application and split everything into diffrent modules as it was already discussed above.
Let's create an application and split everything into different modules as it was already discussed above.

### 7.2 Weather Fetcher App

**Objective:**: Develop an application to display real-time weather information based on user input.
**Objective:** Develop an application to display real-time weather information based on user input.

***NOTE***: The application will interact with the `OpenWeatherMap` `API` to obtain data for the specified city and present it to the user in a clear and concise format.

Expand Down
14 changes: 7 additions & 7 deletions 13.Files.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ The available modes are:
| ---- | --------------------------------------------------------------------------------------------------------------------------------- |
| r | To read a file, open it. (default) |
| w | To write, open a file. if the file doesn't already exist, creates a new one; otherwise, truncates the existing one. |
| a | Access a file without truncating it so that you can append data to the end of it. if the file does not already exist, creates it. |
| a | Access a file without truncating it so that you can append data to the end of it. If the file does not already exist, creates it. |
| t | Switch to text mode. (default) |
| x | For exclusive creation, open a file. The operation fails if the file already exists. |
| b | In binary mode, open. |
Expand Down Expand Up @@ -93,7 +93,7 @@ def display_menu():
print("3. Exit")
```

In python there is method `readlines()`, it can be used to read contents of a file as well as `read`, but instead of returning one string, it returns a list of small ones(lines of text in the document).
In Python there is method `readlines()`, it can be used to read contents of a file as well as `read`, but instead of returning one string, it returns a list of small ones(lines of text in the document).

#### Example

Expand Down Expand Up @@ -161,7 +161,7 @@ line 3

### 2.5 Renaming and Deleting a File

To rename a file in Python, since there is no built-in way to do that in python, we need 'os' library, particularly
To rename a file in Python, since there is no built-in way to do that in Python, we need 'os' library, particularly
the `os.rename()` method.

```python
Expand Down Expand Up @@ -286,7 +286,7 @@ Base/06.Lists.md --> This is a relative path

The path to a file relative to the active working directory is known as a complete path. You may use the os module to obtain the current working directory.

If you clone this project, the it will be the following
If you clone this project, the full path could be the path in the following example.

#### Example

Expand Down Expand Up @@ -319,7 +319,7 @@ The syntax for using `with open` is as follows:

```python
with open("file_name", "mode") as file:
# code to work with file goes here
# code to work with file goes here
```

When you use `with open`, `Python` automatically closes the file after the block of code included in the `with` statement completes running—even if an exception does.
Expand Down Expand Up @@ -526,7 +526,7 @@ with open("file.yaml", "r") as file:

### Pickle

Pickle is a specificly designed for Python file type, which allows us to store or save Python objects in memory. It is particulary useful in machine learning as it allows to store and transfer heavy ai models in regular memory instead of operative.
Pickle is a specificly designed for Python file type, which allows us to store or save Python objects in memory. It is particulary useful in machine learning as it allows to store and transfer heavy AI models in regular memory instead of operative.

#### Example

Expand Down Expand Up @@ -632,4 +632,4 @@ D) `ValueError`
- Only rename files (not directories).
- Print the old and new names of the files as they are renamed.

For additional functionality and tasks, try to use new modules and libs from the previous lesson, be creative, as it's high time you start developing your own applications!
For additional functionality and tasks, try to use new modules and libs from the previous lesson, be creative, as it's high time you start developing your own applications!
Loading