---
# System prepended metadata

title: MLE - Week 1
tags: [week1, list, variables, loop, mle, basics, conditionals]

---

# MLE - Week 1

Summary
-------
- Syntax, variables, data types, input, output
- Conditionals
- Collections: List
- Loop


Syntax
------
- Unlike Java, Python doesn't have the `;` `{}` :blush:
- Indentation needs to be strictly followed:exclamation: This makes the code, by default, formatted.
- Comments:
```python=
# This is a comment in Python

"""
This is a "block comment" in Python.
"""
```
- Data types are determined at run time :worried:
- [Built-in functions](https://docs.python.org/3/library/functions.html)

Variables
---------
>:point_right: A good variable name describes the data it contains.
>- It can be only one word with no spaces.
>- It can use only letters, numbers, and the underscore (_) character.
>- It can’t begin with a number.

`camelCase` or `snake_case` are both good. As per ([3] - Variable Names), he'd prefer to use `camelCase`.

*Reserved words* **can’t** be used as identifiers for other programming elements like name of *variable*, *function* etc. [Python 3 has 33 keywords](https://www.tutorialspoint.com/What-are-Reserved-Keywords-in-Python).


Data types (built-in)
---------------------
### strings
:point_right: String can be considered as a **list** of characters, have similar characteristics as **list**, but string is **immutable**.

#### operations
| Operation    | Name           | Description|
|--------------|----------------|------------|
| ``a + b``    | String concatenation | `'coder' + 'school' # = 'coderschool'`. Note: `'coder'+2 #error`|
| ``a * b``    | String replication |`'coder'*2 #'codercoder'`, :warning: 2nd operand **must** be `int`, not `float`|

### numerics
#### int and float
>The plain `int` type is unbounded.

```python=
>>> 42 == '42'
False
>>> 42 == 42.0
True
>>> 42.0 == 0042.000
True
```

#### operations
From 1.5 > Part 2 > 2_a
| Operation    | Name           | Description|
|--------------|----------------|------------|
| ``a + b``    | Addition       | Sum of ``a`` and ``b``|
| ``a - b``    | Subtraction    | Difference of ``a`` and ``b``|
| ``a * b``    | Multiplication | Product of ``a`` and ``b``|
| ``a / b``    | True division  | Quotient of ``a`` and ``b``|
| ``a // b``   | Floor division | Quotient of ``a`` and ``b``, removing fractional parts |
| ``a % b``    | Modulus        | Integer remainder after division of ``a`` by ``b``|
| ``a ** b``   | Exponentiation | ``a`` raised to the power of ``b``|
| ``-a``       | Negation       | The negative of ``a``|

>The order of operations (also called precedence) of Python math operators is similar to that of mathematics: `**` > `* / // %` > `+ -`.

#### comparisons
>Comparisons can be chained arbitrarily; for example, x < y <= z.

### booleans
:point_right: Booleans are **a subtype of integers**. By default, an object is considered to be `True` ([1]).

Here are most of the built-in objects considered `False`:
- constants defined to be false: `None` and `False`.
- zero of any numeric type: `0, 0.0, 0j, Decimal(0), Fraction(0, 1)`
- empty sequences and collections: `'', (), [], {}, set(), range(0)`

```
False == 0 # True
True == 1 # True
True*False+True*True # = 1
```

#### Logic operators
:point_right: *The expression will be evaluated from left to right*
- `and`: a and b (if `a` is `False`, b won't be evaluated.([2])).
- `or`: a or b (if `a` is `True`, b won't be evaluated.([2])).
- `not`: not a.
- `^`: either a or b, but not both.

List
----
>:point_right: A list is a value that contains **multiple values** (allows duplicates) in an **ordered** sequence.

A list can contain a mix of different data types:
```python=
my_favourite_things = [32, 'Always be learning!', help]
```

### range
```python=
range(stop)
range(start, stop[, step])
```

### operations
| Operation      | Result             |
| -------------- | ------------------ |
| `x in s`       | `True` if an item of `s` is equal to `x`, else `False`                     |
| `x not in s`     | `False` if an item of `s` is equal to `x`, else `True`                     |
| `s + t`          | the concatenation of `s` and `t`                                               |
| `s * n` or `n * s` | equivalent to adding s to itself *n* times                                   |
| `s[i]`           | ith item of `s`, origin 0                                                    |
| `s[i:j]`        | slice of `s` from index `i` to index `j-1`. :warning: it returns `[]` if `i > j`. |
| `s[i:j:k]`       | slice of `s` from index `i` to index `j-1` with step `k`. :penguin: if `k` is a negative number, it will go backward.|
| `len(s)`         | length of s (built-in)                                                     |
| `min(s)`         | smallest item of s                                                         |
| `max(s)`         | largest item of s                                                          |
| `s.count(x)`     | total number of occurrences of x in s                                      |

```python=
>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]
```
*VS*
```python=
>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]
```

---
Examples:

<img src="https://i1.faceprep.in/Companies-1/lists-in-python.png" width=600>

```python=
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

print(planets.index('Earth')) # 2

print(planets.index('Kyrpton')) # Error

print(planets[1] if len(planets) > 1 else 'None') #Ternary Operator
```

### list methods
|Method|	Description|
|------|---------------|
|append()|	Adds an element at the end of the list|
clear()	|Removes all the elements from the list|
copy()	|Returns a copy of the list|
count()	|Returns the number of elements with the specified value|
extend()|	Add the elements of a list (or any iterable), to the end of the current list|
index()|	Returns the index of the first element with the specified value|
insert()|	Adds an element at the specified position|
pop()|	Removes the element at the specified position|
remove()|	Removes the first item with the specified value|
reverse()|	Reverses the order of the list|
sort()|	Sorts the list|
[Python List/Array Methods](https://www.w3schools.com/python/python_ref_list.asp)

From 1.5 > Part 4 > 4_f
:penguin: `list.extend` also adds item to the end of the list. However, the main difference between `extend` and `append` is `extend` add each elements of a list (or any iterable) while `append` will add the whole list.

Input and ouput
---------------
:point_right: The `input()` function waits for the user to type some text on the keyboard and press ENTER.

:point_right: The `print()` function displays the string value inside its parentheses on the screen.
:penguin: `print(f'The string can combine with {variable}.')`

Conditionals
------------
```python=
if [condition 1]:
    [do A]
elif [condition 2]:
    [do B]
elif [condition 3]:
    [do C]
else:
    [do D]
```

Loop
----
### *break* and *continue* statements
:point_right: `break`: exit the nearest loop.
```python=
for i in l1:
    for j in l2:
        print(i, j)
        if i == 2 and j == 20 :
            print('BREAK')
            break
# 1 10
# 1 20
# 1 30
# 2 10
# 2 20
# BREAK
# 3 10
# 3 20
# 3 30
```

:point_right: `continue`: immediately jumps back to the start of the loop and reevaluates the loop’s condition.

>:warning: In fact, you can use `continue` and `break` statements **only** inside *while* and *for* loops. If you try to use these statements **elsewhere**, Python will give you an **error**.

### *for* Loops
```python=
fruits = ['papaya', 'watermelon', 'dragonfruit', 'banana']
for fruit in fruits:
  print(fruit)
  
for index in range(0, len(fruits)):
  print(f'{fruits[index]} is {index}')
```

### *while* Loops
```python=
spam = 0
while spam < 5:
    print('Hello, world.')
    spam = spam + 1
```


[1]: https://docs.python.org/3/library/stdtypes.html#truth-value-testing
[2]: https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not
[3]: https://automatetheboringstuff.com/2e/chapter1/


###### tags: `mle` `week1` `basics` `variables` `conditionals` `list` `loop`
