Skip to content

Commit

Permalink
exception
Browse files Browse the repository at this point in the history
  • Loading branch information
Asabeneh committed Jul 8, 2021
1 parent f6d0c49 commit d255277
Showing 1 changed file with 32 additions and 20 deletions.
52 changes: 32 additions & 20 deletions 17_Day_Exception_handling/17_exception_handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,9 @@

<sub>Author:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> First Edition: Nov 22 - Dec 22, 2019</small>
<small> Second Edition: July, 2021</small>
</sub>
</div>
</div>

[<< Day 16](../16_Day_Python_date_time/16_python_datetime.md) | [Day 18 >>](../18_Day_Regular_expressions/18_regular_expressions.md)

Expand All @@ -37,7 +36,7 @@

Python uses _try_ and _except_ to handle errors gracefully. A graceful exit (or graceful handling) of errors is a simple programming idiom - a program detects a serious error condition and "exits gracefully", in a controlled manner as a result. Often the program prints a descriptive error message to a terminal or log as part of the graceful exit, this makes our application more robust. The cause of an exception is often external to the program itself. An example of exceptions could be an incorrect input, wrong file name, unable to find a file, a malfunctioning IO device. Graceful handling of errors prevents our applications from crashing.

We have covered the different python _error_ types in the previous section. If we use _try_ and _except_ in our program, then it won't raise errors in those blocks.
We have covered the different Python _error_ types in the previous section. If we use _try_ and _except_ in our program, then it will not raise errors in those blocks.

![Try and Except](../images/try_except.png)

Expand Down Expand Up @@ -66,7 +65,6 @@ try:
name = input('Enter your name:')
year_born = input('Year you were born:')
age = 2019 - year_born

print(f'You are {name}. And your age is {age}.')
except:
print('Something went wrong')
Expand All @@ -76,7 +74,7 @@ except:
Something went wrong
```

In the above example, the exception block will run and we do not know exactly the problem. To analize the problem, we can use the different error types with except.
In the above example, the exception block will run and we do not know exactly the problem. To analyze the problem, we can use the different error types with except.

In the following example, it will handle the error and will also tell us the kind of error raised.

Expand All @@ -101,23 +99,20 @@ Type error occured
```

In the code above the output is going to be _TypeError_.

Now, let's add an additional block:

```py
try:
name = input('Enter your name:')
year_born = input('Year you born:')
age = 2019 - int(year_born)

print('You are {name}. And your age is {age}.')
except TypeError:
print('Type error occur')
except ValueError:
print('Value error occur')
except ZeroDivisionError:
print('zero division error occur')

else:
print('I usually run with the try block')
finally:
Expand All @@ -132,14 +127,26 @@ I usually run with the try block
I alway run.
```

It is also shorten the above code as follows:
```py
try:
name = input('Enter your name:')
year_born = input('Year you born:')
age = 2019 - int(year_born)
print('You are {name}. And your age is {age}.')
except Exception as e:
print(e)

```

## Packing and Unpacking Arguments in Python

We use two operators:

- \* for tuples
- \*\* for dictionaries

Let's take as an example below. It takes only arguments but we have list. We can unpack the list and changes to argument.
Let us take as an example below. It takes only arguments but we have list. We can unpack the list and changes to argument.

### Unpacking

Expand All @@ -149,17 +156,17 @@ Let's take as an example below. It takes only arguments but we have list. We can
def sum_of_five_nums(a, b, c, d, e):
return a + b + c + d + e

lst = [1,2,3,4,5]
lst = [1, 2, 3, 4, 5]
print(sum_of_five_nums(lst)) # TypeError: sum_of_five_nums() missing 4 required positional arguments: 'b', 'c', 'd', and 'e'
```

When we run the this code, it raises an error, because this function takes numbers (not a list) as arguments. Let's unpack/destructure the list.
When we run the this code, it raises an error, because this function takes numbers (not a list) as arguments. Let us unpack/destructure the list.

```py
def sum_of_five_nums(a, b, c, d, e):
return a + b + c + d + e

lst = [1,2,3,4,5]
lst = [1, 2, 3, 4, 5]
print(sum_of_five_nums(*lst)) # 15
```

Expand Down Expand Up @@ -189,7 +196,7 @@ print(one, middle, last) # 1 [2, 3, 4, 5, 6] 7

```py
def unpacking_person_info(name, country, city, age):
return '{name} lives in {country}, {city}. He is {age} year old.'
return f'{name} lives in {country}, {city}. He is {age} year old.'
dct = {'name':'Asabeneh', 'country':'Finland', 'city':'Helsinki', 'age':250}
print(unpacking_person_info(**dct)) # Asabeneh lives in Finland, Helsinki. He is 250 years old.
```
Expand Down Expand Up @@ -235,22 +242,27 @@ age = 250

## Spreading in Python

Like in JavaScript, spreading is possible in python. Let's check it in an example below:
Like in JavaScript, spreading is possible in Python. Let us check it in an example below:

```py
lst_one = [1, 2, 3]
lst_two = [4, 5, 6,7]
lst_two = [4, 5, 6, 7]
lst = [0, *list_one, *list_two]
print(lst) # [0, 1, 2, 3, 4, 5, 6, 7]
country_lst_one = ['Finland', 'Sweden', 'Norway']
country_lst_two = ['Denmark', 'Iceland']
nordic_countries = [*country_lst_one, *country_lst_two]
print(nordic_countries) ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
print(nordic_countries) # ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
```

## Enumerate

In we are interested in an index of a list, we use *enumerate*.
If we are interested in an index of a list, we use *enumerate* built-in function to get the index of each item in the list.

```py
for index, item in enumerate([20, 30, 40]):
print(index, item)
```

```py
for index, i in enumerate(countries):
Expand All @@ -268,7 +280,7 @@ The country Finland has been found at index 1.
Sometimes we would like to combine lists when looping through them. See the example below:

```py
fruits = ['banana', 'orange', 'mango', 'lemon']
fruits = ['banana', 'orange', 'mango', 'lemon', 'lime']
vegetables = ['Tomato', 'Potato', 'Cabbage','Onion', 'Carrot']
fruits_and_veges = []
for f, v in zip(fruits, vegetables):
Expand All @@ -278,10 +290,10 @@ print(fruits_and_veges)
```

```sh
[{'fruit': 'banana', 'veg': 'Tomato'}, {'fruit': 'orange', 'veg': 'Potato'}, {'fruit': 'mango', 'veg': 'Cabbage'}, {'fruit': 'lemon', 'veg': 'Onion'}]
[{'fruit': 'banana', 'veg': 'Tomato'}, {'fruit': 'orange', 'veg': 'Potato'}, {'fruit': 'mango', 'veg': 'Cabbage'}, {'fruit': 'lemon', 'veg': 'Onion'}, {'fruit': 'lime', 'veg': 'Carrot'}]
```

🌕 You are determined. You are 17 steps a head to your way to greatness. Now do some exercises for your brain and for your muscle.
🌕 You are determined. You are 17 steps a head to your way to greatness. Now do some exercises for your brain and muscles.

## Exercises: Day 17

Expand Down

0 comments on commit d255277

Please sign in to comment.