# Basic Python

### Basic Components 🐍

Python follows basic order of operations when evaluating expressions, similar to PEMDAS for math.

| Operator | Operation                  | Example | Evaluates to |
| -------- | -------------------------- | ------- | ------------ |
| `**`     | Exponent                   | 2\*\*4  | 16           |
| `%`      | Modulus (remainder!)       | 5 % 2   | 1            |
| `//`     | Integer Division (floored) | 11 // 2 | 5            |
| `/`      | Division                   | 11 / 2  | 5.5          |
| `*`      | Multiplication             | 2 \* 3  | 6            |
| `-`      | Subtraction                | 3 - 2   | 1            |
| `+`      | Addition                   | 2 + 4   | 6            |

### Data Types and Classifications 👩‍🏫

Using a single equals `=` is an **assignment** operator, where it **assigns** a value to a variable.

Using double equals `==` is a **comparison** operator, where it **checks** two values!

### Flow Control 🌊🤽‍♀️

Tons of different ways to control execution of the program. Fundamental way in how programs work and look like magic ✨ Until you realize that whitespace is interpreted. Make sure you use four spaces instead of tabs, just as God intended.

```python
# if, elif, and else control!!
ayyy = 'lmao'

# if statements check if a statement is true
if ayyy == 'lmao':
    print('👽👽👽')

# elif statments help  determine one of many possible clauses
elif len(ayyy) == 4:
    print('😂😂😂😂')

# can have have several elif, but skips any remaining elif after first True
elif len(ayyy) != 4:
    print('🤔🤔🤔')

# else statements is executed ONLY if the preceeding if is False (NOT REQUIRED!)
else:
    print('❌👽❌')
```

There are `while` loops which will check for a condition and keep executing until completed. Using `break` will exit the while loop early! Similarly, `continue` statements will jump back to the beginning of a `while` loop and evaluate the loop's condition.

```python
# while loops will execute until a condition is met
count = 0

while count < 5:
    print('ayyy')
    count = count + 1
print('lmao')

name = ''
while name != 'your name':
    print('Please type your name')
    name = input()

# break statements exit the while loop's clause early, continue jump to start of while
name = ''
while True:
    print('Please type your name')
    name = input()
    if name != 'your name':
        continue
    print('What\'s the password?')
    pass = input()
    if pass = 'ayyylmao':
        break
print('Well done!')
```

Another loop is the `for` loop which can repeat an action a specific amount of times. When using `range` we can also specify start, stop, and steps.

```python
ayyy = 'lmao'

# Print the var ayyy five times
for i in range(5):
    print(ayyy)

# Print the value of i between two values
for i in range(12, 15):
    print(i)

# Similar, only with a step!
for i in range(0, 10, 2):
    print(i)
```

### Strings 🧵

We can take a string of any length and reference ANY part of it!&#x20;

```python
lmao = 'holy hell'

# Print first character of string lmao
print(lmao[0])

# Print last character of string lmao
print(lmao[-1])

# Print entire string backwards!
print(lmao[::-1])

# Split string on a delimeter, default is space
haha = lmao.split()
print(haha)

# Replace certain parts of a string
print(lmao.replace('h','')  # prints 'hoy he'
```

### Lists 📜📜

```python
ans = ['H', 'E', 'L', 'L', 'O']
print(''.join(ans))
# Will print HELLO
```

Comprehension

Search for a partial match in a list and add to another list. Super useful!

```python
origList = ['big','bad','bigly']
subStr = 'ig'
filterList = [string for string in origList if subStr in string]
```

Tuples

### Dictionaries 📚📚

Very similar to JSON. In fact, so close, it can be converted to JSON with minor worries!

```python
# Create the dict type
lmao = {'one':1,'two':2}

# Add a new key to the dictionary
lmao['three'] = 3

# Loop over each pair of keys and values to access
for i, k in enumerate(lmao):
    print(i, k)

# Will print:
# one 1
# two 2
# three 3

```

User Inputs

#### Loops

```python
from string import ascii_lowercase
for a in ascii_lowercase:
    for b in ascii_lowercase:
        print(a+b)
```

Arithmetic and Conditionals

Regex Matching

## Convert bytes to IPv4

```python
ipaddr = '.'.join(f'{c}' for c in line['ipAddress'])
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://notes.m4lwhere.org/programming/python/basic-python.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
