---
title: Python Cheatbook Introduction
tags: Python Cheatbook
---
# Introduction
This is a book dedicated to some handy python snippets. I record these snippets as I work with some Python projects during my lifetime.
Please check the bar on the left for table of contents.
:::info
All snippets were recorded with Python version 3.8.
:::
:::warning
Note that this book is still under development
:::
# Basics
## Variable assignment
Initalize with values
```python=
a = 1 # int
b = 'something' # str
c = {1:2, 3:4} # dict
d = [1,2] # list
e = (1,2) # tuple
```
==Initalize data structures with no items==
```python=
a = {} # dict
b = [] # list
c = () # tuple
```
Print stuff
```python=
p = 'charmander'
print(p)
print('this is {}'.format(p)) # .format api can handle different types
```
## Dictionary Manipulation
```python
a[0] = 'value';
a['key'] = 'value';
len(a); # get length
a.__contains__('key'); # returns a boolean
```
## ==Slicing Arrays==
```python=
a = [1,2,3,4]
# array[start:stop], start is inclusive, stop is exclusive
b = a[2:] # [3,4]
c = a[:2] # [1,2]
d = a[1:2] # [2]
```
## For Loops
Normal
```python=
i = [1,2,3]
for x in i:
print(x)
```
<!-- todo: add while loops -->
==Using `enumerate`==
```python=
i = ['A','B','C']
for x, y in enumerate(i):
print('{}: {}'.format(x, y))
```
```python=
my_dict = {'friend_1':88445523, 'friend_2':44552322}
for x, (k, v) in enumerate(my_dict.items()):
print('{}: {} - {}'.format(x, k, v))
```
## ==Classes, Constructors, Private/Public access.==
```python=
class Car:
wheels = 4 # same as self.wheel below
_speed = 150 # private variable because of _
brake = False
# method constructor
def __init__(self, wheels):
self.wheels = wheels
# private method
def _increase_speed(self):
self._speed += 1
# public method
# val:bool takes a boolean value, by default it will be False so the parameter is optional
def modify_brake_application(self, val:bool=False):
self.brake = val
three_wheel_car = Car(3)
three_wheel_car.modify_brake_application()
```
## ==Naming Conventions==
Here is a really awesome page to know naming conventions for various languages: https://namingconvention.org/python/
## Exit
You can use either one of them
- `quit()`
- `exit()`
- `sys.exit()`
Read more: https://pythonguides.com/python-exit-command/