Skip to content
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

Updated with casting and error handling #150

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
187 changes: 187 additions & 0 deletions tutorial-reference/Day 2/Day 2 - Numbers, Variables, and Operators.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
# Day 2 - Variables, Data Types and Operators
This tutorial is based on variables, data types and operators

## Variables
A variable holds a value in a memory location that is needed for the execution of your program.

### Using a variable
A memory location needs to be allocated for the variable value, before it can be used by the program.

**Declaring a variable** means stating what _data type_ will be used for the value.
**Initialising a variable** means _setting the initial value_. Python doesn’t use variable declaration, only initialisation.

**Example**
```python
name = "Alex"
print(name)
```

## Data Types
There are five main data types namely;
- String (text) e.g "Alex", "Sofia"
- Integer (whole numbers) e.g. 3, 4, 5
- Boolean (True or False) e.g. True, False
- Real or floating point numbers (decimal numbers) e.g. 4.5, 7.54
- Char (single string characters) e.g. "a", "z", "b"

**N.B:** Incorrect data types can cause problems during the execution of your programs.

**Question**

Predict what might happen when this code is executed.

```python
print("Enter a number")
num1 = input()
print("Enter another number")
num2 = input()
print(num1+num2)
```
**Output**
```bash
Enter a number
1
Enter another number
2
12
>>>
```
The data type for an input is always string. When you add two pieces of string together, it will concatenate (join) them.
Instead of adding the two numbers together to make 3, it has joined the corresponding strings together to make 12 (one,two).
This code has produced a logic error because it hasn’t executed as expected.

If you want Python to use your value as an integer, then you need to tell it that by **casting the value**.
You do this by placing `input()` inside the `int()` function.

```python
print("Enter a number")
num1 = int(input())
print("Enter another number")
num2 = int(input())
print(num1+num2)
```

```bash
Enter a number
1
Enter another number
2
3
```

Errors can still happen during execution, even when casting has been used.
**Question**

What might happen if the user enters ‘four’ when this code is executed?

**Answer**

A runtime error occurs. This is a type of error that causes the program to crash during execution.

```python
print("Enter a number")
number = int(input())
print(number)
```

```bash
Enter a number
four
Traceback (most recent call last):
File "c:\users\pi\mu_code\fsea.py", line 2, in <module>
number = int(input())
ValueError: invalid literal for int() with base 10: 'four'
>>>
```

You can avoid this type of error by introducing validation checks.
Here is an example check that you can use called try and except.

```python
print("Enter a number")
try:
number = int(input())
except ValueError:
print("You must enter a number")
number = int(input())
```
To convert values to different data types, you need to know the functions that are available to you.
Here are the most common functions that you will need to know.

```python
# convert to string
str()
# convert to integer
int()
# convert to real
float()
```

## Using Operators in Python
Here are the list of operators in python;
- (+) Addition
```python
5 + 5
```
`>>> 10`

- (-) Subtraction
```python
10 - 5
```
`>>> 5`

- (*) Multiplication
```python
5 * 5
```
`>>> 25`

- / Real division
```python
5 / 2
```
`>>> 2.5`

- // Integer division (quotient) is the operation that calculates how many whole times the divisor (3) will fit in the dividend (14).
```python
26 // 5
```
`>>> 5`

- ** Powers
```python
5 ** 2
```
`>>> 25`

- % Modulo (MOD) is used to work out the remainder of the division.
```python
15 % 7
```
`>>> 1`

**Projects**
- **Hello Python**
Create a script to print hello 🐍.

```python
pi = "🐍"
print("Hello", pi)
```

- **Short Intro**
Create a program to introduce someone.

```python
name = "Albert Einstein"
age = 67
profession = "Scientist"

print("Hello!", name, "is", age, "years old and a", profession)
```





This file was deleted.

116 changes: 39 additions & 77 deletions tutorial-reference/Day 3/Day 3 - Lists & Dictionaries.md
Original file line number Diff line number Diff line change
@@ -1,87 +1,49 @@
Day 3 - Lists & Dictionaiers
Mastering lists and dictionaries in Python involves understanding their functionalities, properties, and common operations. Here's a comprehensive breakdown to get you started:

Code https://github.com/codingforentrepreneurs/30-days-of-python
github: cfe.sh/github
**Lists:**

## Reference
_Coming soon_

__Declare__
```
my_list = []
* **Definition:** An ordered collection of items enclosed in square brackets `[]`. Elements can be of any data type, including other lists and dictionaries.
* **Creation:**
```python
my_list = [1, "hello", 3.14, [True, False]]
```
or
* **Accessing elements:** Use zero-based indexing starting from `[0]`. Negative indices access from the end (`[-1]` is the last element).
```python
first_element = my_list[0] # first_element will be 1
last_element = my_list[-1] # last_element will be [True, False]
```
my_list = [1, 2, 3, 4, 5]
* **Slicing:** Extract a sublist using colon (`:`) notation. `[start:end:step]`:
* `start` (inclusive): index of the first element to include (defaults to 0).
* `end` (exclusive): index of the element after the last element to include (defaults to the end of the list).
* `step`: the difference between consecutive elements to include (defaults to 1).
```python
sublist = my_list[1:3] # sublist will be ["hello", 3.14]
```
* **Common operations:**
* `append(element)`: Add an element to the end of the list.
* `insert(index, element)`: Insert an element at a specific index.
* `remove(element)`: Remove the first occurrence of an element.
* `pop(index)`: Remove and return the element at a specific index (or the last element by default).
* `len(list)`: Get the length of the list (number of elements).
* `sort()`: Sort the list in ascending order (modifies the original list).
* `reversed()`: Return a reversed iterator for the list (doesn't modify the original list).

**Dictionaries:**

### Lists
* **Definition:** An unordered collection of key-value pairs enclosed in curly braces `{}`. Keys must be unique and immutable (e.g., strings, numbers, tuples), while values can be any data type.
* **Creation:**
```python
>>> my_cart = [12.99, 312, 32, 142]
>>> sum(my_cart)
498.99
>>> my_cart.append(39.99)
>>> print(my_cart)
[12.99, 312, 32, 142, 39.99]
>>> len(my_cart)
5
>>> my_cart
[12.99, 312, 32, 142, 39.99]
>>> my_cart[3]
142
>>> my_cart[2]
32
>>> my_cart[2] * 120
3840
>>> my_string = "hello world"
>>> len(my_string)
11
>>> my_string[4]
'o'

>>> my_cart
[12.99, 312, 32, 142, 39.99]
>>> my_items = ["mouse", "laptop", "mic", "screen", "snack"]
>>> my_items
['mouse', 'laptop', 'mic', 'screen', 'snack']
>>> my_cart[1]
312
>>> my_items[1]
'laptop'
>>> my_products = [my_items, my_cart]
>>> my_products
[['mouse', 'laptop', 'mic', 'screen', 'snack'], [12.99, 312, 32, 142, 39.99]]
>>>
my_dict = {"name": "Alice", "age": 30, "hobbies": ["reading", "hiking"]}
```

### Dictionaries
* **Accessing elements:** Use the key enclosed in square brackets `[]` to access the corresponding value.
```python
>>> my_list = [1,2,3,4,5]
>>> my_data = {"name": "Justin Mitchel"}
>>> my_data["name"]
'Justin Mitchel'
>>> my_data = {"name": "Justin Mitchel", "location": "California"}
>>> my_data[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 0
>>> my_data.keys()
dict_keys(['name', 'location'])
>>> list(my_data.keys())
['name', 'location']
>>> list(my_data.keys())[0]
'name'
>>> my_data.append({"occ": "coder"})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'append'
>>> my_data["occ"] = "Coder"
>>> my_data
{'name': 'Justin Mitchel', 'location': 'California', 'occ': 'Coder'}
>>> user_1 = {"name": "James bond"}
>>> user_2 = {"name": "Ned Stark"}
>>> my_users = [user_1, user_2]
>>> my_users
[{'name': 'James bond'}, {'name': 'Ned Stark'}]
```
name = my_dict["name"] # name will be "Alice"
```
* **Common operations:**
* `get(key, default)`: Get the value for a key, returning `default` if the key is not found.
* `keys()`: Return a view of all keys in the dictionary.
* `values()`: Return a view of all values in the dictionary.
* `items()`: Return a view of all key-value pairs as tuples.
* `in`: Check if a key exists in the dictionary.
* `update(dict2)`: Update the dictionary with key-value pairs from another dictionary (`dict2`).
* `pop(key, default)`: Remove the key-value pair and return the value, or `default` if the key is not found.