diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
new file mode 100644
index 000000000..a9ccc188b
--- /dev/null
+++ b/.github/FUNDING.yml
@@ -0,0 +1,3 @@
+github: [Asabeneh]
+thanks_dev:
+custom: []
diff --git a/.gitignore b/.gitignore
index bd49bee46..e9c3c9a5d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,4 +16,6 @@ flask_project/venv/include/
flask_project/ven/lib
numpy.ipynb
.ipynb_checkpoints
-.vscode/
\ No newline at end of file
+.vscode/
+*~
+test.py
\ No newline at end of file
diff --git a/01_Day_Introduction/helloworld.py b/01_Day_Introduction/helloworld.py
index 00f6cb346..d8007868f 100644
--- a/01_Day_Introduction/helloworld.py
+++ b/01_Day_Introduction/helloworld.py
@@ -1,9 +1,14 @@
-
+# Introduction
# Day 1 - 30DaysOfPython Challenge
+print("Hello World!") # print hello world
+
print(2 + 3) # addition(+)
print(3 - 1) # subtraction(-)
print(2 * 3) # multiplication(*)
+print(3 + 2) # addition(+)
+print(3 - 2) # subtraction(-)
+print(3 * 2) # multiplication(*)
print(3 / 2) # division(/)
print(3 ** 2) # exponential(**)
print(3 % 2) # modulus(%)
@@ -16,5 +21,5 @@
print(type(1 + 3j)) # Complex
print(type('Asabeneh')) # String
print(type([1, 2, 3])) # List
-print(type({'name':'Asabeneh'})) # Dictionary
-print(type({9.8, 3.14, 2.7})) # Tuple
\ No newline at end of file
+print(type({'name': 'Asabeneh'})) # Dictionary
+print(type({9.8, 3.14, 2.7})) # Tuple
diff --git a/02_Day_Variables/02_variables.md b/02_Day_Variables_builtin_functions/02_variables_builtin_functions.md
similarity index 52%
rename from 02_Day_Variables/02_variables.md
rename to 02_Day_Variables_builtin_functions/02_variables_builtin_functions.md
index 2445b7372..722edb3ad 100644
--- a/02_Day_Variables/02_variables.md
+++ b/02_Day_Variables_builtin_functions/02_variables_builtin_functions.md
@@ -1,5 +1,5 @@
-
30 Days Of Python: Day 2 - Variables
+
30 Days Of Python: Day 2 - Variables, Builtin Functions
@@ -9,60 +9,61 @@
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+ Second Edition: July, 2021
-
-
-
[<< Day 1](../readme.md) | [Day 3 >>](../03_Day_Operators/03_operators.md)

-- [📘 Day 2](#%f0%9f%93%98-day-2)
+- [📘 Day 2](#-day-2)
- [Built in functions](#built-in-functions)
- [Variables](#variables)
+ - [Declaring Multiple Variable in a Line](#declaring-multiple-variable-in-a-line)
- [Data Types](#data-types)
- [Checking Data types and Casting](#checking-data-types-and-casting)
- [Numbers](#numbers)
- - [💻 Exercises - Day 2](#%f0%9f%92%bb-exercises---day-2)
+ - [💻 Exercises - Day 2](#-exercises---day-2)
+ - [Exercises: Level 1](#exercises-level-1)
+ - [Exercises: Level 2](#exercises-level-2)
# 📘 Day 2
## Built in functions
-In python we have lots of built-in functions. Built-in functions are globally available for your use. Some of the most commonly used python built-in functions are the following: _print()_, _len()_, _type()_, _int()_, _float()_, _str()_, _input()_, _list()_, _dict()_, _min()_, _max()_, _sum()_, _sorted()_, _open()_, _file()_, _help()_, and _dir()_. In the following table you will see an exhaustive list of python built-in functions taken from [python documentation](https://docs.python.org/2/library/functions.html).
+In Python we have lots of built-in functions. Built-in functions are globally available for your use that mean you can make use of the built-in functions without importing or configuring. Some of the most commonly used Python built-in functions are the following: _print()_, _len()_, _type()_, _int()_, _float()_, _str()_, _input()_, _list()_, _dict()_, _min()_, _max()_, _sum()_, _sorted()_, _open()_, _file()_, _help()_, and _dir()_. In the following table you will see an exhaustive list of Python built-in functions taken from [python documentation](https://docs.python.org/3/library/functions.html).

-Let's open the python shell and start using some of the most common built-in functions.
+Let us open the Python shell and start using some of the most common built-in functions.

-Let's practice more by using different built-in functions
+Let us practice more by using different built-in functions

-As you can see from the terminal above, python has got reserved words. We do not use reserved words to declare variables or functions. We will cover variables in the next section.
+As you can see from the terminal above, Python has got reserved words. We do not use reserved words to declare variables or functions. We will cover variables in the next section.
-I believe, by now you are familiar with built-in functions. Let's do one more practice of built-in functions and we will move on to the next section
+I believe, by now you are familiar with built-in functions. Let us do one more practice of built-in functions and we will move on to the next section.

## Variables
-Variables store data in a computer memory. Mnemonic variables are recommended to use in many programming languages. A variable refers to a memory address in which data is stored.
-Number at the beginning, special character, hyphen are not allowed when naming them. A variable can have a short name (like x,y,z), but a more descriptive name (firstname, lastname, age, country) is highly recommended.
+Variables store data in a computer memory. Mnemonic variables are recommended to use in many programming languages. A mnemonic variable is a variable name that can be easily remembered and associated. A variable refers to a memory address in which data is stored.
+Number at the beginning, special character, hyphen are not allowed when naming a variable. A variable can have a short name (like x, y, z), but a more descriptive name (firstname, lastname, age, country) is highly recommended.
+
Python Variable Name Rules
- A variable name must start with a letter or the underscore character
- A variable name cannot start with a number
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and \_ )
-- Variable names are case-sensitive (firstname, Firstname, FirstName and FIRSTNAME are different variables)
+- Variable names are case-sensitive (firstname, Firstname, FirstName and FIRSTNAME) are different variables)
-Valid variable names
+Here are some example of valid variable names:
```shell
firstname
@@ -74,9 +75,10 @@ first_name
last_name
capital_city
_if # if we want to use reserved word as a variable
-year_2019
-year2019
-current_year_2019
+year_2021
+year2021
+current_year_2021
+birth_year
num1
num2
```
@@ -85,19 +87,20 @@ Invalid variables names
```shell
first-name
+first@name
+first$name
num-1
1num
```
-We will use standard python variable naming style which has been adopted by many python developers. The example below is an example of standard naming of variables, underscore when the variable name is long.
+We will use standard Python variable naming style which has been adopted by many Python developers. Python developers use snake case(snake_case) variable naming convention. We use underscore character after each word for a variable containing more than one word(eg. first_name, last_name, engine_rotation_speed). The example below is an example of standard naming of variables, underscore is required when the variable name is more than one word.
-When we assign a certain data type to a variable, it is called variable declaration. For instance in the example below my first name is assigned to a variable first_name. The equal sign is an assignment operator. Assigning means storing data in the variable.
+When we assign a certain data type to a variable, it is called variable declaration. For instance in the example below my first name is assigned to a variable first_name. The equal sign is an assignment operator. Assigning means storing data in the variable. The equal sign in Python is not equality as in Mathematics.
_Example:_
```py
# Variables in Python
-
first_name = 'Asabeneh'
last_name = 'Yetayeh'
country = 'Finland'
@@ -113,17 +116,17 @@ person_info = {
}
```
-Let's use _print()_ and _len()_ built in functions. Print function will take multiple arguments. An argument is a value which we pass or put inside the function parenthesis, see the example below.
+Let us use the _print()_ and _len()_ built-in functions. Print function takes unlimited number of arguments. An argument is a value which we can be passed or put inside the function parenthesis, see the example below.
**Example:**
```py
-print('Hello, World!')
-print('Hello',',', 'World','!') # it can take multiple arguments
+print('Hello, World!') # The text Hello, World! is an argument
+print('Hello',',', 'World','!') # it can take multiple arguments, four arguments have been passed
print(len('Hello, World!')) # it takes only one argument
```
-Let's print and also find the length of the variables declared at the top:
+Let us print and also find the length of the variables declared at the top:
**Example:**
@@ -142,7 +145,9 @@ print('Skills: ', skills)
print('Person information: ', person_info)
```
-Variables can also be declared in one line:
+### Declaring Multiple Variable in a Line
+
+Multiple variables can also be declared in one line:
**Example:**
@@ -157,7 +162,7 @@ print('Age: ', age)
print('Married: ', is_married)
```
-Getting user input using the _input()_ built-in function. Let's assign the data we get from a user into first_name and age variables.
+Getting user input using the _input()_ built-in function. Let us assign the data we get from a user into first_name and age variables.
**Example:**
```py
@@ -170,12 +175,12 @@ print(age)
## Data Types
-There are several data types in python. To identify the data type we use the _type_ builtin function. I would like you to focus on understanding different data types very well. When it comes to programming, it is all about data types. I introduced data types at the very beginning and it comes again, because every topic is related to data types. We will cover data types in more detail in their respective sections.
+There are several data types in Python. To identify the data type we use the _type_ built-in function. I would like to ask you to focus on understanding different data types very well. When it comes to programming, it is all about data types. I introduced data types at the very beginning and it comes again, because every topic is related to data types. We will cover data types in more detail in their respective sections.
## Checking Data types and Casting
- Check Data types: To check the data type of certain data/variable we use the _type_
- **Example:**
+ **Examples:**
```py
# Different python data types
@@ -188,32 +193,31 @@ city= 'Helsinki' # str
age = 250 # int, it is not my real age, don't worry about it
# Printing out types
-print(type('Asabeneh')) # str
-print(type(first_name)) # str
-print(type(10)) # int
-print(type(3.14)) # float
-print(type(1 + 1j)) # complex
-print(type(True)) # bool
-print(type([1, 2,3,4])) # list
-print(type({'name':'Asabeneh','age':250, 'is_married':250})) # dict
-print(type((1,2))) # tuple
-print(type(zip([1,2],[3,4]))) # set
+print(type('Asabeneh')) # str
+print(type(first_name)) # str
+print(type(10)) # int
+print(type(3.14)) # float
+print(type(1 + 1j)) # complex
+print(type(True)) # bool
+print(type([1, 2, 3, 4])) # list
+print(type({'name':'Asabeneh'})) # dict
+print(type((1,2))) # tuple
+print(type(zip([1,2],[3,4]))) # zip
```
-- Casting: Converting one data type to another data type. We use _int()_, _float()_, _str()_, _list_
- When we do arithmetic operations string numbers should be first converted to int or float otherwise it will return an error. If we concatenate a number with string, the number should be first converted to a string. We will talk about concatenation in String section.
- **Example:**
+- Casting: Converting one data type to another data type. We use _int()_, _float()_, _str()_, _list_, _set_
+ When we do arithmetic operations string numbers should be first converted to int or float otherwise it will return an error. If we concatenate a number with a string, the number should be first converted to a string. We will talk about concatenation in String section.
+
+ **Examples:**
```py
# int to float
-
num_int = 10
print('num_int',num_int) # 10
num_float = float(num_int)
print('num_float:', num_float) # 10.0
# float to int
-
gravity = 9.81
print(int(gravity)) # 9
@@ -223,22 +227,25 @@ print(num_int) # 10
num_str = str(num_int)
print(num_str) # '10'
-# str to int
+# str to int or float
num_str = '10.6'
+num_float = float(num_str) # Convert the string to a float first
+num_int = int(num_float) # Then convert the float to an integer
print('num_int', int(num_str)) # 10
print('num_float', float(num_str)) # 10.6
+num_int = int(num_float)
+print('num_int', int(num_int)) # 10
# str to list
-first = 'Asabeneh'
-print(first_name)
-print(first_name) # 'Asabeneh'
+first_name = 'Asabeneh'
+print(first_name) # 'Asabeneh'
first_name_to_list = list(first_name)
print(first_name_to_list) # ['A', 's', 'a', 'b', 'e', 'n', 'e', 'h']
```
## Numbers
-Number data types in python:
+Number data types in Python:
1. Integers: Integer(negative, zero and positive) numbers
Example:
@@ -252,8 +259,12 @@ Number data types in python:
Example:
1 + j, 2 + 4j, 1 - 1j
+🌕 You are awesome. You have just completed day 2 challenges and you are two steps ahead on your way to greatness. Now do some exercises for your brain and muscles.
+
## 💻 Exercises - Day 2
+### Exercises: Level 1
+
1. Inside 30DaysOfPython create a folder called day_2. Inside this folder create a file named variables.py
2. Write a python comment saying 'Day 2: 30 Days of python programming'
3. Declare a first name variable and assign a value to it
@@ -267,23 +278,26 @@ Number data types in python:
11. Declare a variable is_true and assign a value to it
12. Declare a variable is_light_on and assign a value to it
13. Declare multiple variable on one line
-14. Check the data type of all your variables using type() built-in function
-15. Using the _len()_ built-in function find the length of your first name
-16. Compare the length of your first name and your last name
-17. Declare 5 as num_one and 4 as num_two
- 1. Add num_one and num_two and assign the value to a variable \_total
- 2. Subtract num_two from num_one and assign the value to a variable \_diff
- 3. Multiply num_two and num_one and assign the value to a variable \_product
- 4. Divide num_one by num_two and assign the value to a variable \_division
- 5. Use modulus division to find num_two divided by num_one and assign the value to a variable \_remainder
- 6. Calculate num_one to the power of num_two and assign the value to a variable \_exp
- 7. Find floor division of num_one by num_two and assign the value to a variable \_floor_division
-18. The radius of a circle is 30 meters.
- 1. Calculate the area of a circle and assign the value to a variable _area_of_circle_
- 2. Calculate the circumference of a circle and assign the value to a variable _circum_of_circle_
+
+### Exercises: Level 2
+
+1. Check the data type of all your variables using type() built-in function
+2. Using the _len()_ built-in function, find the length of your first name
+3. Compare the length of your first name and your last name
+4. Declare 5 as num_one and 4 as num_two
+5. Add num_one and num_two and assign the value to a variable total
+6. Subtract num_two from num_one and assign the value to a variable diff
+7. Multiply num_two and num_one and assign the value to a variable product
+8. Divide num_one by num_two and assign the value to a variable division
+9. Use modulus division to find num_two divided by num_one and assign the value to a variable remainder
+10. Calculate num_one to the power of num_two and assign the value to a variable exp
+11. Find floor division of num_one by num_two and assign the value to a variable floor_division
+12. The radius of a circle is 30 meters.
+ 1. Calculate the area of a circle and assign the value to a variable name of _area_of_circle_
+ 2. Calculate the circumference of a circle and assign the value to a variable name of _circum_of_circle_
3. Take radius as user input and calculate the area.
-19. Use the built-in input function to get first name, last name, country and age from a user and store the value to their corresponding variable names
-20. Run help('keywords') in python shell or in your file to check for the reserved words
+13. Use the built-in input function to get first name, last name, country and age from a user and store the value to their corresponding variable names
+14. Run help('keywords') in Python shell or in your file to check for the Python reserved words or keywords
🎉 CONGRATULATIONS ! 🎉
diff --git a/02_Day_Variables_builtin_functions/variables.py b/02_Day_Variables_builtin_functions/variables.py
new file mode 100644
index 000000000..bb5c28037
--- /dev/null
+++ b/02_Day_Variables_builtin_functions/variables.py
@@ -0,0 +1,40 @@
+
+# Variables in Python
+
+first_name = 'Asabeneh'
+last_name = 'Yetayeh'
+country = 'Finland'
+city = 'Helsinki'
+age = 250
+is_married = True
+skills = ['HTML', 'CSS', 'JS', 'React', 'Python']
+person_info = {
+ 'firstname': 'Asabeneh',
+ 'lastname': 'Yetayeh',
+ 'country': 'Finland',
+ 'city': 'Helsinki'
+}
+
+# Printing the values stored in the variables
+
+print('First name:', first_name)
+print('First name length:', len(first_name))
+print('Last name: ', last_name)
+print('Last name length: ', len(last_name))
+print('Country: ', country)
+print('City: ', city)
+print('Age: ', age)
+print('Married: ', is_married)
+print('Skills: ', skills)
+print('Person information: ', person_info)
+
+# Declaring multiple variables in one line
+
+first_name, last_name, country, age, is_married = 'Asabeneh', 'Yetayeh', 'Helsink', 250, True
+
+print(first_name, last_name, country, age, is_married)
+print('First name:', first_name)
+print('Last name: ', last_name)
+print('Country: ', country)
+print('Age: ', age)
+print('Married: ', is_married)
diff --git a/03_Day_Operators/03_operators.md b/03_Day_Operators/03_operators.md
index f3e23ddb1..972b56943 100644
--- a/03_Day_Operators/03_operators.md
+++ b/03_Day_Operators/03_operators.md
@@ -9,24 +9,22 @@
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+ Second Edition: July, 2021
-
-
-[<< Day 2](../02_Day_Variables/02_variables.md) | [Day 4 >>](../04_Day_Strings/04_string.md)
+[<< Day 2](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) | [Day 4 >>](../04_Day_Strings/04_strings.md)

-- [📘 Day 3](#%f0%9f%93%98-day-3)
+- [📘 Day 3](#-day-3)
- [Boolean](#boolean)
- - [Operators:](#operators)
- - [Assignment Operators:](#assignment-operators)
+ - [Operators](#operators)
+ - [Assignment Operators](#assignment-operators)
- [Arithmetic Operators:](#arithmetic-operators)
- [Comparison Operators](#comparison-operators)
- [Logical Operators](#logical-operators)
- - [💻 Exercises - Day 3](#%f0%9f%92%bb-exercises---day-3)
+ - [💻 Exercises - Day 3](#-exercises---day-3)
# 📘 Day 3
@@ -40,13 +38,13 @@ print(True)
print(False)
```
-## Operators:
+## Operators
Python language supports several types of operators. In this section, we will focus on few of them.
-### Assignment Operators:
+### Assignment Operators
-Assignment operators are used to assign values to variables. Let's take = as an example. Equal sign in mathematics shows that two values are equal, however in python it means we are storing a value in a certain variable and we call it assignment or a assigning value to a variable. The table below shows the different types of python assignment operators, taken from [w3school](https://www.w3schools.com/python/python_operators.asp).
+Assignment operators are used to assign values to variables. Let us take = as an example. Equal sign in mathematics shows that two values are equal, however in Python it means we are storing a value in a certain variable and we call it assignment or a assigning value to a variable. The table below shows the different types of python assignment operators, taken from [w3school](https://www.w3schools.com/python/python_operators.asp).

@@ -54,11 +52,11 @@ Assignment operators are used to assign values to variables. Let's take = as an
- Addition(+): a + b
- Subtraction(-): a - b
-- Multiplication(*):a * b
+- Multiplication(*): a * b
- Division(/): a / b
-- Modulus(%):a % b
+- Modulus(%): a % b
- Floor division(//): a // b
-- Exponentiation(**):a ** b
+- Exponentiation(**): a ** b

@@ -68,16 +66,16 @@ Assignment operators are used to assign values to variables. Let's take = as an
# Arithmetic Operations in Python
# Integers
-print('Addition: ', 1 + 2)
-print('Subtraction: ', 2 - 1)
-print('Multiplication: ', 2 * 3)
-print ('Division: ', 4 / 2) # Division in python gives floating number
-print('Division: ', 6 / 2)
-print('Division: ', 7 / 2)
-print('Division without the remainder: ', 7 // 2) # gives without the floating number or without the remaining
-print('Modulus: ', 3 % 2) # Gives the remainder
-print ('Division without the remainder: ',7 // 3)
-print('Exponentiation: ', 3 ** 2) # it means 3 * 3
+print('Addition: ', 1 + 2) # 3
+print('Subtraction: ', 2 - 1) # 1
+print('Multiplication: ', 2 * 3) # 6
+print ('Division: ', 4 / 2) # 2.0 Division in Python gives floating number
+print('Division: ', 6 / 2) # 3.0
+print('Division: ', 7 / 2) # 3.5
+print('Division without the remainder: ', 7 // 2) # 3, gives without the floating number or without the remaining
+print ('Division without the remainder: ',7 // 3) # 2
+print('Modulus: ', 3 % 2) # 1, Gives the remainder
+print('Exponentiation: ', 2 ** 3) # 8 it means 2 * 2 * 2
```
**Example:Floats**
@@ -92,8 +90,8 @@ print('Floating Point Number, gravity', 9.81)
```py
# Complex numbers
-print('Complex number: ', 1+1j)
-print('Multiplying complex numbers: ',(1+1j) * (1-1j))
+print('Complex number: ', 1 + 1j)
+print('Multiplying complex numbers: ',(1 + 1j) * (1 - 1j))
```
Let's declare a variable and assign a number data type. I am going to use single character variable but remember do not develop a habit of declaring such types of variables. Variable names should be all the time mnemonic.
@@ -115,15 +113,15 @@ remainder = a % b
floor_division = a // b
exponential = a ** b
-# I should have used sum instead of total but sum is a built-in function - try to avoid overriding builtin functions
-print(total) # if you don't label your print with some string, you never know where the result is coming from
+# I should have used sum instead of total but sum is a built-in function - try to avoid overriding built-in functions
+print(total) # if you do not label your print with some string, you never know where the result is coming from
print('a + b = ', total)
print('a - b = ', diff)
print('a * b = ', product)
print('a / b = ', division)
print('a % b = ', remainder)
print('a // b = ', floor_division)
-print('a ** b = ', exponentiation)
+print('a ** b = ', exponential)
```
**Example:**
@@ -139,7 +137,7 @@ num_two = 4
total = num_one + num_two
diff = num_two - num_one
product = num_one * num_two
-div = num_two / num_two
+div = num_two / num_one
remainder = num_two % num_one
# Printing values with label
@@ -150,7 +148,7 @@ print('division: ', div)
print('remainder: ', remainder)
```
-Let's start start connecting the dots and start making use of what we already know to calculate (area, volume, weight, perimeter, distance, force)
+Let us start connecting the dots and start making use of what we already know to calculate (area, volume,density, weight, perimeter, distance, force).
**Example:**
@@ -164,18 +162,25 @@ print('Area of a circle:', area_of_circle)
length = 10
width = 20
area_of_rectangle = length * width
-print('Area of rectangle:', area_of_width)
+print('Area of rectangle:', area_of_rectangle)
# Calculating a weight of an object
mass = 75
gravity = 9.81
weight = mass * gravity
print(weight, 'N') # Adding unit to the weight
+
+# Calculate the density of a liquid
+mass = 75 # in Kg
+volume = 0.075 # in cubic meter
+density = mass / volume # 1000 Kg/m^3
+print(density, 'Kg/m^3') # Adding unit to the density
+
```
### Comparison Operators
-In programming we compare values, we use comparison operators to compare two values. We check if a value is greater or less or equal to other value. The following table shows python comparison operators which was taken from [w3shool](https://www.w3schools.com/python/python_operators.asp).
+In programming we compare values, we use comparison operators to compare two values. We check if a value is greater or less or equal to other value. The following table shows Python comparison operators which was taken from [w3shool](https://www.w3schools.com/python/python_operators.asp).

**Example: Comparison Operators**
@@ -202,23 +207,20 @@ print(len('python') > len('dragon')) # False
print('True == True: ', True == True)
print('True == False: ', True == False)
print('False == False:', False == False)
-print('True and True: ', True and True)
-print('True or False:', True or False)
-
```
-In addition to the above comparison operator python uses:
+In addition to the above comparison operator Python uses:
- _is_: Returns true if both variables are the same object(x is y)
- _is not_: Returns true if both variables are not the same object(x is not y)
- _in_: Returns True if the queried list contains a certain item(x in y)
-- _not in_: Returns True if the queried list doesn't have a certain item(x in y)
+- _not in_: Returns True if the queried list doesn't have a certain item(x not in y)
```py
print('1 is 1', 1 is 1) # True - because the data values are the same
print('1 is not 2', 1 is not 2) # True - because 1 is not 2
print('A in Asabeneh', 'A' in 'Asabeneh') # True - A found in the string
-print('B in Asabeneh', 'B' in 'Asabeneh') # False - there is no uppercase B
+print('B not in Asabeneh', 'B' in 'Asabeneh') # False - there is no uppercase B
print('coding' in 'coding for all') # True - because coding for all has the word coding
print('a in an:', 'a' in 'an') # True
print('4 is 2 ** 2:', 4 is 2 ** 2) # True
@@ -234,23 +236,26 @@ Unlike other programming languages python uses keywords _and_, _or_ and _not_ fo
print(3 > 2 and 4 > 3) # True - because both statements are true
print(3 > 2 and 4 < 3) # False - because the second statement is false
print(3 < 2 and 4 < 3) # False - because both statements are false
+print('True and True: ', True and True)
print(3 > 2 or 4 > 3) # True - because both statements are true
print(3 > 2 or 4 < 3) # True - because one of the statements is true
print(3 < 2 or 4 < 3) # False - because both statements are false
+print('True or False:', True or False)
print(not 3 > 2) # False - because 3 > 2 is true, then not True gives False
print(not True) # False - Negation, the not operator turns true to false
print(not False) # True
print(not not True) # True
print(not not False) # False
+
```
-🌕 You have boundless energy. You have just completed day 3 challenges and you are three steps ahead on your way to greatness. Now do some exercises for your brain and for your muscle.
+🌕 You have boundless energy. You have just completed day 3 challenges and you are three steps ahead on your way to greatness. Now do some exercises for your brain and your muscles.
## 💻 Exercises - Day 3
1. Declare your age as integer variable
2. Declare your height as a float variable
-3. Declare a complex number variable
+3. Declare a variable that store a complex number
4. Write a script that prompts the user to enter base and height of the triangle and calculate an area of this triangle (area = 0.5 x b x h).
```py
@@ -271,19 +276,19 @@ The perimeter of the triangle is 12
6. Get length and width of a rectangle using prompt. Calculate its area (area = length x width) and perimeter (perimeter = 2 x (length + width))
7. Get radius of a circle using prompt. Calculate the area (area = pi x r x r) and circumference (c = 2 x pi x r) where pi = 3.14.
8. Calculate the slope, x-intercept and y-intercept of y = 2x -2
-9. Slope is (m = y2-y1/x2-x1). Find the slope between point (2, 2) and point (6,10)
+9. Slope is (m = y2-y1/x2-x1). Find the slope and [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance#:~:text=In%20mathematics%2C%20the%20Euclidean%20distance,being%20called%20the%20Pythagorean%20distance.) between point (2, 2) and point (6,10)
10. Compare the slopes in tasks 8 and 9.
-11. Calculate the value of y (y = x^2 + 6x + 9). Try to use different x values and figure out at what x value y is 0.
-12. Find the length of 'python' and 'jargon' and make a falsy comparison statement.
-13. Use _and_ operator to check if 'on' is found in both 'python' and 'jargon'
+11. Calculate the value of y (y = x^2 + 6x + 9). Try to use different x values and figure out at what x value y is going to be 0.
+12. Find the length of 'python' and 'dragon' and make a falsy comparison statement.
+13. Use _and_ operator to check if 'on' is found in both 'python' and 'dragon'
14. _I hope this course is not full of jargon_. Use _in_ operator to check if _jargon_ is in the sentence.
15. There is no 'on' in both dragon and python
16. Find the length of the text _python_ and convert the value to float and convert it to string
17. Even numbers are divisible by 2 and the remainder is zero. How do you check if a number is even or not using python?
-18. The floor division of 7 by 3 is equal to the int converted value of 2.7.
-19. Check if type of '10' is equal to 10
+18. Check if the floor division of 7 by 3 is equal to the int converted value of 2.7.
+19. Check if type of '10' is equal to type of 10
20. Check if int('9.8') is equal to 10
-21. Writ a script that prompts the user to enter hours and rate per hour. Calculate pay of the person?
+21. Write a script that prompts the user to enter hours and rate per hour. Calculate pay of the person?
```py
Enter hours: 40
@@ -291,14 +296,14 @@ Enter rate per hour: 28
Your weekly earning is 1120
```
-22. Write a script that prompts the user to enter number of years. Calculate the number of seconds a person can live. Assume someone lives up to hundred years
+22. Write a script that prompts the user to enter number of years. Calculate the number of seconds a person can live. Assume a person can live hundred years
```py
Enter number of years you have lived: 100
You have lived for 3153600000 seconds.
```
-23. Write a python script that displays the following table
+23. Write a Python script that displays the following table
```py
1 1 1 1 1
@@ -310,4 +315,4 @@ You have lived for 3153600000 seconds.
🎉 CONGRATULATIONS ! 🎉
-[<< Day 2](../02_Day_Variables/02_variables.md) | [Day 4 >>](../04_Day_Strings/04_string.md)
+[<< Day 2](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) | [Day 4 >>](../04_Day_Strings/04_strings.md)
diff --git a/03_Day_Operators/day-3.py b/03_Day_Operators/day-3.py
index bacdf837c..cbf7e5a1d 100644
--- a/03_Day_Operators/day-3.py
+++ b/03_Day_Operators/day-3.py
@@ -4,12 +4,14 @@
print('Addition: ', 1 + 2)
print('Subtraction: ', 2 - 1)
print('Multiplication: ', 2 * 3)
-print ('Division: ', 4 / 2) # Division in python gives floating number
+# Division in python gives floating number
+print('Division: ', 4 / 2)
print('Division: ', 6 / 2)
print('Division: ', 7 / 2)
-print('Division without the remainder: ', 7 // 2) # gives without the floating number or without the remaining
+# gives without the floating number or without the remaining
+print('Division without the remainder: ', 7 // 2)
print('Modulus: ', 3 % 2) # Gives the remainder
-print ('Division without the remainder: ',7 // 3)
+print('Division without the remainder: ', 7 // 3)
print('Exponential: ', 3 ** 2) # it means 3 * 3
# Floating numbers
@@ -18,12 +20,12 @@
# Complex numbers
print('Complex number: ', 1+1j)
-print('Multiplying complex number: ',(1+1j) * (1-1j))
+print('Multiplying complex number: ', (1+1j) * (1-1j))
# Declaring the variable at the top first
-a = 3 # a is a variable name and 3 is an integer data type
-b = 2 # b is a variable name and 3 is an integer data type
+a = 3 # a is a variable name and 3 is an integer data type
+b = 2 # b is a variable name and 3 is an integer data type
# Arithmetic operations and assigning the result to a variable
total = a + b
@@ -35,7 +37,7 @@
exponential = a ** b
# I should have used sum instead of total but sum is a built-in function try to avoid overriding builtin functions
-print(total) # if you don't label your print with some string, you never know from where is the result is coming
+print(total) # if you don't label your print with some string, you never know from where is the result is coming
print('a + b = ', total)
print('a - b = ', diff)
print('a * b = ', product)
@@ -65,7 +67,8 @@
# Calculating area of a circle
radius = 10 # radius of a circle
-area_of_circle = 3.14 * radius ** 2 # two * sign means exponent or power
+# two * sign means exponent or power
+area_of_circle = 3.14 * radius ** 2
print('Area of a circle:', area_of_circle)
# Calculating area of a rectangle
@@ -102,18 +105,20 @@
print('True and True: ', True and True)
print('True or False:', True or False)
-# Another way comparison
-print('1 is 1', 1 is 1) # True - because the data values are the same
+# Another way comparison
+# True - because the data values are the same
+print('1 is 1', 1 is 1)
print('1 is not 2', 1 is not 2) # True - because 1 is not 2
-print('A in Asabeneh', 'A' in 'Asabeneh') # True - A found in the string
-print('B in Asabeneh', 'B' in 'Asabeneh') # False -there is no uppercase B
-print('coding' in 'coding for all') # True - because coding for all has the word coding
+print('A in Asabeneh', 'A' in 'Asabeneh') # True - A found in the string
+print('B in Asabeneh', 'B' in 'Asabeneh') # False -there is no uppercase B
+# True - because coding for all has the word coding
+print('coding' in 'coding for all')
print('a in an:', 'a' in 'an') # True
-print('4 is 2 ** 2:', 4 is 2 **2) # True
+print('4 is 2 ** 2:', 4 is 2 ** 2) # True
-print(3 > 2 and 4 > 3) # True - because both statements are true
-print(3 > 2 and 4 < 3) # False - because the second statement is false
-print(3 < 2 and 4 < 3) # False - because both statements are false
+print(3 > 2 and 4 > 3) # True - because both statements are true
+print(3 > 2 and 4 < 3) # False - because the second statement is false
+print(3 < 2 and 4 < 3) # False - because both statements are false
print(3 > 2 or 4 > 3) # True - because both statements are true
print(3 > 2 or 4 < 3) # True - because one of the statement is true
print(3 < 2 or 4 < 3) # False - because both statements are false
@@ -121,4 +126,4 @@
print(not True) # False - Negation, the not operator turns true to false
print(not False) # True
print(not not True) # True
-print(not not False) # False
\ No newline at end of file
+print(not not False) # False
diff --git a/04_Day_Strings/04_string.md b/04_Day_Strings/04_strings.md
similarity index 64%
rename from 04_Day_Strings/04_string.md
rename to 04_Day_Strings/04_strings.md
index bc997eab4..9d09d2cfe 100644
--- a/04_Day_Strings/04_string.md
+++ b/04_Day_Strings/04_strings.md
@@ -1,4 +1,3 @@
-
30 Days Of Python: Day 4 - Strings
-
Author:
- Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
-
-
+Author:
+Asabeneh Yetayeh
+ Second Edition: July, 2021
+
+
-[<< Day 3](../03_Day_Operators/03_operators.md) | [Day 5 >>](../05_Day_Lists/05_list.md)
+[<< Day 3](../03_Day_Operators/03_operators.md) | [Day 5 >>](../05_Day_Lists/05_lists.md)

+
- [Day 4](#day-4)
- - [String](#string)
+ - [Strings](#strings)
- [Creating a String](#creating-a-string)
- [String Concatenation](#string-concatenation)
- [Escape Sequences in Strings](#escape-sequences-in-strings)
- - [String Formating](#string-formating)
- - [Old Style String Formating (% Operator)](#old-style-string-formating--operator)
- - [New Style String Formating (str.format)](#new-style-string-formating-strformat)
+ - [String formatting](#string-formatting)
+ - [Old Style String Formatting (% Operator)](#old-style-string-formatting--operator)
+ - [New Style String Formatting (str.format)](#new-style-string-formatting-strformat)
- [String Interpolation / f-Strings (Python 3.6+)](#string-interpolation--f-strings-python-36)
- [Python Strings as Sequences of Characters](#python-strings-as-sequences-of-characters)
- [Unpacking Characters](#unpacking-characters)
@@ -34,12 +34,13 @@
- [Reversing a String](#reversing-a-string)
- [Skipping Characters While Slicing](#skipping-characters-while-slicing)
- [String Methods](#string-methods)
- - [💻 Exercises - Day 4](#%f0%9f%92%bb-exercises---day-4)
+ - [💻 Exercises - Day 4](#-exercises---day-4)
+
# Day 4
-## String
+## Strings
-Text is a string data type. Any data type written as text is a string. Any data under single or double quote are strings. There are different string methods and built-in functions to deal with string data types. To check the length of a string use the len() method.
+Text is a string data type. Any data type written as text is a string. Any data under single, double or triple quote are strings. There are different string methods and built-in functions to deal with string data types. To check the length of a string use the len() method.
### Creating a String
@@ -47,20 +48,21 @@ Text is a string data type. Any data type written as text is a string. Any data
letter = 'P' # A string could be a single character or a bunch of texts
print(letter) # P
print(len(letter)) # 1
-greeting = 'Hello, World!' # String could be a single or double quote,"Hello, World!"
+greeting = 'Hello, World!' # String could be made using a single or double quote,"Hello, World!"
print(greeting) # Hello, World!
print(len(greeting)) # 13
sentence = "I hope you are enjoying 30 days of Python Challenge"
print(sentence)
```
-Multiline string is created by using triple single (''') or double quotes ("""). See the example below.
+Multiline string is created by using triple single (''') or triple double quotes ("""). See the example below.
```py
multiline_string = '''I am a teacher and enjoy teaching.
I didn't find anything as rewarding as empowering people.
That is why I created 30 days of python.'''
print(multiline_string)
+
# Another way of doing the same thing
multiline_string = """I am a teacher and enjoy teaching.
I didn't find anything as rewarding as empowering people.
@@ -71,44 +73,46 @@ print(multiline_string)
### String Concatenation
We can connect strings together. Merging or connecting strings is called concatenation. See the example below:
-
+
```py
first_name = 'Asabeneh'
last_name = 'Yetayeh'
space = ' '
full_name = first_name + space + last_name
print(full_name) # Asabeneh Yetayeh
-# Checking length of a string using len() built-in function
+# Checking the length of a string using len() built-in function
print(len(first_name)) # 8
print(len(last_name)) # 7
print(len(first_name) > len(last_name)) # True
-print(len(full_name)) # 15
+print(len(full_name)) # 16
```
### Escape Sequences in Strings
-In python and other programming languages \ followed by a character. Let's see the most common escape characters:
+In Python and other programming languages \ followed by a character is an escape sequence. Let us see the most common escape characters:
+
+- \n: new line
+- \t: Tab means(8 spaces)
+- \\\\: Back slash
+- \\': Single quote (')
+- \\": Double quote (")
-* \n: new line
-* \t: Tab means(8 spaces)
-* \\\\: Back slash
-* \\': Single quote (')
-* \\": Double quote (")
+Now, let us see the use of the above escape sequences with examples.
```py
print('I hope everyone is enjoying the Python Challenge.\nAre you ?') # line break
-print('Days\tTopics\tExercises')
-print('Day 1\t3\t5')
-print('Day 2\t3\t5')
-print('Day 3\t3\t5')
-print('Day 4\t3\t5')
+print('Days\tTopics\tExercises') # adding tab space or 4 spaces
+print('Day 1\t5\t5')
+print('Day 2\t6\t20')
+print('Day 3\t5\t23')
+print('Day 4\t1\t35')
print('This is a backslash symbol (\\)') # To write a backslash
-print('In every programming language it starts with \"Hello, World!\"')
+print('In every programming language it starts with \"Hello, World!\"') # to write a double quote inside a single quote
# output
I hope every one is enjoying the Python Challenge.
Are you ?
-Days Topics Exercises
+Days Topics Exercises
Day 1 5 5
Day 2 6 20
Day 3 5 23
@@ -117,17 +121,17 @@ This is a backslash symbol (\)
In every programming language it starts with "Hello, World!"
```
-### String formating
+### String formatting
-#### Old Style String Formating (% Operator)
+#### Old Style String Formatting (% Operator)
-In python there are many ways of formating strings. In this section we will cover some of them.
-The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s", "%d", "%f", "%.f".
+In Python there are many ways of formatting strings. In this section, we will cover some of them.
+The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s", "%d", "%f", "%.number of digitsf".
-* %s - String (or any object with a string representation, like numbers)
-* %d - Integers
-* %f - Floating point numbers
-* %.f - Floating point numbers with fixed precision
+- %s - String (or any object with a string representation, like numbers)
+- %d - Integers
+- %f - Floating point numbers
+- "%.number of digitsf" - Floating point numbers with fixed precision
```py
# Strings only
@@ -143,12 +147,14 @@ pi = 3.14
area = pi * radius ** 2
formated_string = 'The area of circle with a radius %d is %.2f.' %(radius, area) # 2 refers the 2 significant digits after the point
-python_libraries = ['Django', 'Flask', 'Numpy', 'Pandas']
-formated_string = 'The following are python libraries:' % python_libraries
-print(formated_string) # "The following are python libraries:['Django', 'Flask', 'Numpy', 'Pandas']"
+python_libraries = ['Django', 'Flask', 'NumPy', 'Matplotlib','Pandas']
+formated_string = 'The following are python libraries:%s' % (python_libraries)
+print(formated_string) # "The following are python libraries:['Django', 'Flask', 'NumPy', 'Matplotlib','Pandas']"
```
-#### New Style String Formating (str.format)
-This formating is introduced in python version 3.
+
+#### New Style String Formatting (str.format)
+
+This format was introduced in Python version 3.
```py
@@ -181,42 +187,50 @@ print('{} ** {} = {}'.format(a, b, a ** b))
radius = 10
pi = 3.14
area = pi * radius ** 2
-formated_string = 'The area of a cricle with a radius {} is {:.2f}.'.format(radius, area) # 2 digits after decimal
+formated_string = 'The area of a circle with a radius {} is {:.2f}.'.format(radius, area) # 2 digits after decimal
print(formated_string)
```
-#### String Interpolation / f-Strings (Python 3.6+)
-Another new string formating is string interpolation, f-strings. Strings start with f and we can inject the data in their corresponding positions.
+
+#### String Interpolation / f-Strings (Python 3.6+)
+
+Another new string formatting is string interpolation, f-strings. Strings start with f and we can inject the data in their corresponding positions.
+
```py
a = 4
b = 3
print(f'{a} + {b} = {a +b}')
print(f'{a} - {b} = {a - b}')
print(f'{a} * {b} = {a * b}')
-print(f'{a} / {b} = {a / b:.2f}')
+print(f'{a} / {b} = {a / b:.2f}')
print(f'{a} % {b} = {a % b}')
print(f'{a} // {b} = {a // b}')
print(f'{a} ** {b} = {a ** b}')
```
### Python Strings as Sequences of Characters
-Python strings are sequences of characters, and share their basic methods of access with other Python ordered sequences of objects – lists and tuples. The simplest way of extracting single characters from strings (and individual members from any sequence) is to unpack them into corresponding variables.
-#### Unpacking Characters
+
+Python strings are sequences of characters, and share their basic methods of access with other Python ordered sequences of objects – lists and tuples. The simplest way of extracting single characters from strings (and individual members from any sequence) is to unpack them into corresponding variables.
+
+#### Unpacking Characters
+
```
language = 'Python'
a,b,c,d,e,f = language # unpacking sequence characters into variables
print(a) # P
print(b) # y
-print(c) # t
+print(c) # t
print(d) # h
print(e) # o
print(f) # n
```
+
#### Accessing Characters in Strings by Index
- In programming counting starts from zero. Therefore the first letter of a string is at zero index and the last letter of a string is the length of a string minus one.
- 
-
+In programming counting starts from zero. Therefore the first letter of a string is at zero index and the last letter of a string is the length of a string minus one.
+
+
+
```py
language = 'Python'
first_letter = language[0]
@@ -227,14 +241,16 @@ last_index = len(language) - 1
last_letter = language[last_index]
print(last_letter) # n
```
+
If we want to start from right end we can use negative indexing. -1 is the last index.
+
```py
language = 'Python'
last_letter = language[-1]
print(last_letter) # n
second_last = language[-2]
print(second_last) # o
- ```
+```
#### Slicing Python Strings
@@ -243,6 +259,7 @@ In python we can slice strings into substrings.
```py
language = 'Python'
first_three = language[0:3] # starts at zero index and up to 3 but not include 3
+print(first_three) #Pyt
last_three = language[3:6]
print(last_three) # hon
# Another way
@@ -262,61 +279,78 @@ print(greeting[::-1]) # !dlroW ,olleH
```
#### Skipping Characters While Slicing
+
It is possible to skip characters while slicing by passing step argument to slice method.
+
```py
language = 'Python'
-pto = language[0,6:2] #
+pto = language[0:6:2] #
print(pto) # Pto
```
### String Methods
+
There are many string methods which allow us to format strings. See some of the string methods in the following example:
-* capitalize(): Converts the first character of the string to capital Letter
+- capitalize(): Converts the first character of the string to capital letter
+
```py
challenge = 'thirty days of python'
print(challenge.capitalize()) # 'Thirty days of python'
```
-* count(): returns occurrences of substring in string, count(substring, start=.., end=..)
+
+- count(): returns occurrences of substring in string, count(substring, start=.., end=..). The start is a starting indexing for counting and end is the last index to count.
+
```py
challenge = 'thirty days of python'
print(challenge.count('y')) # 3
-print(challenge.count('y', 7, 14)) # 1
+print(challenge.count('y', 7, 14)) # 1,
print(challenge.count('th')) # 2`
```
-* endswith(): Checks if a string ends with a specified ending
+
+- endswith(): Checks if a string ends with a specified ending
+
```py
challenge = 'thirty days of python'
print(challenge.endswith('on')) # True
print(challenge.endswith('tion')) # False
```
-* expandtabs(): Replaces tab character with spaces, default tab size is 8. It takes tab size argument
+
+- expandtabs(): Replaces tab character with spaces, default tab size is 8. It takes tab size argument
+
```py
challenge = 'thirty\tdays\tof\tpython'
print(challenge.expandtabs()) # 'thirty days of python'
print(challenge.expandtabs(10)) # 'thirty days of python'
```
-* find(): Returns the lowest index of the first occurrence of a substring, if not found returns -1
+
+- find(): Returns the index of the first occurrence of a substring, if not found returns -1
+
```py
challenge = 'thirty days of python'
print(challenge.find('y')) # 5
print(challenge.find('th')) # 0
```
-* rfind(): Returns the highest index of the first occurrence of a substring, if not found returns -1
+
+- rfind(): Returns the index of the last occurrence of a substring, if not found returns -1
+
```py
challenge = 'thirty days of python'
-print(challenge.find('y')) # 5
-print(challenge.find('th')) # 1
+print(challenge.rfind('y')) # 16
+print(challenge.rfind('th')) # 17
```
-* format(): formats string into a nicer output
- More about string formating check this [link](https://www.programiz.com/python-programming/methods/string/format)
+
+- format(): formats string into a nicer output
+ More about string formatting check this [link](https://www.programiz.com/python-programming/methods/string/format)
+
```py
first_name = 'Asabeneh'
last_name = 'Yetayeh'
+age = 250
job = 'teacher'
country = 'Finland'
-sentence = 'I am {} {}. I am a {}. I live in {}.'.format(first_name, last_name, job, country)
-print(sentence) # I am Asabeneh Yetayeh. I am a teacher. I live in Finland.
+sentence = 'I am {} {}. I am a {}. I am {} years old. I live in {}.'.format(first_name, last_name, job, age, country)
+print(sentence) # I am Asabeneh Yetayeh. I am 250 years old. I am a teacher. I live in Finland.
radius = 10
pi = 3.14
@@ -324,21 +358,28 @@ area = pi * radius ** 2
result = 'The area of a circle with radius {} is {}'.format(str(radius), str(area))
print(result) # The area of a circle with radius 10 is 314
```
-* index(): Returns the lowest index of a substring, additional arguments indicate starting and ending index (default 0 and string length - 1)
+
+- index(): Returns the lowest index of a substring, additional arguments indicate starting and ending index (default 0 and string length - 1). If the substring is not found it raises a valueError.
+
```py
challenge = 'thirty days of python'
sub_string = 'da'
print(challenge.index(sub_string)) # 7
print(challenge.index(sub_string, 9)) # error
```
-* rindex(): Returns the highest index of a substring, additional arguments indicate starting and ending index (default 0 and string length - 1)
+
+- rindex(): Returns the highest index of a substring, additional arguments indicate starting and ending index (default 0 and string length - 1)
+
```py
challenge = 'thirty days of python'
sub_string = 'da'
-print(challenge.index(sub_string)) # 8
-print(challenge.index(sub_string, 9)) # error
+print(challenge.rindex(sub_string)) # 7
+print(challenge.rindex(sub_string, 9)) # error
+print(challenge.rindex('on', 8)) # 19
```
-* isalnum(): Checks alphanumeric character
+
+- isalnum(): Checks alphanumeric character
+
```py
challenge = 'ThirtyDaysPython'
print(challenge.isalnum()) # True
@@ -352,7 +393,9 @@ print(challenge.isalnum()) # False, space is not an alphanumeric character
challenge = 'thirty days of python 2019'
print(challenge.isalnum()) # False
```
-* isalpha(): Checks if all string elements are alphabet characters (a-z and A-Z)
+
+- isalpha(): Checks if all string elements are alphabet characters (a-z and A-Z)
+
```py
challenge = 'thirty days of python'
print(challenge.isalpha()) # False, space is once again excluded
@@ -361,18 +404,22 @@ print(challenge.isalpha()) # True
num = '123'
print(num.isalpha()) # False
```
-* isdecimal(): Checks if all characters in a string are decimal (0-9)
+
+- isdecimal(): Checks if all characters in a string are decimal (0-9)
+
```py
challenge = 'thirty days of python'
print(challenge.isdecimal()) # False
challenge = '123'
print(challenge.isdecimal()) # True
challenge = '\u00B2'
-print(challenge.isdigit()) # False
+print(challenge.isdigit()) # True
challenge = '12 3'
-print(challenge.isdecimal()) # False, no space allowed
+print(challenge.isdecimal()) # False, space not allowed
```
-* isdigit(): Checks if all characters in a string are numbers (0-9 and some other unicode characters for numbers)
+
+- isdigit(): Checks if all characters in a string are numbers (0-9 and some other unicode characters for numbers)
+
```py
challenge = 'Thirty'
print(challenge.isdigit()) # False
@@ -381,7 +428,9 @@ print(challenge.isdigit()) # True
challenge = '\u00B2'
print(challenge.isdigit()) # True
```
-* isnumeric(): Checks if all characters in a string are numbers or number related (just like isdigit(), just accepts more symbols, like ½)
+
+- isnumeric(): Checks if all characters in a string are numbers or number related (just like isdigit(), just accepts more symbols, like ½)
+
```py
num = '10'
print(num.isnumeric()) # True
@@ -391,7 +440,8 @@ num = '10.5'
print(num.isnumeric()) # False
```
-* isidentifier(): Checks for a valid identifier - means it checks, if a string is a valid variable name
+- isidentifier(): Checks for a valid identifier - it checks if a string is a valid variable name
+
```py
challenge = '30DaysOfPython'
print(challenge.isidentifier()) # False, because it starts with a number
@@ -399,14 +449,17 @@ challenge = 'thirty_days_of_python'
print(challenge.isidentifier()) # True
```
-* islower(): Checks if all alphabet characters in the string are lowercase
+- islower(): Checks if all alphabet characters in the string are lowercase
+
```py
challenge = 'thirty days of python'
print(challenge.islower()) # True
challenge = 'Thirty days of python'
print(challenge.islower()) # False
```
-* isupper(): Checks if all alphabet characters in the string are uppercase
+
+- isupper(): Checks if all alphabet characters in the string are uppercase
+
```py
challenge = 'thirty days of python'
print(challenge.isupper()) # False
@@ -414,42 +467,61 @@ challenge = 'THIRTY DAYS OF PYTHON'
print(challenge.isupper()) # True
```
-* join(): Returns a concatenated string
+- join(): Returns a concatenated string
+
+```py
+web_tech = ['HTML', 'CSS', 'JavaScript', 'React']
+result = ' '.join(web_tech)
+print(result) # 'HTML CSS JavaScript React'
+```
+
```py
web_tech = ['HTML', 'CSS', 'JavaScript', 'React']
result = '# '.join(web_tech)
print(result) # 'HTML# CSS# JavaScript# React'
```
-* strip(): Removes all given characters starting from the beggining and end of the string
+
+- strip(): Removes all given characters starting from the beginning and end of the string
+
```py
challenge = 'thirty days of pythoonnn'
print(challenge.strip('noth')) # 'irty days of py'
```
-* replace(): Replaces substring with a given string
+
+- replace(): Replaces substring with a given string
+
```py
challenge = 'thirty days of python'
print(challenge.replace('python', 'coding')) # 'thirty days of coding'
```
-* split(): Splits the string, using given string as a separator
+
+- split(): Splits the string, using given string or space as a separator
+
```py
challenge = 'thirty days of python'
print(challenge.split()) # ['thirty', 'days', 'of', 'python']
challenge = 'thirty, days, of, python'
print(challenge.split(', ')) # ['thirty', 'days', 'of', 'python']
```
-* title(): Returns a title cased string
+
+- title(): Returns a title cased string
+
```py
challenge = 'thirty days of python'
print(challenge.title()) # Thirty Days Of Python
```
-* swapcase(): Converts all uppercase characters to lowercase and all lowercase characters to uppercase characters
+
+- swapcase(): Converts all uppercase characters to lowercase and all lowercase characters to uppercase characters
+
```py
challenge = 'thirty days of python'
print(challenge.swapcase()) # THIRTY DAYS OF PYTHON
challenge = 'Thirty Days Of Python'
print(challenge.swapcase()) # tHIRTY dAYS oF pYTHON
```
-* startswith(): Checks if String Starts with the Specified String
+
+- startswith(): Checks if String Starts with the Specified String
+
```py
challenge = 'thirty days of python'
print(challenge.startswith('thirty')) # True
@@ -458,23 +530,26 @@ challenge = '30 days of python'
print(challenge.startswith('thirty')) # False
```
+🌕 You are an extraordinary person and you have a remarkable potential. You have just completed day 4 challenges and you are four steps a head in to your way to greatness. Now do some exercises for your brain and muscles.
+
## 💻 Exercises - Day 4
+
1. Concatenate the string 'Thirty', 'Days', 'Of', 'Python' to a single string, 'Thirty Days Of Python'.
2. Concatenate the string 'Coding', 'For' , 'All' to a single string, 'Coding For All'.
3. Declare a variable named company and assign it to an initial value "Coding For All".
-4. Print the variable company using *print()*.
-5. Print the length of the company string using *len()* method and *print()*.
-6. Change all the characters to capital letters using *upper()* method.
-7. Change all the characters to lowercase letters using *lower()* method.
-8. Use capitalize(), title(), swapcase() methods to format the value of the string *Coding For All*.
-9. Cut(slice) out the first word of *Coding For All* string.
-10. Check if *Coding For All* string contains a word Coding using the method index, find or other methods.
+4. Print the variable company using _print()_.
+5. Print the length of the company string using _len()_ method and _print()_.
+6. Change all the characters to uppercase letters using _upper()_ method.
+7. Change all the characters to lowercase letters using _lower()_ method.
+8. Use capitalize(), title(), swapcase() methods to format the value of the string _Coding For All_.
+9. Cut(slice) out the first word of _Coding For All_ string.
+10. Check if _Coding For All_ string contains a word Coding using the method index, find or other methods.
11. Replace the word coding in the string 'Coding For All' to Python.
-12. Change Python for Everyone to Python for All using the replace method or other methods.
+12. Change "Python for Everyone" to "Python for All" using the replace method or other methods.
13. Split the string 'Coding For All' using space as the separator (split()) .
14. "Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon" split the string at the comma.
-15. What is the character at index 0 in the string *Coding For All*.
-16. What is the last index of the string *Coding For All*.
+15. What is the character at index 0 in the string _Coding For All_.
+16. What is the last index of the string _Coding For All_.
17. What character is at index 10 in "Coding For All" string.
18. Create an acronym or an abbreviation for the name 'Python For Everyone'.
19. Create an acronym or an abbreviation for the name 'Coding For All'.
@@ -486,13 +561,13 @@ print(challenge.startswith('thirty')) # False
25. Slice out the phrase 'because because because' in the following sentence: 'You cannot end a sentence with because because because is a conjunction'
26. Find the position of the first occurrence of the word 'because' in the following sentence: 'You cannot end a sentence with because because because is a conjunction'
27. Slice out the phrase 'because because because' in the following sentence: 'You cannot end a sentence with because because because is a conjunction'
-28. Does '\'Coding For All' start with a substring *Coding*?
-29. Does 'Coding For All' end with a substring *coding*?
-30. ' Coding For All ' , remove the left and right trailing spaces in the given string.
+28. Does 'Coding For All' start with a substring _Coding_?
+29. Does 'Coding For All' end with a substring _coding_?
+30. ' Coding For All ' , remove the left and right trailing spaces in the given string.
31. Which one of the following variables return True when we use the method isidentifier():
- * 30DaysOfPython
- * thirty_days_of_python
-32. The following list contains the names of some of python libraries: ['Django', 'Flask', 'Bottle', 'Pyramid', 'Falcon']. Join the list with a hash with space string.
+ - 30DaysOfPython
+ - thirty_days_of_python
+32. The following list contains the names of some of python libraries: ['Django', 'Flask', 'Bottle', 'Pyramid', 'Falcon']. Join the list with a hash with space string.
33. Use the new line escape sequence to separate the following sentences.
```py
I am enjoying this challenge.
@@ -500,16 +575,19 @@ print(challenge.startswith('thirty')) # False
```
34. Use a tab escape sequence to write the following lines.
```py
- Name Age Country
- Asabeneh 250 Finland
+ Name Age Country City
+ Asabeneh 250 Finland Helsinki
```
-35. Use the string formating method to display the following:
+35. Use the string formatting method to display the following:
+
```sh
radius = 10
area = 3.14 * radius ** 2
-The area of a cricle with radius 10 is 314 meters square.
+The area of a circle with radius 10 is 314 meters square.
```
-36. Make the following using string formating methods:
+
+36. Make the following using string formatting methods:
+
```sh
8 + 6 = 14
8 - 6 = 2
@@ -522,4 +600,6 @@ The area of a cricle with radius 10 is 314 meters square.
🎉 CONGRATULATIONS ! 🎉
-[<< Day 3](../03_Day_Operators/03_operators.md) | [Day 5 >>](../05_Day_Lists/05_list.md)
\ No newline at end of file
+[<< Day 3](../03_Day_Operators/03_operators.md) | [Day 5 >>](../05_Day_Lists/05_lists.md)
+
+
diff --git a/04_Day_Strings/day_4.py b/04_Day_Strings/day_4.py
index e3bfeccef..54e59464b 100644
--- a/04_Day_Strings/day_4.py
+++ b/04_Day_Strings/day_4.py
@@ -24,47 +24,48 @@
first_name = 'Asabeneh'
last_name = 'Yetayeh'
space = ' '
-full_name = first_name + space + last_name
-print(full_name) # Asabeneh Yetayeh
+full_name = first_name + space + last_name
+print(full_name) # Asabeneh Yetayeh
# Checking length of a string using len() builtin function
print(len(first_name)) # 8
print(len(last_name)) # 7
-print(len(first_name) > len(last_name)) # True
-print(len(full_name)) # 15
+print(len(first_name) > len(last_name)) # True
+print(len(full_name)) # 15
-#### Unpacking characters
+# Unpacking characters
language = 'Python'
-a,b,c,d,e,f = language # unpacking sequence characters into variables
-print(a) # P
-print(b) # y
-print(c) # t
-print(d) # h
-print(e) # o
-print(f) # n
+a, b, c, d, e, f = language # unpacking sequence characters into variables
+print(a) # P
+print(b) # y
+print(c) # t
+print(d) # h
+print(e) # o
+print(f) # n
# Accessing characters in strings by index
language = 'Python'
first_letter = language[0]
-print(first_letter) # P
+print(first_letter) # P
second_letter = language[1]
-print(second_letter) # y
+print(second_letter) # y
last_index = len(language) - 1
last_letter = language[last_index]
-print(last_letter) # n
+print(last_letter) # n
# If we want to start from right end we can use negative indexing. -1 is the last index
language = 'Python'
last_letter = language[-1]
-print(last_letter) # n
+print(last_letter) # n
second_last = language[-2]
-print(second_last) # o
+print(second_last) # o
# Slicing
language = 'Python'
-first_three = language[0:3] # starts at zero index and up to 3 but not include 3
+# starts at zero index and up to 3 but not include 3
+first_three = language[0:3]
last_three = language[3:6]
-print(last_three) # hon
+print(last_three) # hon
# Another way
last_three = language[-3:]
print(last_three) # hon
@@ -73,87 +74,88 @@
# Skipping character while splitting Python strings
language = 'Python'
-pto = language[0,6:2] #
-print(pto) # pto
+pto = language[0:6:2]
+print(pto) # pto
# Escape sequence
-print('I hope every one enjoying the python challenge.\nDo you ?') # line break
+print('I hope every one enjoying the python challenge.\nDo you ?') # line break
print('Days\tTopics\tExercises')
print('Day 1\t3\t5')
print('Day 2\t3\t5')
print('Day 3\t3\t5')
print('Day 4\t3\t5')
-print('This is a back slash symbol (\\)') # To write a back slash
+print('This is a back slash symbol (\\)') # To write a back slash
print('In every programming language it starts with \"Hello, World!\"')
-## String Methods
+# String Methods
# capitalize(): Converts the first character the string to Capital Letter
challenge = 'thirty days of python'
-print(challenge.capitalize()) # 'Thirty days of python'
+print(challenge.capitalize()) # 'Thirty days of python'
# count(): returns occurrences of substring in string, count(substring, start=.., end=..)
challenge = 'thirty days of python'
-print(challenge.count('y')) # 3
-print(challenge.count('y', 7, 14)) # 1
-print(challenge.count('th')) # 2`
+print(challenge.count('y')) # 3
+print(challenge.count('y', 7, 14)) # 1
+print(challenge.count('th')) # 2`
# endswith(): Checks if a string ends with a specified ending
challenge = 'thirty days of python'
print(challenge.endswith('on')) # True
-print(challenge.endswith('tion')) # False
+print(challenge.endswith('tion')) # False
# expandtabs(): Replaces tab character with spaces, default tab size is 8. It takes tab size argument
challenge = 'thirty\tdays\tof\tpython'
print(challenge.expandtabs()) # 'thirty days of python'
-print(challenge.expandtabs(10)) # 'thirty days of python'
+print(challenge.expandtabs(10)) # 'thirty days of python'
# find(): Returns the index of first occurrence of substring
challenge = 'thirty days of python'
print(challenge.find('y')) # 5
-print(challenge.find('th')) # 0
+print(challenge.find('th')) # 0
-# format() formats string into nicer output
+# format() formats string into nicer output
first_name = 'Asabeneh'
last_name = 'Yetayeh'
job = 'teacher'
country = 'Finland'
-sentence = 'I am {} {}. I am a {}. I live in {}.'.format(first_name, last_name, job, country)
-print(sentence) # I am Asabeneh Yetayeh. I am a teacher. I live in Finland.
+sentence = 'I am {} {}. I am a {}. I live in {}.'.format(
+ first_name, last_name, job, country)
+print(sentence) # I am Asabeneh Yetayeh. I am a teacher. I live in Finland.
radius = 10
pi = 3.14
-area = pi # radius ## 2
+area = pi # radius ## 2
result = 'The area of circle with {} is {}'.format(str(radius), str(area))
-print(result) # The area of circle with 10 is 314.0
+print(result) # The area of circle with 10 is 314.0
# index(): Returns the index of substring
challenge = 'thirty days of python'
print(challenge.find('y')) # 5
-print(challenge.find('th')) # 0
+print(challenge.find('th')) # 0
# isalnum(): Checks alphanumeric character
challenge = 'ThirtyDaysPython'
-print(challenge.isalnum()) # True
+print(challenge.isalnum()) # True
challenge = '30DaysPython'
-print(challenge.isalnum()) # True
+print(challenge.isalnum()) # True
challenge = 'thirty days of python'
-print(challenge.isalnum()) # False
+print(challenge.isalnum()) # False
challenge = 'thirty days of python 2019'
-print(challenge.isalnum()) # False
+print(challenge.isalnum()) # False
# isalpha(): Checks if all characters are alphabets
challenge = 'thirty days of python'
-print(challenge.isalpha()) # True
+print(challenge.isalpha()) # True
num = '123'
print(num.isalpha()) # False
@@ -161,44 +163,44 @@
challenge = 'thirty days of python'
print(challenge.find('y')) # 5
-print(challenge.find('th')) # 0
+print(challenge.find('th')) # 0
# isdigit(): Checks Digit Characters
challenge = 'Thirty'
-print(challenge.isdigit()) # False
+print(challenge.isdigit()) # False
challenge = '30'
-print(challenge.digit()) # True
+print(challenge.isdigit()) # True
# isdecimal():Checks decimal characters
num = '10'
-print(num.isdecimal()) # True
+print(num.isdecimal()) # True
num = '10.5'
-print(num.isdecimal()) # False
+print(num.isdecimal()) # False
# isidentifier():Checks for valid identifier means it check if a string is a valid variable name
challenge = '30DaysOfPython'
-print(challenge.isidentifier()) # False, because it starts with a number
+print(challenge.isidentifier()) # False, because it starts with a number
challenge = 'thirty_days_of_python'
-print(challenge.isidentifier()) # True
+print(challenge.isidentifier()) # True
# islower():Checks if all alphabets in a string are lowercase
challenge = 'thirty days of python'
-print(challenge.islower()) # True
+print(challenge.islower()) # True
challenge = 'Thirty days of python'
-print(challenge.islower()) # False
+print(challenge.islower()) # False
# isupper(): returns if all characters are uppercase characters
challenge = 'thirty days of python'
-print(challenge.isupper()) # False
+print(challenge.isupper()) # False
challenge = 'THIRTY DAYS OF PYTHON'
-print(challenge.isupper()) # True
+print(challenge.isupper()) # True
# isnumeric():Checks numeric characters
@@ -211,30 +213,30 @@
web_tech = ['HTML', 'CSS', 'JavaScript', 'React']
result = '#, '.join(web_tech)
-print(result) # 'HTML# CSS# JavaScript# React'
+print(result) # 'HTML# CSS# JavaScript# React'
# strip(): Removes both leading and trailing characters
challenge = ' thirty days of python '
-print(challenge.strip('y')) # 5
+print(challenge.strip('y')) # 5
# replace(): Replaces substring inside
challenge = 'thirty days of python'
-print(challenge.replace('python', 'coding')) # 'thirty days of coding'
+print(challenge.replace('python', 'coding')) # 'thirty days of coding'
# split():Splits String from Left
challenge = 'thirty days of python'
-print(challenge.split()) # ['thirty', 'days', 'of', 'python']
+print(challenge.split()) # ['thirty', 'days', 'of', 'python']
# title(): Returns a Title Cased String
challenge = 'thirty days of python'
-print(challenge.title()) # Thirty Days Of Python
+print(challenge.title()) # Thirty Days Of Python
# swapcase(): Checks if String Starts with the Specified String
-
+
challenge = 'thirty days of python'
print(challenge.swapcase()) # THIRTY DAYS OF PYTHON
challenge = 'Thirty Days Of Python'
@@ -243,6 +245,6 @@
# startswith(): Checks if String Starts with the Specified String
challenge = 'thirty days of python'
-print(challenge.startswith('thirty')) # True
+print(challenge.startswith('thirty')) # True
challenge = '30 days of python'
-print(challenge.startswith('thirty')) # False
\ No newline at end of file
+print(challenge.startswith('thirty')) # False
diff --git a/05_Day_Lists/05_list.md b/05_Day_Lists/05_lists.md
similarity index 79%
rename from 05_Day_Lists/05_list.md
rename to 05_Day_Lists/05_lists.md
index b7d0e7498..a91c74d5f 100644
--- a/05_Day_Lists/05_list.md
+++ b/05_Day_Lists/05_lists.md
@@ -1,5 +1,5 @@
-
30 Days Of Python: Day 5 - List
+
30 Days Of Python: Day 5 - Lists
@@ -9,13 +9,12 @@
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+ Second Edition: July - 2021
-
-[<< Day 5](../04_Day_Strings/04_string.md) | [Day 6 >>](../06_Day_Tuples/06_tuple.md)
+[<< Day 4](../04_Day_Strings/04_strings.md) | [Day 6 >>](../06_Day_Tuples/06_tuples.md)

@@ -40,24 +39,26 @@
- [Finding Index of an Item](#finding-index-of-an-item)
- [Reversing a List](#reversing-a-list)
- [Sorting List Items](#sorting-list-items)
- - [💻 Exercises: Day 5](#%f0%9f%92%bb-exercises-day-5)
+ - [💻 Exercises: Day 5](#-exercises-day-5)
+ - [Exercises: Level 1](#exercises-level-1)
+ - [Exercises: Level 2](#exercises-level-2)
# Day 5
## Lists
-There are four collection data types in python :
+There are four collection data types in Python :
- List: is a collection which is ordered and changeable(modifiable). Allows duplicate members.
- Tuple: is a collection which is ordered and unchangeable or unmodifiable(immutable). Allows duplicate members.
-- Set: is a collection which is unordered, unindexed and unmodifiable, but you can add new items. No duplicate members.
+- Set: is a collection which is unordered, un-indexed and unmodifiable, but we can add new items to the set. Duplicate members are not allowed.
- Dictionary: is a collection which is unordered, changeable(modifiable) and indexed. No duplicate members.
-A list is collection of different data types which is ordered and modifiable(mutable). A list can be empty or it may have different data type items or items
+A list is collection of different data types which is ordered and modifiable(mutable). A list can be empty or it may have different data type items.
### How to Create a List
-In python we can create lists in two ways:
+In Python we can create lists in two ways:
- Using list built-in function
@@ -90,7 +91,7 @@ fruits = ['banana', 'orange', 'mango', 'lemon'] # list of fr
vegetables = ['Tomato', 'Potato', 'Cabbage','Onion', 'Carrot'] # list of vegetables
animal_products = ['milk', 'meat', 'butter', 'yoghurt'] # list of animal products
web_techs = ['HTML', 'CSS', 'JS', 'React','Redux', 'Node', 'MongDB'] # list of web technologies
-countries = ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway']
+countries = ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway']
# Print the lists and its length
print('Fruits:', fruits)
@@ -162,7 +163,7 @@ print(second_last) # mango
### Unpacking List Items
```py
-lst = ['item','item2','item3', 'item4', 'item5']
+lst = ['item1','item2','item3', 'item4', 'item5']
first_item, second_item, third_item, *rest = lst
print(first_item) # item1
print(second_item) # item2
@@ -174,7 +175,7 @@ print(rest) # ['item4', 'item5']
```py
# First Example
fruits = ['banana', 'orange', 'mango', 'lemon','lime','apple']
-first_fruit, second_fruit, third_fruit, *rest = lst
+first_fruit, second_fruit, third_fruit, *rest = fruits
print(first_fruit) # banana
print(second_fruit) # orange
print(third_fruit) # mango
@@ -189,7 +190,7 @@ print(tenth) # 10
# Third Example about unpacking list
countries = ['Germany', 'France','Belgium','Sweden','Denmark','Finland','Norway','Iceland','Estonia']
gr, fr, bg, sw, *scandic, es = countries
-print(gr)
+print(gr)
print(fr)
print(bg)
print(sw)
@@ -208,7 +209,7 @@ all_fruits = fruits[0:4] # it returns all the fruits
all_fruits = fruits[0:] # if we don't set where to stop it takes all the rest
orange_and_mango = fruits[1:3] # it does not include the first index
orange_mango_lemon = fruits[1:]
-orange_and_lemon = fruits[::2] # here we used a 3rd argument, step. It will take every 2cnd item - ['orange', 'lemon']
+orange_and_lemon = fruits[::2] # here we used a 3rd argument, step. It will take every 2cnd item - ['banana', 'mango']
```
- Negative Indexing: We can specify a range of negative indexes by specifying the start, end and step, the return value will be a new list.
@@ -216,9 +217,9 @@ orange_and_lemon = fruits[::2] # here we used a 3rd argument, step. It will take
```py
fruits = ['banana', 'orange', 'mango', 'lemon']
all_fruits = fruits[-4:] # it returns all the fruits
-orange_and_mango = fruits[-3:-1] # it does not include the last index
-orange_mango_lemon = fruits[-3:] # this will give the same result as the one above
-reverse_fruits = fruits[::-1] # a negative step will take the list in reverse order
+orange_and_mango = fruits[-3:-1] # it does not include the last index,['orange', 'mango']
+orange_mango_lemon = fruits[-3:] # this will give starting from -3 to the end,['orange', 'mango', 'lemon']
+reverse_fruits = fruits[::-1] # a negative step will take the list in reverse order,['lemon', 'mango', 'orange', 'banana']
```
### Modifying Lists
@@ -231,13 +232,15 @@ fruits[0] = 'avocado'
print(fruits) # ['avocado', 'orange', 'mango', 'lemon']
fruits[1] = 'apple'
print(fruits) # ['avocado', 'apple', 'mango', 'lemon']
-last_index = len(fruits)
+last_index = len(fruits) - 1
fruits[last_index] = 'lime'
print(fruits) # ['avocado', 'apple', 'mango', 'lime']
```
### Checking Items in a List
+Checking an item if it is a member of a list using *in* operator. See the example below.
+
```py
fruits = ['banana', 'orange', 'mango', 'lemon']
does_exist = 'banana' in fruits
@@ -248,7 +251,7 @@ print(does_exist) # False
### Adding Items to a List
-To add item to the end of an existing list we use the method
+To add item to the end of an existing list we use the method *append()*.
```py
# syntax
@@ -266,7 +269,7 @@ print(fruits)
### Inserting Items into a List
-Use insert() method to insert a single item at a specified index in a list. Note that other items are shifted to the right.
+We can use *insert()* method to insert a single item at a specified index in a list. Note that other items are shifted to the right. The *insert()* methods takes two arguments:index and an item to insert.
```py
# syntax
@@ -295,14 +298,14 @@ lst.remove(item)
```py
fruits = ['banana', 'orange', 'mango', 'lemon', 'banana']
fruits.remove('banana')
-print(fruits) # ['orange', 'mango', 'lemon', 'banana'] - this method removes the first occurence of the item in the list
+print(fruits) # ['orange', 'mango', 'lemon', 'banana'] - this method removes the first occurrence of the item in the list
fruits.remove('lemon')
print(fruits) # ['orange', 'mango', 'banana']
```
### Removing Items Using Pop
-The pop() method removes the specified index, (or the last item if index is not specified):
+The *pop()* method removes the specified index, (or the last item if index is not specified):
```py
# syntax
@@ -322,7 +325,7 @@ print(fruits) # ['orange', 'mango']
### Removing Items Using Del
-The del keyword removes the specified index and it can also be used to delete items within index range. It can also delete the list completely
+The *del* keyword removes the specified index and it can also be used to delete items within index range. It can also delete the list completely
```py
# syntax
@@ -345,7 +348,7 @@ print(fruits) # This should give: NameError: name 'fruits' is not defined
### Clearing List Items
-The clear() method empties the list:
+The *clear()* method empties the list:
```py
# syntax
@@ -361,7 +364,7 @@ print(fruits) # []
### Copying a List
-It is possible to copy a list by reassigning it to a new variable in the following way: list2 = list1. Now, list2 is a reference of list1, any changes we make in list2 will also modify the original, list2. But there are lots of case in which we do not like to modify the original instead we like to have a different copy. One of way avoid the problem above is using _copy()_.
+It is possible to copy a list by reassigning it to a new variable in the following way: list2 = list1. Now, list2 is a reference of list1, any changes we make in list2 will also modify the original, list1. But there are lots of case in which we do not like to modify the original instead we like to have a different copy. One of way of avoiding the problem above is using _copy()_.
```py
# syntax
@@ -391,57 +394,44 @@ positive_numbers = [1, 2, 3, 4, 5]
zero = [0]
negative_numbers = [-5,-4,-3,-2,-1]
integers = negative_numbers + zero + positive_numbers
-print(integers)
+print(integers) # [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
fruits = ['banana', 'orange', 'mango', 'lemon']
vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
fruits_and_vegetables = fruits + vegetables
-print(fruits_and_vegetables )
-
-```
-
-```py
-# output
-[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
-['banana', 'orange', 'mango', 'lemon', 'Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
+print(fruits_and_vegetables ) # ['banana', 'orange', 'mango', 'lemon', 'Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
```
- Joining using extend() method
+ The *extend()* method allows to append list in a list. See the example below.
```py
# syntax
list1 = ['item1', 'item2']
list2 = ['item3', 'item4', 'item5']
-list1.extend(list2)
+list1.extend(list2) # ['item1', 'item2', 'item3', 'item4', 'item5']
```
```py
num1 = [0, 1, 2, 3]
-num2= [4, 5,6]
+num2= [4, 5, 6]
num1.extend(num2)
-print('Numbers:', num1)
+print('Numbers:', num1) # Numbers: [0, 1, 2, 3, 4, 5, 6]
negative_numbers = [-5,-4,-3,-2,-1]
positive_numbers = [1, 2, 3,4,5]
zero = [0]
negative_numbers.extend(zero)
negative_numbers.extend(positive_numbers)
-print('Integers:', negative_numbers)
+print('Integers:', negative_numbers) # Integers: [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
fruits = ['banana', 'orange', 'mango', 'lemon']
vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
fruits.extend(vegetables)
-print('Fruits and vegetables:', fruits )
-
-```
-
-```py
-Numbers: [0, 1, 2, 3, 4, 5, 6]
-Integers: [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
-Fruits and vegetables: ['banana', 'orange', 'mango', 'lemon', 'Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
+print('Fruits and vegetables:', fruits ) # Fruits and vegetables: ['banana', 'orange', 'mango', 'lemon', 'Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
```
### Counting Items in a List
-The count() method returns the number of times an item appears in a list:
+The *count()* method returns the number of times an item appears in a list:
```py
# syntax
@@ -458,7 +448,7 @@ print(ages.count(24)) # 3
### Finding Index of an Item
-The index() method returns the index of an item in the list:
+The *index()* method returns the index of an item in the list:
```py
# syntax
@@ -475,7 +465,7 @@ print(ages.index(24)) # 2, the first occurrence
### Reversing a List
-The reverse() method reverses the order of a list.
+The *reverse()* method reverses the order of a list.
```py
# syntax
@@ -487,15 +477,10 @@ lst.reverse()
```py
fruits = ['banana', 'orange', 'mango', 'lemon']
fruits.reverse()
-print(fruits.reverse())
+print(fruits) # ['lemon', 'mango', 'orange', 'banana']
ages = [22, 19, 24, 25, 26, 24, 25, 24]
ages.reverse()
-print(ages.reverse())
-```
-
-```py
-['lemon', 'mango', 'orange', 'banana']
-[24, 25, 24, 26, 25, 24, 19, 22]
+print(ages) # [24, 25, 24, 26, 25, 24, 19, 22]
```
### Sorting List Items
@@ -516,37 +501,35 @@ To sort lists we can use _sort()_ method or _sorted()_ built-in functions. The _
```py
fruits = ['banana', 'orange', 'mango', 'lemon']
fruits.sort()
- print(fruits) # sorted in alphabetical order
+ print(fruits) # sorted in alphabetical order, ['banana', 'lemon', 'mango', 'orange']
fruits.sort(reverse=True)
- print(fruits)
+ print(fruits) # ['orange', 'mango', 'lemon', 'banana']
ages = [22, 19, 24, 25, 26, 24, 25, 24]
ages.sort()
- print(ages)
+ print(ages) # [19, 22, 24, 24, 24, 25, 25, 26]
+
ages.sort(reverse=True)
- print(ages)
- ```
-
- ```sh
- ['banana', 'lemon', 'mango', 'orange']
- ['orange', 'mango', 'lemon', 'banana']
- [19, 22, 24, 24, 24, 25, 25, 26]
- [26, 25, 25, 24, 24, 24, 22, 19]
+ print(ages) # [26, 25, 25, 24, 24, 24, 22, 19]
```
- sorted(): returns the ordered list without modifying the original
+ sorted(): returns the ordered list without modifying the original list
**Example:**
```py
fruits = ['banana', 'orange', 'mango', 'lemon']
- print(sorted(fruits)) # ['banana', 'lemon', 'mango', 'orange']
+ print(sorted(fruits)) # ['banana', 'lemon', 'mango', 'orange']
# Reverse order
fruits = ['banana', 'orange', 'mango', 'lemon']
fruits = sorted(fruits,reverse=True)
print(fruits) # ['orange', 'mango', 'lemon', 'banana']
```
+🌕 You are diligent and you have already achieved quite a lot. You have just completed day 5 challenges and you are 5 steps a head in to your way to greatness. Now do some exercises for your brain and muscles.
+
## 💻 Exercises: Day 5
+### Exercises: Level 1
+
1. Declare an empty list
2. Declare a list with more than 5 items
3. Find the length of your list
@@ -579,8 +562,11 @@ To sort lists we can use _sort()_ method or _sorted()_ built-in functions. The _
back_end = ['Node','Express', 'MongoDB']
```
-27. After joining the lists in question 26. Copy the joined list and assign it to a variable full_stack. Then insert Python and SQL after Redux.
-28. The following is a list of 10 students ages:
+27. After joining the lists in question 26. Copy the joined list and assign it to a variable full_stack, then insert Python and SQL after Redux.
+
+### Exercises: Level 2
+
+1. The following is a list of 10 students ages:
```sh
ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24]
@@ -593,10 +579,10 @@ ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24]
- Find the range of the ages (max minus min)
- Compare the value of (min - average) and (max - average), use _abs()_ method
-29. Find the middle country(ies) in the [countries list](https://github.com/Asabeneh/30-Days-Of-Python/tree/master/data/countries.py)
-30. Divide the countries list into two equal lists if it is even if not one more country for the first half.
-31. ['China', 'Russia', 'USA', 'Finland', 'Sweden', 'Norway', 'Denmark']. Unpack the first three countries and the rest as scandic countries.
+1. Find the middle country(ies) in the [countries list](https://github.com/Asabeneh/30-Days-Of-Python/tree/master/data/countries.py)
+1. Divide the countries list into two equal lists if it is even if not one more country for the first half.
+1. ['China', 'Russia', 'USA', 'Finland', 'Sweden', 'Norway', 'Denmark']. Unpack the first three countries and the rest as scandic countries.
🎉 CONGRATULATIONS ! 🎉
-[<< Day 5](../04_Day_Strings/04_string.md) | [Day 6 >>](../06_Day_Tuples/06_tuple.md)
+[<< Day 4](../04_Day_Strings/04_strings.md) | [Day 6 >>](../06_Day_Tuples/06_tuples.md)
diff --git a/05_Day_Lists/day_5.py b/05_Day_Lists/day_5.py
index 971b4e143..6b9c2a1f7 100644
--- a/05_Day_Lists/day_5.py
+++ b/05_Day_Lists/day_5.py
@@ -1,10 +1,14 @@
-empty_list = list() # this is an empty list, no item in the list
-print(len(empty_list)) # 0
+empty_list = list() # this is an empty list, no item in the list
+print(len(empty_list)) # 0
-fruits = ['banana', 'orange', 'mango', 'lemon'] # list of fruits
-vegetables = ['Tomato', 'Potato', 'Cabbage','Onion', 'Carrot'] # list of vegetables
-animal_products = ['milk', 'meat', 'butter', 'yoghurt'] # list of animal products
-web_techs = ['HTML', 'CSS', 'JS', 'React','Redux', 'Node', 'MongDB'] # list of web technologies
+# list of fruits
+fruits = ['banana', 'orange', 'mango', 'lemon']
+vegetables = ['Tomato', 'Potato', 'Cabbage',
+ 'Onion', 'Carrot'] # list of vegetables
+animal_products = ['milk', 'meat', 'butter',
+ 'yoghurt'] # list of animal products
+web_techs = ['HTML', 'CSS', 'JS', 'React', 'Redux',
+ 'Node', 'MongDB'] # list of web technologies
countries = ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway']
# Print the lists and it length
@@ -12,7 +16,7 @@
print('Number of fruits:', len(fruits))
print('Vegetables:', vegetables)
print('Number of vegetables:', len(vegetables))
-print('Animal products:',animal_products)
+print('Animal products:', animal_products)
print('Number of animal products:', len(animal_products))
print('Web technologies:', web_techs)
print('Number of web technologies:', len(web_techs))
@@ -20,47 +24,47 @@
# Modifying list
-fruits = ['banana', 'orange', 'mango', 'lemon']
-first_fruit = fruits[0] # we are accessing the first item using its index
+fruits = ['banana', 'orange', 'mango', 'lemon']
+first_fruit = fruits[0] # we are accessing the first item using its index
print(first_fruit) # banana
second_fruit = fruits[1]
print(second_fruit) # orange
last_fruit = fruits[3]
-print(last_fruit) # lemon
+print(last_fruit) # lemon
# Last index
last_index = len(fruits) - 1
last_fruit = fruits[last_index]
# Accessing itmes
-fruits = ['banana', 'orange', 'mango', 'lemon']
+fruits = ['banana', 'orange', 'mango', 'lemon']
last_fruit = fruits[-1]
second_last = fruits[-2]
print(last_fruit) # lemon
print(second_last) # mango
# Slicing items
-fruits = ['banana', 'orange', 'mango', 'lemon']
-all_fruits = fruits[0:4] # it returns all the fruits
+fruits = ['banana', 'orange', 'mango', 'lemon']
+all_fruits = fruits[0:4] # it returns all the fruits
# this is also give the same result as the above
-all_fruits = fruits[0:] # if we don't set where to stop it takes all the rest
-orange_and_mango = fruits[1:3] # it does not include the end index
+all_fruits = fruits[0:] # if we don't set where to stop it takes all the rest
+orange_and_mango = fruits[1:3] # it does not include the end index
orange_mango_lemon = fruits[1:]
-fruits = ['banana', 'orange', 'mango', 'lemon']
-all_fruits = fruits[-4:] # it returns all the fruits
+fruits = ['banana', 'orange', 'mango', 'lemon']
+all_fruits = fruits[-4:] # it returns all the fruits
# this is also give the same result as the above
-orange_and_mango = fruits[-3:-1] # it does not include the end index
+orange_and_mango = fruits[-3:-1] # it does not include the end index
orange_mango_lemon = fruits[-3:]
-fruits = ['banana', 'orange', 'mango', 'lemon']
-fruits[0] = 'Avocado'
-print(fruits) # ['avocado', 'orange', 'mango', 'lemon']
+fruits = ['banana', 'orange', 'mango', 'lemon']
+fruits[0] = 'Avocado'
+print(fruits) # ['avocado', 'orange', 'mango', 'lemon']
fruits[1] = 'apple'
-print(fruits) # ['avocado', 'apple', 'mango', 'lemon']
+print(fruits) # ['avocado', 'apple', 'mango', 'lemon']
last_index = len(fruits)
fruits[last_index] = 'lime'
-print(fruits) # ['avocado', 'apple', 'mango', 'lime']
+print(fruits) # ['avocado', 'apple', 'mango', 'lime']
# checking items
fruits = ['banana', 'orange', 'mango', 'lemon']
@@ -73,14 +77,16 @@
fruits = ['banana', 'orange', 'mango', 'lemon']
fruits.append('apple')
print(fruits) # ['banana', 'orange', 'mango', 'lemon', 'apple']
-fruits.append('lime') # ['banana', 'orange', 'mango', 'lemon', 'apple', 'lime]
+# ['banana', 'orange', 'mango', 'lemon', 'apple', 'lime]
+fruits.append('lime')
print(fruits)
# insert
fruits = ['banana', 'orange', 'mango', 'lemon']
-fruits.insert(2, 'apple') # insert apple between orange and mango
+fruits.insert(2, 'apple') # insert apple between orange and mango
print(fruits) # ['banana', 'orange', 'apple', 'mango', 'lemon']
-fruits.list(3, 'lime') # ['banana', 'orange', 'apple', 'mango', 'lime','lemon',]
+# ['banana', 'orange', 'apple', 'mango', 'lime','lemon',]
+fruits.list(3, 'lime')
print(fruits)
# remove
@@ -92,60 +98,60 @@
# pop
fruits = ['banana', 'orange', 'mango', 'lemon']
-fruits.remove()
+fruits.remove()
print(fruits) # ['banana', 'orange', 'mango']
-fruits.remove(0)
-print(fruits) # ['orange', 'mango']
+fruits.remove(0)
+print(fruits) # ['orange', 'mango']
-# del
+# del
fruits = ['banana', 'orange', 'mango', 'lemon']
-del fruits[0]
+del fruits[0]
print(fruits) # ['orange', 'mango', 'lemon']
-del fruits[1]
+del fruits[1]
print(fruits) # ['orange', 'lemon']
del fruits
print(fruits) # This should give: NameError: name 'fruits' is not defined
# clear
fruits = ['banana', 'orange', 'mango', 'lemon']
-fruits.clear()
+fruits.clear()
print(fruits) # []
# copying a lits
fruits = ['banana', 'orange', 'mango', 'lemon']
-fruits_copy = fruits.copy()
+fruits_copy = fruits.copy()
print(fruits_copy) # ['banana', 'orange', 'mango', 'lemon']
# join
-positive_numbers = [1, 2, 3,4,5]
+positive_numbers = [1, 2, 3, 4, 5]
zero = [0]
-negative_numbers = [-5,-4,-3,-2,-1]
+negative_numbers = [-5, -4, -3, -2, -1]
integers = negative_numbers + zero + positive_numbers
print(integers)
fruits = ['banana', 'orange', 'mango', 'lemon']
-vegetables = ['Tomato', 'Potato', 'Cabbage','Onion', 'Carrot']
+vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
fruits_and_vegetables = fruits + vegetables
-print(fruits_and_vegetables )
+print(fruits_and_vegetables)
# join with extend
num1 = [0, 1, 2, 3]
-num2= [4, 5,6]
+num2 = [4, 5, 6]
num1.extend(num2)
print('Numbers:', num1)
-negative_numbers = [-5,-4,-3,-2,-1]
-positive_numbers = [1, 2, 3,4,5]
+negative_numbers = [-5, -4, -3, -2, -1]
+positive_numbers = [1, 2, 3, 4, 5]
zero = [0]
negative_numbers.extend(zero)
negative_numbers.extend(positive_numbers)
print('Integers:', negative_numbers)
fruits = ['banana', 'orange', 'mango', 'lemon']
-vegetables = ['Tomato', 'Potato', 'Cabbage','Onion', 'Carrot']
+vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
fruits.extend(vegetables)
-print('Fruits and vegetables:', fruits )
+print('Fruits and vegetables:', fruits)
# count
fruits = ['banana', 'orange', 'mango', 'lemon']
@@ -157,23 +163,23 @@
fruits = ['banana', 'orange', 'mango', 'lemon']
print(fruits.index('orange')) # 1
ages = [22, 19, 24, 25, 26, 24, 25, 24]
-print(ages.index(24))
+print(ages.index(24))
# Reverse
fruits = ['banana', 'orange', 'mango', 'lemon']
fruits.reverse()
-print(fruits.reverse())
+print(fruits.reverse())
ages = [22, 19, 24, 25, 26, 24, 25, 24]
ages.reverse()
-print(ages.reverse())
+print(ages.reverse())
# sort
fruits = ['banana', 'orange', 'mango', 'lemon']
fruits.sort()
-print(fruits)
+print(fruits)
fruits.sort(reverse=True)
print(fruits)
ages = [22, 19, 24, 25, 26, 24, 25, 24]
ages.sort()
-print(ages)
+print(ages)
ages.sort(reverse=True)
-print(ages)
\ No newline at end of file
+print(ages)
diff --git a/06_Day_Tuples/06_tuple.md b/06_Day_Tuples/06_tuples.md
similarity index 76%
rename from 06_Day_Tuples/06_tuple.md
rename to 06_Day_Tuples/06_tuples.md
index c614f3cf9..5c155034e 100644
--- a/06_Day_Tuples/06_tuple.md
+++ b/06_Day_Tuples/06_tuples.md
@@ -1,5 +1,5 @@
-
30 Days Of Python: Day 6 - Tuple
+
30 Days Of Python: Day 6 - Tuples
@@ -9,54 +9,58 @@
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+ Second Edition: July, 2021
-
-[<< Day 5](../05_Day_Lists/05_list.md) | [Day 7 >>](../07_Day_Sets/07_set.md)
+[<< Day 5](../05_Day_Lists/05_lists.md) | [Day 7 >>](../07_Day_Sets/07_sets.md)

- [Day 6:](#day-6)
- - [Tuple](#tuple)
+ - [Tuples](#tuples)
- [Creating a Tuple](#creating-a-tuple)
- - [Tuple Length](#tuple-length)
+ - [Tuple length](#tuple-length)
- [Accessing Tuple Items](#accessing-tuple-items)
- - [Slicing Tuples](#slicing-tuples)
+ - [Slicing tuples](#slicing-tuples)
- [Changing Tuples to Lists](#changing-tuples-to-lists)
- - [Checking an Item in a List](#checking-an-item-in-a-list)
+ - [Checking an Item in a Tuple](#checking-an-item-in-a-tuple)
- [Joining Tuples](#joining-tuples)
- [Deleting Tuples](#deleting-tuples)
- - [💻 Exercises: Day 6](#%f0%9f%92%bb-exercises-day-6)
+ - [💻 Exercises: Day 6](#-exercises-day-6)
+ - [Exercises: Level 1](#exercises-level-1)
+ - [Exercises: Level 2](#exercises-level-2)
# Day 6:
-## Tuple
+## Tuples
A tuple is a collection of different data types which is ordered and unchangeable (immutable). Tuples are written with round brackets, (). Once a tuple is created, we cannot change its values. We cannot use add, insert, remove methods in a tuple because it is not modifiable (mutable). Unlike list, tuple has few methods. Methods related to tuples:
- tuple(): to create an empty tuple
- count(): to count the number of a specified item in a tuple
- index(): to find the index of a specified item in a tuple
-- - operator: to join two or more tuples and to create a new tuple
+- `+` operator: to join two or more tuples and to create a new tuple
### Creating a Tuple
- Empty tuple: Creating an empty tuple
+
```py
# syntax
empty_tuple = ()
# or using the tuple constructor
empty_tuple = tuple()
```
+
- Tuple with initial values
+
```py
# syntax
tpl = ('item1', 'item2','item3')
```
- -
+
```py
fruits = ('banana', 'orange', 'mango', 'lemon')
```
@@ -89,18 +93,20 @@ len(tpl)
first_fruit = fruits[0]
second_fruit = fruits[1]
last_index =len(fruits) - 1
- last_fruit = fruits[las_index]
+ last_fruit = fruits[last_index]
```
- Negative indexing
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last and the negative of the list/tuple length refers to the first item.

+
```py
# Syntax
tpl = ('item1', 'item2', 'item3','item4')
first_item = tpl[-4]
second_item = tpl[-3]
```
+
```py
fruits = ('banana', 'orange', 'mango', 'lemon')
first_fruit = fruits[-4]
@@ -110,7 +116,7 @@ len(tpl)
### Slicing tuples
-We can slice out a subtuple by specifying a range of indexes where to start and where to end in the tuple, the return value will be a new tuple with the specified items.
+We can slice out a sub-tuple by specifying a range of indexes where to start and where to end in the tuple, the return value will be a new tuple with the specified items.
- Range of Positive Indexes
@@ -165,9 +171,9 @@ fruits = tuple(fruits)
print(fruits) # ('apple', 'orange', 'mango', 'lemon')
```
-### Checking an Item in a List
+### Checking an Item in a Tuple
-We can check if an item exists or not in a list using _in_, it returns a boolean.
+We can check if an item exists or not in a tuple using _in_, it returns a boolean.
```py
# Syntax
@@ -215,24 +221,34 @@ fruits = ('banana', 'orange', 'mango', 'lemon')
del fruits
```
+🌕 You are so brave, you made it to this far. You have just completed day 6 challenges and you are 6 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
+
## 💻 Exercises: Day 6
+### Exercises: Level 1
+
1. Create an empty tuple
2. Create a tuple containing names of your sisters and your brothers (imaginary siblings are fine)
3. Join brothers and sisters tuples and assign it to siblings
4. How many siblings do you have?
5. Modify the siblings tuple and add the name of your father and mother and assign it to family_members
-6. Unpack siblings and parents from family_members
-7. Create fruits, vegetables and animal products tuples. Join the three tuples and assign it to a variable called food_stuff.
-8. Slice out the middle item or items from the food_staff list
-9. Slice out the first three items and the last three items from food_staff list
-10. Delete the food_staff list completely
-11. Check if an item exist in a tuple:
+
+### Exercises: Level 2
+
+1. Unpack siblings and parents from family_members
+1. Create fruits, vegetables and animal products tuples. Join the three tuples and assign it to a variable called food_stuff_tp.
+1. Change the about food_stuff_tp tuple to a food_stuff_lt list
+1. Slice out the middle item or items from the food_stuff_tp tuple or food_stuff_lt list.
+1. Slice out the first three items and the last three items from food_stuff_lt list
+1. Delete the food_stuff_tp tuple completely
+1. Check if an item exists in tuple:
- Check if 'Estonia' is a nordic country
- Check if 'Iceland' is a nordic country
+
```py
nordic_countries = ('Denmark', 'Finland','Iceland', 'Norway', 'Sweden')
```
-[<< Day 5](../05_Day_Lists/05_list.md) | [Day 7 >>](../07_Day_Sets/07_set.md)
+
+[<< Day 5](../05_Day_Lists/05_lists.md) | [Day 7 >>](../07_Day_Sets/07_sets.md)
diff --git a/07_Day_Sets/07_set.md b/07_Day_Sets/07_sets.md
similarity index 68%
rename from 07_Day_Sets/07_set.md
rename to 07_Day_Sets/07_sets.md
index 0ccd8654d..26ca08e40 100644
--- a/07_Day_Sets/07_set.md
+++ b/07_Day_Sets/07_sets.md
@@ -1,5 +1,5 @@
-
30 Days Of Python: Day 7 - Set
+
30 Days Of Python: Day 7 - Sets
@@ -9,51 +9,51 @@
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+ Second Edition: July, 2021
-
-[<< Day 6](../06_Day_Tuples/06_tuple.md) | [Day 8 >>](../08_Day/08_dictionary.md)
+[<< Day 6](../06_Day_Tuples/06_tuples.md) | [Day 8 >>](../08_Day_Dictionaries/08_dictionaries.md)

-- [📘 Day 7](#%f0%9f%93%98-day-7)
- - [Set](#set)
+- [📘 Day 7](#-day-7)
+ - [Sets](#sets)
- [Creating a Set](#creating-a-set)
- [Getting Set's Length](#getting-sets-length)
- [Accessing Items in a Set](#accessing-items-in-a-set)
- [Checking an Item](#checking-an-item)
- [Adding Items to a Set](#adding-items-to-a-set)
- [Removing Items from a Set](#removing-items-from-a-set)
- - [Clearing Items in a Set](#clearing-item-in-a-set)
+ - [Clearing Items in a Set](#clearing-items-in-a-set)
- [Deleting a Set](#deleting-a-set)
- - [Converting List to a Set](#converting-list-to-a-set)
+ - [Converting List to Set](#converting-list-to-set)
- [Joining Sets](#joining-sets)
- [Finding Intersection Items](#finding-intersection-items)
- - [Checking Subsets and Super Sets](#checking-subsets-and-super-sets)
+ - [Checking Subset and Super Set](#checking-subset-and-super-set)
- [Checking the Difference Between Two Sets](#checking-the-difference-between-two-sets)
- [Finding Symmetric Difference Between Two Sets](#finding-symmetric-difference-between-two-sets)
- - [Joining Sets](#joining-sets)
- - [💻 Exercises: Day 7](#%f0%9f%92%bb-exercises-day-7)
+ - [Joining Sets](#joining-sets-1)
+ - [💻 Exercises: Day 7](#-exercises-day-7)
+ - [Exercises: Level 1](#exercises-level-1)
+ - [Exercises: Level 2](#exercises-level-2)
+ - [Exercises: Level 3](#exercises-level-3)
# 📘 Day 7
-## Set
+## Sets
-Let me take you back to your elementary or high school Mathematics lesson. The Mathematics definition of a set can be applied also in python. Set is a collection of unordered and unindexed distinct elements. In python set is used to store unique items, and it is possible to find the _union_, _intersection_, _difference_, _symmetric difference_, _subset_, _super set_ and _disjoint set_ among sets.
+Set is a collection of items. Let me take you back to your elementary or high school Mathematics lesson. The Mathematics definition of a set can be applied also in Python. Set is a collection of unordered and un-indexed distinct elements. In Python set is used to store unique items, and it is possible to find the _union_, _intersection_, _difference_, _symmetric difference_, _subset_, _super set_ and _disjoint set_ among sets.
### Creating a Set
-We use curly brackets, {} to create a set.
+To create an empty set, we use the set() function. Empty curly brackets {} will create a dictionary.
- Creating an empty set
```py
# syntax
-st = {}
-# or
st = set()
```
@@ -78,7 +78,7 @@ We use **len()** method to find the length of a set.
```py
# syntax
st = {'item1', 'item2', 'item3', 'item4'}
-len(set)
+len(st)
```
**Example:**
@@ -94,7 +94,7 @@ We use loops to access items. We will see this in loop section
### Checking an Item
-To check if an item exist in a list use use _in_.
+To check if an item exist in a list we use _in_ membership operator.
```py
# syntax
@@ -106,12 +106,12 @@ print("Does set st contain item3? ", 'item3' in st) # Does set st contain item3?
```py
fruits = {'banana', 'orange', 'mango', 'lemon'}
-'mango' in fruits
+print('mango' in fruits ) # True
```
### Adding Items to a Set
-Once a set is created we cannot change any items but we can add additional ones.
+Once a set is created we cannot change any items and we can also add additional items.
- Add one item using _add()_
@@ -129,6 +129,7 @@ fruits.add('lime')
```
- Add multiple items using _update()_
+ The _update()_ allows to add multiple items to a set. The _update()_ takes a list argument.
```py
# syntax
@@ -154,11 +155,21 @@ st = {'item1', 'item2', 'item3', 'item4'}
st.remove('item2')
```
+The pop() methods remove a random item from a list and it returns the removed item.
+
**Example:**
```py
fruits = {'banana', 'orange', 'mango', 'lemon'}
-fruits.pop() # removes the last element from the set
+fruits.pop() # removes a random item from the set
+
+```
+
+If we are interested in the removed item.
+
+```py
+fruits = {'banana', 'orange', 'mango', 'lemon'}
+removed_item = fruits.pop()
```
### Clearing Items in a Set
@@ -186,7 +197,7 @@ If we want to delete the set itself we use _del_ operator.
```py
# syntax
st = {'item1', 'item2', 'item3', 'item4'}
-del set
+del st
```
**Example:**
@@ -198,7 +209,7 @@ del fruits
### Converting List to Set
-We can convert list to set and set to list back. Converting list to set removes duplicates and only unique items will be reserved.
+We can convert list to set and set to list. Converting list to set removes duplicates and only unique items will be reserved.
```py
# syntax
@@ -215,7 +226,7 @@ fruits = set(fruits) # {'mango', 'lemon', 'banana', 'orange'}
### Joining Sets
-We can join two sets using the _union()_ or _update()_ method.
+We can join two sets using the _union()_ or _update()_ method or _|_ symbol .
- Union
This method returns a new set
@@ -224,7 +235,7 @@ We can join two sets using the _union()_ or _update()_ method.
# syntax
st1 = {'item1', 'item2', 'item3', 'item4'}
st2 = {'item5', 'item6', 'item7', 'item8'}
-st3 = st1.union(st2)
+st3 = st1.union(st2) #st3 = st1 | st2
```
**Example:**
@@ -233,6 +244,7 @@ st3 = st1.union(st2)
fruits = {'banana', 'orange', 'mango', 'lemon'}
vegetables = {'tomato', 'potato', 'cabbage','onion', 'carrot'}
print(fruits.union(vegetables)) # {'lemon', 'carrot', 'tomato', 'banana', 'mango', 'orange', 'cabbage', 'potato', 'onion'}
+# or using this : print(fruits | vegetables)
```
- Update
@@ -256,13 +268,14 @@ print(fruits) # {'lemon', 'carrot', 'tomato', 'banana', 'mango', 'orange', 'cabb
### Finding Intersection Items
-Intersection returns a set of items which are in both the sets. See the example
+Intersection returns a set of items which are in both the sets or using _&_ symbol. See the example
```py
# syntax
st1 = {'item1', 'item2', 'item3', 'item4'}
st2 = {'item3', 'item2'}
st1.intersection(st2) # {'item3', 'item2'}
+# or using thia : st1 & st2
```
**Example:**
@@ -275,6 +288,7 @@ whole_numbers.intersection(even_numbers) # {0, 2, 4, 6, 8, 10}
python = {'p', 'y', 't', 'h', 'o','n'}
dragon = {'d', 'r', 'a', 'g', 'o','n'}
python.intersection(dragon) # {'o', 'n'}
+# python & dragon
```
### Checking Subset and Super Set
@@ -307,14 +321,14 @@ python.issubset(dragon) # False
### Checking the Difference Between Two Sets
-It returns the difference between two sets.
+It returns the difference between two sets or using _-_ symbol .
```py
# syntax
st1 = {'item1', 'item2', 'item3', 'item4'}
st2 = {'item2', 'item3'}
-st2.difference(st1) # set()
-st1.difference(st2) # {'item1', 'item4'} => st1\st2
+st2.difference(st1) # set() : st2 - st1
+st1.difference(st2) # {'item1', 'item4'} => st1\st2 : st2 - st1
```
**Example:**
@@ -327,19 +341,21 @@ whole_numbers.difference(even_numbers) # {1, 3, 5, 7, 9}
python = {'p', 'y', 't', 'o','n'}
dragon = {'d', 'r', 'a', 'g', 'o','n'}
python.difference(dragon) # {'p', 'y', 't'} - the result is unordered (characteristic of sets)
+# python - dragon
dragon.difference(python) # {'d', 'r', 'a', 'g'}
+# dragon - python
```
### Finding Symmetric Difference Between Two Sets
-It returns the the symmetric difference between two sets. It means that it returns a set that contains all items from both sets, except items that are present in both sets, mathematically: (A\B) ∪ (B\A)
+It returns the symmetric difference between two sets. It means that it returns a set that contains all items from both sets, except items that are present in both sets, mathematically: (A\B) ∪ (B\A)
```py
# syntax
st1 = {'item1', 'item2', 'item3', 'item4'}
st2 = {'item2', 'item3'}
-# it means (A\B)∪(B)
-st2.symmetric_difference(st1) # {'item1', 'item4'}
+# it means (A\B)∪(B\A)
+st2.symmetric_difference(st1) # {'item1', 'item4'} : st2 ^ st1
```
**Example:**
@@ -352,6 +368,7 @@ whole_numbers.symmetric_difference(some_numbers) # {0, 6, 7, 8, 9, 10}
python = {'p', 'y', 't', 'h', 'o','n'}
dragon = {'d', 'r', 'a', 'g', 'o','n'}
python.symmetric_difference(dragon) # {'r', 't', 'p', 'y', 'g', 'a', 'd', 'h'}
+# python ^ dragon
```
### Joining Sets
@@ -369,14 +386,16 @@ st2.isdisjoint(st1) # False
```py
even_numbers = {0, 2, 4 ,6, 8}
-even_numbers = {1, 3, 5, 7, 9}
+odd_numbers = {1, 3, 5, 7, 9}
even_numbers.isdisjoint(odd_numbers) # True, because no common item
python = {'p', 'y', 't', 'h', 'o','n'}
dragon = {'d', 'r', 'a', 'g', 'o','n'}
-python.disjoint(dragon) # False, there are common items {'o', 'n'}
+python.isdisjoint(dragon) # False, there are common items {'o', 'n'}
```
+🌕 You are a rising star . You have just completed day 7 challenges and you are 7 steps ahead in to your way to greatness. Now do some exercises for your brain and muscles.
+
## 💻 Exercises: Day 7
```py
@@ -387,22 +406,30 @@ B = {19, 22, 20, 25, 26, 24, 28, 27}
age = [22, 19, 24, 25, 26, 24, 25, 24]
```
+### Exercises: Level 1
+
1. Find the length of the set it_companies
2. Add 'Twitter' to it_companies
3. Insert multiple IT companies at once to the set it_companies
4. Remove one of the companies from the set it_companies
5. What is the difference between remove and discard
-6. Join A and B
-7. Find A intersection B
-8. Is A subset of B
-9. Are A and B disjoint sets
-10. Join A with B and B with A
-11. What is the symmetric difference between A and B
-12. Delete the sets completely
-13. Convert the ages to a set and compare the length of the list and the set, which one is bigger?
-14. Explain the difference between the following data types: string, list, tuple and set
-15. _I am a teacher and I love to inspire and teach people._ How many unique words have been used in the sentence?
+
+### Exercises: Level 2
+
+1. Join A and B
+2. Find A intersection B
+3. Is A subset of B
+4. Are A and B disjoint sets
+5. Join A with B and B with A
+6. What is the symmetric difference between A and B
+7. Delete the sets completely
+
+### Exercises: Level 3
+
+1. Convert the ages to a set and compare the length of the list and the set, which one is bigger?
+2. Explain the difference between the following data types: string, list, tuple and set
+3. _I am a teacher and I love to inspire and teach people._ How many unique words have been used in the sentence? Use the split methods and set to get the unique words.
🎉 CONGRATULATIONS ! 🎉
-[<< Day 6](../06_Day_Tuples/06_tuple.md) | [Day 8 >>](../08_Day/08_dictionary.md)
+[<< Day 6](../06_Day_Tuples/06_tuples.md) | [Day 8 >>](../08_Day_Dictionaries/08_dictionaries.md)
diff --git a/08_Day/08_dictionary.md b/08_Day_Dictionaries/08_dictionaries.md
similarity index 88%
rename from 08_Day/08_dictionary.md
rename to 08_Day_Dictionaries/08_dictionaries.md
index acc051c85..07bd049e3 100644
--- a/08_Day/08_dictionary.md
+++ b/08_Day_Dictionaries/08_dictionaries.md
@@ -1,5 +1,5 @@
-
30 Days Of Python: Day 7 - Dictionary
+
30 Days Of Python: Day 8 - Dictionaries
@@ -9,18 +9,17 @@
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+ Second Edition: July, 2021
-
-[<< Day 7 ](../07_Day/07_set.md) | [Day 9 >>](../09_Day/09_conditional.md)
+[<< Day 7 ](../07_Day_Sets/07_sets.md) | [Day 9 >>](../09_Day_Conditionals/09_conditionals.md)

-- [📘 Day 8](#%f0%9f%93%98-day-8)
- - [Dictionary](#dictionary)
+- [📘 Day 8](#-day-8)
+ - [Dictionaries](#dictionaries)
- [Creating a Dictionary](#creating-a-dictionary)
- [Dictionary Length](#dictionary-length)
- [Accessing Dictionary Items](#accessing-dictionary-items)
@@ -31,20 +30,20 @@
- [Changing Dictionary to a List of Items](#changing-dictionary-to-a-list-of-items)
- [Clearing a Dictionary](#clearing-a-dictionary)
- [Deleting a Dictionary](#deleting-a-dictionary)
- - [Copying a Dictionary](#copying-a-dictionary)
+ - [Copy a Dictionary](#copy-a-dictionary)
- [Getting Dictionary Keys as a List](#getting-dictionary-keys-as-a-list)
- - [Getting Dictionary Values as a List](#getting-dictionary-values-as-list)
- - [💻 Exercises: Day 8](#%f0%9f%92%bb-exercises-day-8)
+ - [Getting Dictionary Values as a List](#getting-dictionary-values-as-a-list)
+ - [💻 Exercises: Day 8](#-exercises-day-8)
# 📘 Day 8
-## Dictionary
+## Dictionaries
A dictionary is a collection of unordered, modifiable(mutable) paired (key: value) data type.
### Creating a Dictionary
-To create a dictionary we use curly brackets, {}.
+To create a dictionary we use curly brackets, {} or the *dict()* built-in function.
```py
# syntax
@@ -62,7 +61,7 @@ person = {
'age':250,
'country':'Finland',
'is_marred':True,
- 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python']
+ 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address':{
'street':'Space street',
'zipcode':'02210'
@@ -70,7 +69,7 @@ person = {
}
```
-The dictionary above shows that a value could be any different data type:string, boolean, list, tuple, set or a dictionary.
+The dictionary above shows that a value could be any data types:string, boolean, list, tuple, set or a dictionary.
### Dictionary Length
@@ -90,7 +89,7 @@ person = {
'last_name':'Yetayeh',
'age':250,
'country':'Finland',
- 'is_marred':True,
+ 'is_married':True,
'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address':{
'street':'Space street',
@@ -151,7 +150,7 @@ person = {
}
print(person.get('first_name')) # Asabeneh
print(person.get('country')) # Finland
-print(person.get('skills')) #['HTML','CSS','JavaScript', 'React', 'Node', 'MongoDB', 'Python']
+print(person.get('skills')) #['JavaScript', 'React', 'Node', 'MongoDB', 'Python']
print(person.get('city')) # None
```
@@ -211,7 +210,7 @@ person = {
}
}
person['first_name'] = 'Eyob'
-person['age']
+person['age'] = 252
```
### Checking Keys in a Dictionary
@@ -256,7 +255,7 @@ person = {
}
}
person.pop('first_name') # Removes the firstname item
-person.popitem() # Removes the lastname item
+person.popitem() # Removes the address item
del person['is_married'] # Removes the is_married item
```
@@ -322,9 +321,11 @@ values = dct.values()
print(values) # dict_values(['value1', 'value2', 'value3', 'value4'])
```
+🌕 You are astonishing. Now, you are super charged with the power of dictionaries. You have just completed day 8 challenges and you are 8 steps a head in to your way to greatness. Now do some exercises for your brain and muscles.
+
## 💻 Exercises: Day 8
-1. Create a an empty dictionary called dog
+1. Create an empty dictionary called dog
2. Add name, color, breed, legs, age to the dog dictionary
3. Create a student dictionary and add first_name, last_name, gender, age, marital status, skills, country, city and address as keys for the dictionary
4. Get the length of the student dictionary
@@ -338,4 +339,4 @@ print(values) # dict_values(['value1', 'value2', 'value3', 'value4'])
🎉 CONGRATULATIONS ! 🎉
-[<< Day 7 ](../07_Day/07_set.md) | [Day 9 >>](../09_Day/09_conditional.md)
+[<< Day 7 ](../07_Day_Sets/07_sets.md) | [Day 9 >>](../09_Day_Conditionals/09_conditionals.md)
diff --git a/09_Day/09_conditional.md b/09_Day_Conditionals/09_conditionals.md
similarity index 61%
rename from 09_Day/09_conditional.md
rename to 09_Day_Conditionals/09_conditionals.md
index bae095762..811908c7e 100644
--- a/09_Day/09_conditional.md
+++ b/09_Day_Conditionals/09_conditionals.md
@@ -1,5 +1,5 @@
-
30 Days Of Python: Day 7 - Conditionals
+
30 Days Of Python: Day 9 - Conditionals
@@ -9,17 +9,16 @@
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+ Second Edition: July, 2021
-
-[<< Day 8](../08_Day/08_dictionary.md) | [Day 10 >>](../10_Day/10_loop.md)
+[<< Day 8](../08_Day_Dictionaries/08_dictionaries.md) | [Day 10 >>](../10_Day_Loops/10_loops.md)

-- [📘 Day 9](#%f0%9f%93%98-day-9)
+- [📘 Day 9](#-day-9)
- [Conditionals](#conditionals)
- [If Condition](#if-condition)
- [If Else](#if-else)
@@ -28,20 +27,23 @@
- [Nested Conditions](#nested-conditions)
- [If Condition and Logical Operators](#if-condition-and-logical-operators)
- [If and Or Logical Operators](#if-and-or-logical-operators)
- - [💻 Exercises: Day 9](#%f0%9f%92%bb-exercises-day-9)
+ - [💻 Exercises: Day 9](#-exercises-day-9)
+ - [Exercises: Level 1](#exercises-level-1)
+ - [Exercises: Level 2](#exercises-level-2)
+ - [Exercises: Level 3](#exercises-level-3)
# 📘 Day 9
## Conditionals
-By default, statements in python script are executed sequentially from top to bottom. If the processing logic require so, the sequential flow of execution can be altered in two way:
+By default, statements in Python script are executed sequentially from top to bottom. If the processing logic require so, the sequential flow of execution can be altered in two way:
- Conditional execution: a block of one or more statements will be executed if a certain expression is true
- Repetitive execution: a block of one or more statements will be repetitively executed as long as a certain expression is true. In this section, we will cover _if_, _else_, _elif_ statements. The comparison and logical operators we learned in previous sections will be useful here.
### If Condition
-In python and other programming languages the key word _if_ we use to check if a condition is true and to execute the block code. Remember the indentation after the colon.
+In python and other programming languages the key word _if_ is used to check if a condition is true and to execute the block code. Remember the indentation after the colon.
```py
# syntax
@@ -49,7 +51,7 @@ if condition:
this part of code runs for truthy conditions
```
-**Example: **
+**Example: 1**
```py
a = 3
@@ -72,7 +74,7 @@ else:
this part of code runs for false conditions
```
-**Example: **
+**Example:**
```py
a = 3
@@ -82,7 +84,7 @@ else:
print('A is a positive number')
```
-The condition above proves false, therefore the else block was executed. How about if our condition is more than two? We could use _ elif_.
+The condition above proves false, therefore the else block was executed. How about if our condition is more than two? We could use _elif_.
### If Elif Else
@@ -99,7 +101,7 @@ else:
```
-**Example: **
+**Example:**
```py
a = 0
@@ -118,7 +120,7 @@ else:
code if condition else code
```
-**Example: **
+**Example:**
```py
a = 3
@@ -137,7 +139,7 @@ if condition:
code
```
-**Example: **
+**Example:**
```py
a = 0
@@ -163,13 +165,13 @@ if condition and condition:
code
```
-**Example: **
+**Example:**
```py
a = 0
if a > 0 and a % 2 == 0:
print('A is an even and positive integer')
-elif a > 0 and a % 2 != = 0:
+elif a > 0 and a % 2 != 0:
print('A is a positive integer')
elif a == 0:
print('A is zero')
@@ -185,7 +187,7 @@ if condition or condition:
code
```
-**Example: **
+**Example:**
```py
user = 'James'
@@ -196,9 +198,14 @@ else:
print('Access denied!')
```
+🌕 You are doing great.Never give up because great things take time. You have just completed day 9 challenges and you are 9 steps a head in to your way to greatness. Now do some exercises for your brain and muscles.
+
## 💻 Exercises: Day 9
-1. Get user input using input(“Enter your age: ”). If user is 18 or older, give feedback: You are old enough to drive. If below 18 give feedback to wait for the missing amount of years. Output:
+### Exercises: Level 1
+
+1. Get user input using input(“Enter your age: ”). If user is 18 or older, give feedback: You are old enough to drive. If below 18 give feedback to wait for the missing amount of years. Output:
+
```sh
Enter your age: 30
You are old enough to learn to drive.
@@ -206,58 +213,75 @@ else:
Enter your age: 15
You need 3 more years to learn to drive.
```
-2. Compare the values of my_age and your_age using if … else. Who is older (me or you)? Use input(“Enter your age: ”) to get the age as input. You can use a nested condition to print 'year' for 1 year difference in age, 'years' for bigger differences, and a custom text if my_age = your_age. Output:
+
+2. Compare the values of my_age and your_age using if … else. Who is older (me or you)? Use input(“Enter your age: ”) to get the age as input. You can use a nested condition to print 'year' for 1 year difference in age, 'years' for bigger differences, and a custom text if my_age = your_age. Output:
+
```sh
Enter your age: 30
You are 5 years older than me.
```
-3. Get two numbers from the user using input prompt. If a is greater than b return a is greater than b, if a is less b return a is smaller than b, else a is equal to b. Output:
- ```sh
- Enter number one: 4
- Enter number two: 3
- 4 is greater than 3
- ```
-4. Write a code which gives grade to students according to theirs scores:
+
+3. Get two numbers from the user using input prompt. If a is greater than b return a is greater than b, if a is less b return a is smaller than b, else a is equal to b. Output:
+
+```sh
+Enter number one: 4
+Enter number two: 3
+4 is greater than 3
+```
+
+### Exercises: Level 2
+
+ 1. Write a code which gives grade to students according to theirs scores:
+
```sh
- 80-100, A
- 70-89, B
- 60-69, C
- 50-59, D
- 0-49, F
+ 90-100, A
+ 80-89, B
+ 70-79, C
+ 60-69, D
+ 0-59, F
```
-5. Check if the season is Autumn, Winter, Spring or Summer. If the user input is:
+
+ 2. Get the month from user input then check if the season is Autumn, Winter, Spring or Summer. If the user input is:
September, October or November, the season is Autumn.
December, January or February, the season is Winter.
March, April or May, the season is Spring
June, July or August, the season is Summer
-6. The following list contains some fruits:
+ 3. The following list contains some fruits:
+
```sh
fruits = ['banana', 'orange', 'mango', 'lemon']
```
- If a fruit doesn't exist in the list add the fruit to the list and print the modified list. If the fruit exists print('That fruit already exist in the list')
-7. Here we have a person dictionary. Feel free to modify it!
- ```py
+
+ If a fruit doesn't exist in the list add the fruit to the list and print the modified list. If the fruit exists print('That fruit already exist in the list')
+
+### Exercises: Level 3
+
+ 1. Here we have a person dictionary. Feel free to modify it!
+
+```py
person={
'first_name': 'Asabeneh',
'last_name': 'Yetayeh',
'age': 250,
'country': 'Finland',
- 'is_marred': True,
+ 'is_married': True,
'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address': {
'street': 'Space street',
'zipcode': '02210'
}
}
- ```
- * Check if the person dictionary has skills key, if so print out the middle skill in the skills list.
- * Check if the person dictionary has skills key, if so check if the person has 'Python' skill and print out the result.
- * If a person skills has only JavaScript and React, print('He is a front end developer'), if the person skills has Node, Python, MongoDB, print('He is a backend developer'), if the person skills has React, Node and MongoDB, Print('He is a fullstack developer'), else print('unknown title') - for more accurate results more conditions can be nested!
- * If the person is married and if he lives in Finland, print the information in the following format:
- ```py
- Asabeneh Yetayeh lives in Finland. He is married.
- ```
+```
+
+ * Check if the person dictionary has skills key, if so print out the middle skill in the skills list.
+ * Check if the person dictionary has skills key, if so check if the person has 'Python' skill and print out the result.
+ * If a person skills has only JavaScript and React, print('He is a front end developer'), if the person skills has Node, Python, MongoDB, print('He is a backend developer'), if the person skills has React, Node and MongoDB, Print('He is a fullstack developer'), else print('unknown title') - for more accurate results more conditions can be nested!
+ * If the person is married and if he lives in Finland, print the information in the following format:
+
+```py
+ Asabeneh Yetayeh lives in Finland. He is married.
+```
🎉 CONGRATULATIONS ! 🎉
-[<< Day 8](../08_Day/08_dictionary.md) | [Day 10 >>](../10_Day/10_loop.md)
+[<< Day 8](../08_Day_Dictionaries/08_dictionaries.md) | [Day 10 >>](../10_Day_Loops/10_loops.md)
diff --git a/10_Day/10_loop.md b/10_Day_Loops/10_loops.md
similarity index 74%
rename from 10_Day/10_loop.md
rename to 10_Day_Loops/10_loops.md
index 4fffc196a..9192e059d 100644
--- a/10_Day/10_loop.md
+++ b/10_Day_Loops/10_loops.md
@@ -9,17 +9,16 @@
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+ Second Edition: July, 2021
-
-[<< Day 9](../09_Day/09_conditional.md) | [Day 11 >>](../11_Day/11_function.md)
+[<< Day 9](../09_Day_Conditionals/09_conditionals.md) | [Day 11 >>](../11_Day_Functions/11_functions.md)

-- [📘 Day 10](#%f0%9f%93%98-day-10)
+- [📘 Day 10](#-day-10)
- [Loops](#loops)
- [While Loop](#while-loop)
- [Break and Continue - Part 1](#break-and-continue---part-1)
@@ -29,13 +28,16 @@
- [Nested For Loop](#nested-for-loop)
- [For Else](#for-else)
- [Pass](#pass)
- - [💻 Exercises: Day 10](#%f0%9f%92%bb-exercises-day-10)
+ - [💻 Exercises: Day 10](#-exercises-day-10)
+ - [Exercises: Level 1](#exercises-level-1)
+ - [Exercises: Level 2](#exercises-level-2)
+ - [Exercises: Level 3](#exercises-level-3)
# 📘 Day 10
## Loops
-Life is full of routines. In programming we also do lots of repetitive tasks. In order to handle repetitive task programming languages provide loops. Python programming language also provides the following types of two loops:
+Life is full of routines. In programming we also do lots of repetitive tasks. In order to handle repetitive task programming languages use loops. Python programming language also provides the following types of two loops:
1. while loop
2. for loop
@@ -57,6 +59,7 @@ count = 0
while count < 5:
print(count)
count = count + 1
+#prints from 0 to 4
```
In the above while loop, the condition becomes false when count is 5. That is when the loop stops.
@@ -83,7 +86,6 @@ else:
The above loop condition will be false when count is 5 and the loop stops, and execution starts the else statement. As a result 5 will be printed.
-
### Break and Continue - Part 1
- Break: We use break when we like to get out of or stop the loop.
@@ -109,7 +111,7 @@ while count < 5:
The above while loop only prints 0, 1, 2, but when it reaches 3 it stops.
-- Continue: With the continue statement we can stop the current iteration, and continue with the next:
+- Continue: With the continue statement we can skip the current iteration, and continue with the next:
```py
# syntax
@@ -125,6 +127,7 @@ while condition:
count = 0
while count < 5:
if count == 3:
+ count += 1
continue
print(count)
count = count + 1
@@ -136,7 +139,7 @@ The above while loop only prints 0, 1, 2 and 4 (skips 3).
A _for_ keyword is used to make a for loop, similar with other programming languages, but with some syntax differences. Loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
-- For loop with list
+-Using For loop on list
```py
# syntax
@@ -152,7 +155,7 @@ for number in numbers: # number is temporary name to refer to the list's items,
print(number) # the numbers will be printed line by line, from 0 to 5
```
-- For loop with string
+-Using For loop on string
```py
# syntax
@@ -166,9 +169,13 @@ for iterator in string:
language = 'Python'
for letter in language:
print(letter)
+
+
+for i in range(len(language)):
+ print(language[i])
```
-- For loop with tuple
+-Using For loop on tuple
```py
# syntax
@@ -179,7 +186,7 @@ for iterator in tpl:
**Example:**
```py
-numbers = (0,1,2,3,4,5)
+numbers = (0, 1, 2, 3, 4, 5)
for number in numbers:
print(number)
```
@@ -215,7 +222,7 @@ for key, value in person.items():
print(key, value) # this way we get both keys and values printed out
```
-- Loops in set
+-Using For Loop in set
```py
# syntax
@@ -234,7 +241,7 @@ for company in it_companies:
### Break and Continue - Part 2
Short reminder:
-_Break_: We use break when we like to stop our loop before it is completed.
+_Break_: We use break when we want to stop our loop before it is completed.
```py
# syntax
@@ -256,7 +263,7 @@ for number in numbers:
In the above example, the loop stops when it reaches 3.
-Continue: We use continue when we like to skip some of the steps in the iteration of the loop.
+Continue: We use continue when we want to skip some of the steps in the iteration of the loop.
```py
# syntax
@@ -278,15 +285,15 @@ for number in numbers:
print('outside the loop')
```
-In the example above, if the number equals 3, the step *after* the condition (but inside the loop) is skipped and the execution of the loop continues if there are any iterations left.
+In the example above, if the number equals 3, the step _after_ the condition (but inside the loop) is skipped and the execution of the loop continues if there are any iterations left.
### The Range Function
-The _range()_ function is used to loop through a set of code a certain number of times. The _range(start,end, step)_ takes three parameters: starting, ending and increment. By default it starts from 0 and the increment is 1. The range sequence needs at least 1 argument (end).
+The _range()_ function is used to return a list of numbers. The _range(start, end, step)_ takes three parameters: starting, ending and increment. By default it starts from 0 and the increment is 1. The range sequence needs at least 1 argument (end).
Creating sequences using range
```py
-lst = list(range(11))
+lst = list(range(11))
print(lst) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
st = set(range(1, 11)) # 2 arguments indicate start and end of the sequence, step set to default 1
print(st) # {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
@@ -295,11 +302,15 @@ lst = list(range(0,11,2))
print(lst) # [0, 2, 4, 6, 8, 10]
st = set(range(0,11,2))
print(st) # {0, 2, 4, 6, 8, 10}
+
+# for backward from start to end
+lst = list(range(11,0,-2))
+print(lst) # [11,9,7,5,3,1]
```
```py
# syntax
-for iterator in range(start, end, increment):
+for iterator in range(start, end, step):
```
**Example:**
@@ -316,7 +327,7 @@ We can write loops inside a loop.
```py
# syntax
for x in y:
- for t in s:
+ for t in x:
print(t)
```
@@ -347,7 +358,7 @@ If we want to execute some message when the loop ends, we use else.
```py
# syntax
-for iterator in range(start, end, increment):
+for iterator in range(start, end, step):
do something
else:
print('The loop ended')
@@ -373,11 +384,16 @@ for number in range(6):
pass
```
+🌕 You established a big milestone, you are unstoppable. Keep going! You have just completed day 10 challenges and you are 10 steps a head in to your way to greatness. Now do some exercises for your brain and muscles.
+
## 💻 Exercises: Day 10
+### Exercises: Level 1
+
1. Iterate 0 to 10 using for loop, do the same using while loop.
2. Iterate 10 to 0 using for loop, do the same using while loop.
3. Write a loop that makes seven calls to print(), so we get on the output the following triangle:
+
```py
#
##
@@ -387,7 +403,9 @@ for number in range(6):
######
#######
```
+
4. Use nested loops to create the following:
+
```sh
# # # # # # # #
# # # # # # # #
@@ -398,7 +416,9 @@ for number in range(6):
# # # # # # # #
# # # # # # # #
```
+
5. Print the following pattern:
+
```sh
0 x 0 = 0
1 x 1 = 1
@@ -412,20 +432,34 @@ for number in range(6):
9 x 9 = 81
10 x 10 = 100
```
+
6. Iterate through the list, ['Python', 'Numpy','Pandas','Django', 'Flask'] using a for loop and print out the items.
7. Use for loop to iterate from 0 to 100 and print only even numbers
8. Use for loop to iterate from 0 to 100 and print only odd numbers
-9. Use for loop to iterate from 0 to 100 and print the sum of all numbers.
+
+### Exercises: Level 2
+
+1. Use for loop to iterate from 0 to 100 and print the sum of all numbers.
+
+```sh
+The sum of all numbers is 5050.
+```
+
+2. Use for loop to iterate from 0 to 100 and print the sum of all evens and the sum of all odds.
+
```sh
- The sum of all numbers is 5050.
+ The sum of all evens is 2550. And the sum of all odds is 2500.
```
-10. Use for loop to iterate from 0 to 100 and print the sum of all evens and the sum of all odds.
- ```sh
- The sum of all evens is 2550. And the sum of all odds is 2500.
- ```
-11. Go to the data folder and use the countries.py file. Loop through the countries and extract all the countries containing the word _land_.
-12. This is a fruit list, ['banana', 'orange', 'mango', 'lemon'] reverse the order using loop.
+
+### Exercises: Level 3
+
+1. Go to the data folder and use the [countries.py](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/countries.py) file. Loop through the countries and extract all the countries containing the word _land_.
+1. This is a fruit list, ['banana', 'orange', 'mango', 'lemon'] reverse the order using loop.
+1. Go to the data folder and use the [countries_data.py](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/countries-data.py) file.
+ 1. What are the total number of languages in the data
+ 2. Find the ten most spoken languages from the data
+ 3. Find the 10 most populated countries in the world
🎉 CONGRATULATIONS ! 🎉
-[<< Day 9](../09_Day/09_conditional.md) | [Day 11 >>](../11_Day/11_function.md)
+[<< Day 9](../09_Day_Conditionals/09_conditionals.md) | [Day 11 >>](../11_Day_Functions/11_functions.md)
diff --git a/11_Day/11_function.md b/11_Day_Functions/11_functions.md
similarity index 61%
rename from 11_Day/11_function.md
rename to 11_Day_Functions/11_functions.md
index 28de92cb8..cbfe6210c 100644
--- a/11_Day/11_function.md
+++ b/11_Day_Functions/11_functions.md
@@ -9,17 +9,16 @@
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+ Second Edition: July, 2021
-
-[<< Day 10](../10_Day/10_loop.md) | [Day 12 >>](../12_Day/12_module.md)
+[<< Day 10](../10_Day_Loops/10_loops.md) | [Day 12 >>](../12_Day_Modules/12_modules.md)

-- [📘 Day 11](#%f0%9f%93%98-day-11)
+- [📘 Day 11](#-day-11)
- [Functions](#functions)
- [Defining a Function](#defining-a-function)
- [Declaring and Calling a Function](#declaring-and-calling-a-function)
@@ -32,21 +31,25 @@
- [Arbitrary Number of Arguments](#arbitrary-number-of-arguments)
- [Default and Arbitrary Number of Parameters in Functions](#default-and-arbitrary-number-of-parameters-in-functions)
- [Function as a Parameter of Another Function](#function-as-a-parameter-of-another-function)
- - [💻 Exercises: Day 11](#%f0%9f%92%bb-exercises-day-11)
+ - [Testimony](#testimony)
+ - [💻 Exercises: Day 11](#-exercises-day-11)
+ - [Exercises: Level 1](#exercises-level-1)
+ - [Exercises: Level 2](#exercises-level-2)
+ - [Exercises: Level 3](#exercises-level-3)
# 📘 Day 11
## Functions
-So far we have seen many built-in python functions. In this section, we will focus on custom functions. What is a function? Before we start making functions, lets learn what a function is and why we need them?
+So far we have seen many built-in Python functions. In this section, we will focus on custom functions. What is a function? Before we start making functions, let us learn what a function is and why we need them?
### Defining a Function
-A function is a reusable block of code or programming statements designed to perform a certain task. To define a function, Python provides the _def_ keyword. The following is the syntax for defining a function. The function block of code is executed only if we call it.
+A function is a reusable block of code or programming statements designed to perform a certain task. To define or declare a function, Python provides the _def_ keyword. The following is the syntax for defining a function. The function block of code is executed only if the function is called or invoked.
### Declaring and Calling a Function
-When we make a function we call it declaring a function. When we start using the it we call it calling or invoking a function. Function can be declared with or without parameters.
+When we make a function, we call it declaring a function. When we start using the it, we call it _calling_ or _invoking_ a function. Functions can be declared with or without parameters.
```py
# syntax
@@ -83,7 +86,7 @@ add_two_numbers()
### Function Returning a Value - Part 1
-Function can also return values, if a function does not return any, the value of the function is None. Lets rewrite the above functions using return. From now on, we get a value when calling the function, instead of printing it.
+Functions return values using the _return_ statement. If a function has no return statement, it returns None. Let us rewrite the above functions using return. From now on, we get a value from a function when we call the function and print it.
```py
def generate_full_name ():
@@ -104,7 +107,7 @@ print(add_two_numbers())
### Function with Parameters
-In a function we can pass different data types(number, string, boolean, list, tuple, dictionary or set) as a parameter
+In a function we can pass different data types(number, string, boolean, list, tuple, dictionary or set) as parameters.
- Single Parameter: If our function takes a parameter we should call our function with an argument
@@ -115,7 +118,7 @@ In a function we can pass different data types(number, string, boolean, list, tu
codes
codes
# Calling function
- function_name(parameter)
+ print(function_name(argument))
```
**Example:**
@@ -146,12 +149,12 @@ def sum_of_numbers(n):
total = 0
for i in range(n+1):
total+=i
- print(total)
-sum_of_numbers(10) # 55
-sum_of_numbers(100) # 5050
+ return total
+print(sum_of_numbers(10)) # 55
+print(sum_of_numbers(100)) # 5050
```
-- Two Parameter: A function may or may not have a parameter or parameters. A function may have two or more parameters. If our function takes parameters we should call it with arguments. Let's check a function with two parameters:
+- Two Parameter: A function may or may not have a parameter or parameters. A function may also have two or more parameters. If our function takes parameters we should call it with arguments. Let us check a function with two parameters:
```py
# syntax
@@ -160,7 +163,7 @@ sum_of_numbers(100) # 5050
codes
codes
# Calling function
- function_name(arg1, arg2)
+ print(function_name(arg1, arg2))
```
**Example:**
@@ -179,9 +182,9 @@ print('Sum of two numbers: ', sum_two_numbers(1, 9))
def calculate_age (current_year, birth_year):
age = current_year - birth_year
- return age;
+ return age
-print('Age: ', calculate_age(2019, 1819))
+print('Age: ', calculate_age(2021, 1819))
def weight_of_object (mass, gravity):
weight = str(mass * gravity)+ ' N' # the value has to be changed to a string first
@@ -200,7 +203,7 @@ def function_name(para1, para2):
codes
codes
# Calling function
-function_name(para1='John', para2='Doe') # the order of arguments does not matter here
+print(function_name(para1 = 'John', para2 = 'Doe')) # the order of arguments does not matter here
```
**Example:**
@@ -210,12 +213,12 @@ def print_fullname(firstname, lastname):
space = ' '
full_name = firstname + space + lastname
print(full_name)
-print_fullname(firstname='Asabeneh', lastname='Yetayeh')
+print_fullname(firstname = 'Asabeneh', lastname = 'Yetayeh')
def add_two_numbers (num1, num2):
total = num1 + num2
- print(total)
-add_two_numbers(num2=3, num1=2) # Order does not matter
+ return total
+print(add_two_numbers(num2 = 3, num1 = 2)) # Order does not matter
```
### Function Returning a Value - Part 2
@@ -249,7 +252,7 @@ print(add_two_numbers(2, 3))
def calculate_age (current_year, birth_year):
age = current_year - birth_year
- return age;
+ return age
print('Age: ', calculate_age(2019, 1819))
```
@@ -259,7 +262,6 @@ print('Age: ', calculate_age(2019, 1819))
```py
def is_even (n):
if n % 2 == 0:
- print('even')
return True # return stops further execution of the function, similar to break
return False
print(is_even(10)) # True
@@ -272,7 +274,7 @@ print(is_even(7)) # False
```py
def find_even_numbers(n):
evens = []
- for i in range(n+1):
+ for i in range(n + 1):
if i % 2 == 0:
evens.append(i)
return evens
@@ -311,10 +313,10 @@ def generate_full_name (first_name = 'Asabeneh', last_name = 'Yetayeh'):
print(generate_full_name())
print(generate_full_name('David','Smith'))
-def calculate_age (birth_year,current_year = 2019):
+def calculate_age (birth_year,current_year = 2021):
age = current_year - birth_year
- return age;
-print('Age: ', calculate_age(1819))
+ return age
+print('Age: ', calculate_age(1821))
def weight_of_object (mass, gravity = 9.81):
weight = str(mass * gravity)+ ' N' # the value has to be changed to string first
@@ -345,7 +347,7 @@ def sum_all_nums(*nums):
for num in nums:
total += num # same as total = total + num
return total
-print(sum_all_nums(2, 3, 5))
+print(sum_all_nums(2, 3, 5)) # 10
```
### Default and Arbitrary Number of Parameters in Functions
@@ -354,27 +356,73 @@ print(sum_all_nums(2, 3, 5))
def generate_groups (team,*args):
print(team)
for i in args:
- print(i)
+ print(i)
generate_groups('Team-1','Asabeneh','Brook','David','Eyob')
```
+### Dictionary unpacking
+
+You can call a function which has named arguments using a dictionary with matching key names. You do so using ``**``.
+
+```py
+# Define a function that takes two arguments: 'name' and 'location'
+def greet(name, location):
+ # Print a greeting message using the provided arguments
+ print("Hi there", name, "how is the weather in", location)
+
+# Call the function using keyword arguments
+greet(name="Alice", location="New York")
+# Output: Hi there Alice how is the weather in New York
+
+# Create a dictionary with keys matching the function's parameter names
+my_dict = {"name": "Alice", "location": "New York"}
+
+# Call the function using dictionary unpacking
+greet(**my_dict)
+# The ** operator unpacks the dictionary, passing its key-value pairs
+# as keyword arguments to the function.
+# Output: Hi there Alice how is the weather in New York
+```
+
+### Arbitrary Number of Named Arguments
+
+You can also define a function to accept an arbitrary number of named arguments.
+
+```py
+def arbitrary_named_args(**args):
+ print("I received an arbitrary number of arguments, totaling", len(args))
+ print("They are provided as a dictionary in my function:", type(args))
+ print("Let's print them:")
+ for k, v in args.items():
+ print(" * key:", k, "value:", v)
+```
+
+Generally avoid this unless required as it makes it harder to understand what the function accepts and does.
### Function as a Parameter of Another Function
```py
#You can pass functions around as parameters
def square_number (n):
- return n * n
+ return n ** n
def do_something(f, x):
return f(x)
-print(do_something(square_number, 3))
+print(do_something(square_number, 3)) # 9
```
+🌕 You achieved quite a lot so far. Keep going! You have just completed day 11 challenges and you are 11 steps a head in to your way to greatness. Now do some exercises for your brain and muscles.
+
+## Testimony
+
+Now it is time to express your thoughts about the Author and 30DaysOfPython. You can leave your testimonial on this [link](https://testimonial-s3sw.onrender.com/)
+
## 💻 Exercises: Day 11
+### Exercises: Level 1
+
1. Declare a function _add_two_numbers_. It takes two parameters and it returns a sum.
2. Area of a circle is calculated as follows: area = π x r x r. Write a function that calculates _area_of_circle_.
3. Write a function called add_all_nums which takes arbitrary number of arguments and sums all the arguments. Check if all the list items are number types. If not do give a reasonable feedback.
-4. Temperature in °C can be converted to °F using this formula: °F = (°C x 9/5) + 32. Write a function which converts °C to °F, _convert_celcius_to-fahrenheit_.
+4. Temperature in °C can be converted to °F using this formula: °F = (°C x 9/5) + 32. Write a function which converts °C to °F, _convert_celsius_to-fahrenheit_.
5. Write a function called check-season, it takes a month parameter and returns the season: Autumn, Winter, Spring or Summer.
6. Write a function called calculate_slope which return the slope of a linear equation
7. Quadratic equation is calculated as follows: ax² + bx + c = 0. Write a function which calculates solution set of a quadratic equation, _solve_quadratic_eqn_.
@@ -384,7 +432,7 @@ print(do_something(square_number, 3))
```py
print(reverse_list([1, 2, 3, 4, 5]))
# [5, 4, 3, 2, 1]
-print(reverse_list1(["A", "B", "C"]))
+print(reverse_list(["A", "B", "C"]))
# ["C", "B", "A"]
```
@@ -392,34 +440,36 @@ print(reverse_list1(["A", "B", "C"]))
11. Declare a function named add_item. It takes a list and an item parameters. It returns a list with the item added at the end.
```py
-food_staff = ['Potato', 'Tomato', 'Mango', 'Milk'];
-print( add_item(food_staff, 'Meat')) # ['Potato', 'Tomato', 'Mango', 'Milk','Meat'];
+food_stuff = ['Potato', 'Tomato', 'Mango', 'Milk'];
+print(add_item(food_stuff, 'Meat')) # ['Potato', 'Tomato', 'Mango', 'Milk','Meat'];
numbers = [2, 3, 7, 9];
-print(add_item(numbers, 5)) [2, 3, 7, 9, 5]
+print(add_item(numbers, 5)) # [2, 3, 7, 9, 5]
+
```
12. Declare a function named remove_item. It takes a list and an item parameters. It returns a list with the item removed from it.
```py
-food_staff = ['Potato', 'Tomato', 'Mango', 'Milk'];
-print(remove_item(food_staff, 'Mango')) # ['Potato', 'Tomato', 'Milk'];
-numbers = [2, 3, 7, 9];
+food_stuff = ['Potato', 'Tomato', 'Mango', 'Milk']
+print(remove_item(food_stuff, 'Mango')) # ['Potato', 'Tomato', 'Milk'];
+numbers = [2, 3, 7, 9]
print(remove_item(numbers, 3)) # [2, 7, 9]
```
-13. Declare a function named sum_of_numbers. It takes a number parameter and it adds all the numbers in that range.
+13. Declare a function named sum_of_numbers. It takes a number parameter and it adds all the numbers in that range.
```py
print(sum_of_numbers(5)) # 15
-print(sum_all_numbers(10)) # 55
-print(sum_all_numbers(100)) # 5050
+print(sum_of_numbers(10)) # 55
+print(sum_of_numbers(100)) # 5050
+```
+14. Declare a function named sum_of_odds. It takes a number parameter and it adds all the odd numbers in that range.
+15. Declare a function named sum_of_even. It takes a number parameter and it adds all the even numbers in that - range.
-```
+### Exercises: Level 2
-14. Declare a function named sum_of_odds. It takes a number parameter and it adds all the odd numbers in that range.
-15. Declare a function named sum_of_even. It takes a number parameter and it adds all the even numbers in that - range.
-16. Declare a function named evens_and_odds . It takes a positive integer as parameter and it counts number of evens and odds in the number.
+1. Declare a function named evens_and_odds . It takes a positive integer as parameter and it counts number of evens and odds in the number.
```py
print(evens_and_odds(100))
@@ -427,18 +477,37 @@ print(sum_all_numbers(100)) # 5050
# The number of evens are 51.
```
-17. Call your function factorial, it takes a whole number as a parameter and it return a factorial of the number
-18. Call your function _is_empty_, it takes a parameter and it checks if it is empty or not
-19. Write different functions which take lists. They should calculate_mean, calculate_median, calculate_mode, calculate_range, calculate_variance, calculate_std (standard deviation).
-20. Write a function called is_prime, which checks if a number is prime.
-21. Write a functions which checks if all items are unique in the list.
-22. Write a function which checks if all the items of the list are of the same data type.
-23. Write a function which check if provided variable is a valid python variable
-24. Go to the data folder and access the countries-data.py file.
+1. Call your function factorial, it takes a whole number as a parameter and it return a factorial of the number
+1. Call your function _is_empty_, it takes a parameter and it checks if it is empty or not
+1. Write different functions which take lists. They should calculate_mean, calculate_median, calculate_mode, calculate_range, calculate_variance, calculate_std (standard deviation).
+1. Write a function called _greet_ which takes a default argument, _name_. If no argument is supplied it should print "Hello, Guest!", otherwise it should greet the person by name.
+
+```py
+ greet()
+ # "Hello, Guest!
+ greet("Alice")
+ # "Hello, Alice!"
+```
+1. Create a function called _show_args_ to take an arbitrary number of named arguments and print their names and values.
+ ```py
+ show_args(name="Alice", age=30, city="New York")
+ # Received: name: Alice, age: 30, city: New York
+ show_args(name="Bob", pet="Fluffy, the bunny")
+ # Received: name: Bob, pet: Fluffy, the bunny
+ ```
+
+
+### Exercises: Level 3
+
+1. Write a function called is_prime, which checks if a number is prime.
+1. Write a functions which checks if all items are unique in the list.
+1. Write a function which checks if all the items of the list are of the same data type.
+1. Write a function which check if provided variable is a valid python variable
+1. Go to the data folder and access the countries-data.py file.
- Create a function called the most_spoken_languages in the world. It should return 10 or 20 most spoken languages in the world in descending order
- Create a function called the most_populated_countries. It should return 10 or 20 most populated countries in descending order.
🎉 CONGRATULATIONS ! 🎉
-[<< Day 10](../10_Day/10_loop.md) | [Day 12 >>](../12_Day/12_module.md)
+[<< Day 10](../10_Day_Loops/10_loops.md) | [Day 12 >>](../12_Day_Modules/12_modules.md)
diff --git a/12_Day/12_module.md b/12_Day_Modules/12_modules.md
similarity index 74%
rename from 12_Day/12_module.md
rename to 12_Day_Modules/12_modules.md
index f21756461..07508a88b 100644
--- a/12_Day/12_module.md
+++ b/12_Day_Modules/12_modules.md
@@ -1,5 +1,5 @@
-
30 Days Of Python: Day 11 - Modules
+
30 Days Of Python: Day 12 - Modules
@@ -9,18 +9,18 @@
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+ Second Edition: July, 2021
-
+
-[<< Day 11](../11_Day/11_function.md) | [Day 13>>](../13_Day/13_list_comprehension.md)
+[<< Day 11](../11_Day_Functions/11_functions.md) | [Day 13>>](../13_Day_List_comprehension/13_list_comprehension.md)

-- [📘 Day 12](#%f0%9f%93%98-day-12)
- - [Module](#module)
+- [📘 Day 12](#-day-12)
+ - [Modules](#modules)
- [What is a Module](#what-is-a-module)
- [Creating a Module](#creating-a-module)
- [Importing a Module](#importing-a-module)
@@ -33,26 +33,27 @@
- [Math Module](#math-module)
- [String Module](#string-module)
- [Random Module](#random-module)
- - [💻 Exercises: Day 12](#%f0%9f%92%bb-exercises-day-12)
+ - [💻 Exercises: Day 12](#-exercises-day-12)
+ - [Exercises: Level 1](#exercises-level-1)
+ - [Exercises: Level 2](#exercises-level-2)
+ - [Exercises: Level 3](#exercises-level-3)
# 📘 Day 12
-## Module
+## Modules
### What is a Module
-A module is a file containing a set of codes or a set of functions which can be included to an application. A module could be a file containing a single variable, or a function, a big code base.
+A module is a file containing a set of codes or a set of functions which can be included to an application. A module could be a file containing a single variable, a function or a big code base.
### Creating a Module
-To create a module we write our codes in a python script and we save it as a .py file. Create a file named mymodule.py inside your project folder. Let write some code in this file.
+To create a module we write our codes in a python script and we save it as a .py file. Create a file named mymodule.py inside your project folder. Let us write some code in this file.
```py
# mymodule.py file
def generate_full_name(firstname, lastname):
- space = ' '
- fullname = firstname + space + lastname
- return fullname
+ return firstname + ' ' + lastname
```
Create main.py file in your project directory and import the mymodule.py file.
@@ -64,7 +65,7 @@ To import the file we use the _import_ keyword and the name of the file only.
```py
# main.py file
import mymodule
-print(mymodule.generate_full_name('Asabeneh', 'Yetayeh'))
+print(mymodule.generate_full_name('Asabeneh', 'Yetayeh')) # Asabeneh Yetayeh
```
### Import Functions from a Module
@@ -74,9 +75,9 @@ We can have many functions in a file and we can import all the functions differe
```py
# main.py file
from mymodule import generate_full_name, sum_two_nums, person, gravity
-print(generate_full_name('Asabneh','Yetay'))
+print(generate_full_name('Asabneh','Yetayeh'))
print(sum_two_nums(1,9))
-mass = 100;
+mass = 100
weight = mass * gravity
print(weight)
print(person['firstname'])
@@ -90,8 +91,8 @@ During importing we can rename the name of the module.
# main.py file
from mymodule import generate_full_name as fullname, sum_two_nums as total, person as p, gravity as g
print(fullname('Asabneh','Yetayeh'))
-print(total(1,9))
-mass = 100;
+print(total(1, 9))
+mass = 100
weight = mass * g
print(weight)
print(p)
@@ -162,7 +163,7 @@ The statistics module provides functions for mathematical statistics of numeric
```py
from statistics import * # importing all the statistics modules
-ages = [20,20,24,24,25,22,26,20,23,22,26]
+ages = [20, 20, 4, 24, 25, 22, 26, 20, 23, 22, 26]
print(mean(ages)) # ~22.9
print(median(ages)) # 23
print(mode(ages)) # 20
@@ -180,10 +181,10 @@ print(math.sqrt(2)) # 1.4142135623730951, square root
print(math.pow(2, 3)) # 8.0, exponential function
print(math.floor(9.81)) # 9, rounding to the lowest
print(math.ceil(9.81)) # 10, rounding to the highest
-print(math.log10(100)) # 2, logarithim with 10 as base
+print(math.log10(100)) # 2, logarithm with 10 as base
```
-Now, we have imported the math module which contains lots of function whichs can help us to perform mathematical calculations. To check what functions the module has got, you can use _help(math)_, or _dir(math)_. This will display the available functions in the module. If we want to import only a specific function from the module we import it as follows:
+Now, we have imported the *math* module which contains lots of function which can help us to perform mathematical calculations. To check what functions the module has got, we can use _help(math)_, or _dir(math)_. This will display the available functions in the module. If we want to import only a specific function from the module we import it as follows:
```py
from math import pi
@@ -225,7 +226,7 @@ print(PI) # 3.141592653589793
### String Module
-A useful module for many purposes. Below an example of strings we can get from it.
+A string module is a useful module for many purposes. The example below shows some use of the string module.
```py
import string
@@ -236,24 +237,29 @@ print(string.punctuation) # !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
### Random Module
-By now you are familiar with importing modules. Let's do one more import to get very familiar with it. Let's import _random_ module which gives us a random number between 0 and 0.9999.... The _random_ module has lots of functions but in this section we will only use _random_ and _randint_.
+By now you are familiar with importing modules. Let us do one more import to get very familiar with it. Let us import _random_ module which gives us a random number between 0 and 0.9999.... The _random_ module has lots of functions but in this section we will only use _random_ and _randint_.
```py
from random import random, randint
print(random()) # it doesn't take any arguments; it returns a value between 0 and 0.9999
-print(randint(5, 20)) # it returns a random integer number between 5 and 20
+print(randint(5, 20)) # it returns a random integer number between [5, 20] inclusive
```
+🌕 You are going far. Keep going! You have just completed day 12 challenges and you are 12 steps a head in to your way to greatness. Now do some exercises for your brain and muscles.
+
## 💻 Exercises: Day 12
-1. Writ a function which generates a six digit/character random_user_id.
+### Exercises: Level 1
+
+1. Write a function which generates a six digit/character random_user_id.
```py
- print(random_user_id());
+ print(random_user_id())
'1ee33d'
```
2. Modify the previous task. Declare a function named user_id_gen_by_user. It doesn’t take any parameters but it takes two inputs using input(). One of the inputs is the number of characters and the second input is the number of IDs which are supposed to be generated.
- ```py
-user_id_gen_by_user() # user input: 5 5
+
+```py
+print(user_id_gen_by_user()) # user input: 5 5
#output:
#kcsy2
#SMFYb
@@ -261,31 +267,39 @@ user_id_gen_by_user() # user input: 5 5
#ZXOYh
#2Rgxf
-user_id_gen_by_user() # 16 5
+print(user_id_gen_by_user()) # 16 5
#1GCSgPLMaBAVQZ26
#YD7eFwNQKNs7qXaT
#ycArC5yrRupyG00S
#UbGxOFI7UXSWAyKN
#dIV0SSUTgAdKwStr
+```
- ```
3. Write a function named rgb_color_gen. It will generate rgb colors (3 values ranging from 0 to 255 each).
- ```py
+
+```py
print(rgb_color_gen())
# rgb(125,244,255) - the output should be in this form
+```
+
+### Exercises: Level 2
+
+1. Write a function list_of_hexa_colors which returns any number of hexadecimal colors in an array (six hexadecimal numbers written after #. Hexadecimal numeral system is made out of 16 symbols, 0-9 and first 6 letters of the alphabet, a-f. Check the task 6 for output examples).
+1. Write a function list_of_rgb_colors which returns any number of RGB colors in an array.
+1. Write a function generate_colors which can generate any number of hexa or rgb colors.
+
+```py
+ generate_colors('hexa', 3) # ['#a3e12f','#03ed55','#eb3d2b']
+ generate_colors('hexa', 1) # ['#b334ef']
+ generate_colors('rgb', 3) # ['rgb(5, 55, 175','rgb(50, 105, 100','rgb(15, 26, 80']
+ generate_colors('rgb', 1) # ['rgb(33,79, 176)']
```
-4. Write a function list_of_hexa_colors which returns any number of hexadecimal colors in an array (six hexadecimal numbers written after #. Hexadecimal numeral system is made out of 16 symbols, 0-9 and first 6 letters of the alphabet, a-f. Check the task 6 for output examples).
-5. Write a function list_of_rgb_colors which returns any number of RGB colors in an array.
-6. Write a function generate_colors which can generate any number of hexa or rgb colors.
- ```py
- generate_colors('hexa', 3) # ['#a3e12f','#03ed55','#eb3d2b']
- generate_colors('hexa', 1) # ['#b334ef']
- generate_colors('rgb', 3) # ['rgb(5, 55, 175','rgb(50, 105, 100','rgb(15, 26, 80']
- generate_colors('rgb', 1) # ['rgb(33,79, 176)']
- ```
-7. Call your function shuffle_list, it takes a list as a parameter and it returns a shuffled list
-8. Write a function which returns an array of seven random numbers in a range of 0-9. All the numbers must be unique.
+
+### Exercises: Level 3
+
+1. Call your function shuffle_list, it takes a list as a parameter and it returns a shuffled list
+1. Write a function which returns an array of seven random numbers in a range of 0-9. All the numbers must be unique.
🎉 CONGRATULATIONS ! 🎉
-[<< Day 11](../11_Day/11_function.md) | [Day 13>>](../13_Day/13_list_comprehension.md)
+[<< Day 11](../11_Day_Functions/11_functions.md) | [Day 13>>](../13_Day_List_comprehension/13_list_comprehension.md)
diff --git a/12_Day_Modules/main.py b/12_Day_Modules/main.py
new file mode 100644
index 000000000..e5e3e416e
--- /dev/null
+++ b/12_Day_Modules/main.py
@@ -0,0 +1,10 @@
+
+from mymodule import generate_full_name as fullname, sum_two_nums as total, person as p, gravity as g
+print(fullname('Asabneh','Yetayeh'))
+print(total(1, 9))
+mass = 100
+print(mass)
+weight = mass * g
+print(weight)
+print(p)
+print(p['firstname'])
\ No newline at end of file
diff --git a/12_Day_Modules/mymodule.py b/12_Day_Modules/mymodule.py
new file mode 100644
index 000000000..127ab21f1
--- /dev/null
+++ b/12_Day_Modules/mymodule.py
@@ -0,0 +1,16 @@
+def generate_full_name(firstname, lastname):
+ space = ' '
+ fullname = firstname + space + lastname
+ return fullname
+
+def sum_two_nums (num1, num2):
+ return num1 + num2
+gravity = 9.81
+person = {
+ "firstname": "Asabeneh",
+ "age": 250,
+ "country": "Finland",
+ "city":'Helsinki'
+}
+
+
diff --git a/13_Day/13_list_comprehension.md b/13_Day_List_comprehension/13_list_comprehension.md
similarity index 81%
rename from 13_Day/13_list_comprehension.md
rename to 13_Day_List_comprehension/13_list_comprehension.md
index afd48223c..df44d92ed 100644
--- a/13_Day/13_list_comprehension.md
+++ b/13_Day_List_comprehension/13_list_comprehension.md
@@ -1,5 +1,5 @@
-
30 Days Of Python: Day 12 - List Comprehension
+
30 Days Of Python: Day 13 - List Comprehension
@@ -9,22 +9,22 @@
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+ Second Edition: July, 2021
-
+
-[<< Day 12](../12_Day/12_module.md) | [Day 14>>](../14_Day/14_higher_order_function.md)
+[<< Day 12](../12_Day_Modules/12_modules.md) | [Day 14>>](../14_Day_Higher_order_functions/14_higher_order_functions.md)

-- [📘 Day 13](#%f0%9f%93%98-day-13)
+- [📘 Day 13](#-day-13)
- [List Comprehension](#list-comprehension)
- [Lambda Function](#lambda-function)
- [Creating a Lambda Function](#creating-a-lambda-function)
- [Lambda Function Inside Another Function](#lambda-function-inside-another-function)
- - [💻 Exercises: Day 13](#%f0%9f%92%bb-exercises-day-13)
+ - [💻 Exercises: Day 13](#-exercises-day-13)
# 📘 Day 13
@@ -34,7 +34,7 @@ List comprehension in Python is a compact way of creating a list from a sequence
```py
# syntax
-[i for i in iterable if expression]
+[expression for i in iterable if condition]
```
**Example:1**
@@ -89,12 +89,12 @@ odd_numbers = [i for i in range(21) if i % 2 != 0] # to generate odd numbers in
print(odd_numbers) # [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
# Filter numbers: let's filter out positive even numbers from the list below
numbers = [-8, -7, -3, -1, 0, 1, 3, 4, 5, 7, 6, 8, 10]
-positive_even_numbers = [i for i in range(21) if i % 2 == 0 and i > 0]
+positive_even_numbers = [i for i in numbers if i % 2 == 0 and i > 0]
print(positive_even_numbers) # [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
-# Flattening a three dimensional array
-three_dimen_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
-flattened_list = [ number for row in three_dimen_list for number in row]
+# Flattening a two dimensional array
+list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
+flattened_list = [ number for row in list_of_lists for number in row]
print(flattened_list) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
```
@@ -108,7 +108,7 @@ To create a lambda function we use _lambda_ keyword followed by a parameter(s),
```py
# syntax
-x = lambda param1, param2, param3: param1 + param2 + param2
+x = lambda param1, param2, param3: param1 + param2 + param3
print(x(arg1, arg2, arg3))
```
@@ -119,7 +119,7 @@ print(x(arg1, arg2, arg3))
def add_two_nums(a, b):
return a + b
-print(2, 3) # 5
+print(add_two_nums(2, 3)) # 5
# Lets change the above function to a lambda function
add_two_nums = lambda a, b: a + b
print(add_two_nums(2,3)) # 5
@@ -134,7 +134,7 @@ print(cube(3)) # 27
# Multiple variables
multiple_variable = lambda a, b, c: a ** 2 - 3 * b + 4 * c
-print(multiple_variable(5, 5, 3))
+print(multiple_variable(5, 5, 3)) # 22
```
### Lambda Function Inside Another Function
@@ -151,6 +151,8 @@ two_power_of_five = power(2)(5)
print(two_power_of_five) # 32
```
+🌕 Keep up the good work. Keep the momentum going, the sky is the limit! You have just completed day 13 challenges and you are 13 steps a head in to your way to greatness. Now do some exercises for your brain and muscles.
+
## 💻 Exercises: Day 13
1. Filter only negative and zero in the list using list comprehension
@@ -160,7 +162,7 @@ print(two_power_of_five) # 32
2. Flatten the following list of lists of lists to a one dimensional list :
```py
- list_of_lists =[[[1, 2, 3]], [[4, 5, 6]], [[7, 8, 9]]]
+ list_of_lists =[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
@@ -184,7 +186,7 @@ print(two_power_of_five) # 32
```py
countries = [[('Finland', 'Helsinki')], [('Sweden', 'Stockholm')], [('Norway', 'Oslo')]]
output:
- ['FINLAND', 'HELSINKI', 'SWEDEN', 'STOCKHOLM', 'NORWAY', 'OSLO']
+ [['FINLAND','FIN', 'HELSINKI'], ['SWEDEN', 'SWE', 'STOCKHOLM'], ['NORWAY', 'NOR', 'OSLO']]
```
5. Change the following list to a list of dictionaries:
```py
@@ -196,7 +198,7 @@ print(two_power_of_five) # 32
```
6. Change the following list of lists to a list of concatenated strings:
```py
- names = [[('Asabeneh', 'Yetaeyeh')], [('David', 'Smith')], [('Donald', 'Trump')], [('Bill', 'Gates')]]
+ names = [[('Asabeneh', 'Yetayeh')], [('David', 'Smith')], [('Donald', 'Trump')], [('Bill', 'Gates')]]
output
['Asabeneh Yetaeyeh', 'David Smith', 'Donald Trump', 'Bill Gates']
```
@@ -204,4 +206,4 @@ print(two_power_of_five) # 32
🎉 CONGRATULATIONS ! 🎉
-[<< Day 12](../13_Day/13_list_comprehension.md) | [Day 15>>](../15_Day/15_python_type_error.md)
+[<< Day 12](../12_Day_Modules/12_modules.md) | [Day 14>>](../14_Day_Higher_order_functions/14_higher_order_functions.md)
diff --git a/14_Day/14_higher_order_function.md b/14_Day_Higher_order_functions/14_higher_order_functions.md
similarity index 73%
rename from 14_Day/14_higher_order_function.md
rename to 14_Day_Higher_order_functions/14_higher_order_functions.md
index 7fba2e8da..6787584c1 100644
--- a/14_Day/14_higher_order_function.md
+++ b/14_Day_Higher_order_functions/14_higher_order_functions.md
@@ -9,15 +9,15 @@
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+ Second Edition: July, 2021
-
-
-[<< Day 13](../13_Day/13_list_comprehension.md) | [Day 15>>](../15_Day/15_python_type_error.md)
+
+
+[<< Day 13](../13_Day_List_comprehension/13_list_comprehension.md) | [Day 15>>](../15_Day_Python_type_errors/15_python_type_errors.md)

-- [📘 Day 14](#%f0%9f%93%98-day-14)
+- [📘 Day 14](#-day-14)
- [Higher Order Functions](#higher-order-functions)
- [Function as a Parameter](#function-as-a-parameter)
- [Function as a Return Value](#function-as-a-return-value)
@@ -30,13 +30,16 @@
- [Python - Map Function](#python---map-function)
- [Python - Filter Function](#python---filter-function)
- [Python - Reduce Function](#python---reduce-function)
- - [💻 Exercises: Day 14](#%f0%9f%92%bb-exercises-day-14)
+ - [💻 Exercises: Day 14](#-exercises-day-14)
+ - [Exercises: Level 1](#exercises-level-1)
+ - [Exercises: Level 2](#exercises-level-2)
+ - [Exercises: Level 3](#exercises-level-3)
# 📘 Day 14
## Higher Order Functions
-In python functions are treated as first class citizens, allowing you to perform the following operations on functions:
+In Python functions are treated as first class citizens, allowing you to perform the following operations on functions:
- A function can take one or more functions as parameters
- A function can be returned as a result of another function
@@ -46,8 +49,8 @@ In python functions are treated as first class citizens, allowing you to perform
In this section, we will cover:
1. Handling functions as parameters
-2. Returning functions as return value from other functions
-3. Using python closures and decorators
+2. Returning functions as return value from another functions
+3. Using Python closures and decorators
### Function as a Parameter
@@ -55,8 +58,8 @@ In this section, we will cover:
def sum_numbers(nums): # normal function
return sum(nums) # a sad function abusing the built-in sum function :<
-def higher_order_function(f, *args): # function as a parameter
- summation = f(*args)
+def higher_order_function(f, lst): # function as a parameter
+ summation = f(lst)
return summation
result = higher_order_function(sum_numbers, [1, 2, 3, 4, 5])
print(result) # 15
@@ -97,14 +100,13 @@ You can see from the above example that the higher order function is returning d
## Python Closures
-Python allows a nested function to access the outer scope of the enclosing function. This is is known as a Closure. Let’s have a look at how closures work in Python. In Python, closure is created by nesting a function inside another encapsulating function and then returning the inner function. See the example below.
+Python allows a nested function to access the outer scope of the enclosing function. This is is known as a Closure. Let us have a look at how closures work in Python. In Python, closure is created by nesting a function inside another encapsulating function and then returning the inner function. See the example below.
**Example:**
```py
def add_ten():
ten = 10
-
def add(num):
return num + ten
return add
@@ -137,7 +139,7 @@ def uppercase_decorator(function):
g = uppercase_decorator(greeting)
print(g()) # WELCOME TO PYTHON
-## Lets implement the example above with a decorator
+## Let us implement the example above with a decorator
'''This decorator function is a higher order function
that takes a function as a parameter'''
@@ -168,22 +170,21 @@ def uppercase_decorator(function):
make_uppercase = func.upper()
return make_uppercase
return wrapper
+
# Second decorator
def split_string_decorator(function):
def wrapper():
func = function()
splitted_string = func.split()
return splitted_string
-
return wrapper
+#Decorators will be executed from bottom to top
@split_string_decorator
@uppercase_decorator # order with decorators is important in this case - .upper() function does not work with lists
-
def greeting():
return 'Welcome to Python'
-print(greeting()) # WELCOME TO PYTHON
-
+print(greeting()) # ['WELCOME', 'TO', 'PYTHON']
```
### Accepting Parameters in Decorator Functions
@@ -200,7 +201,7 @@ def decorator_with_parameters(function):
@decorator_with_parameters
def print_full_name(first_name, last_name, country):
print("I am {} {}. I love to teach.".format(
- first_name, last_name, country))
+ first_name, last_name))
print_full_name("Asabeneh", "Yetayeh",'Finland')
```
@@ -251,7 +252,7 @@ def change_to_upper(name):
names_upper_cased = map(change_to_upper, names)
print(list(names_upper_cased)) # ['ASABENEH', 'LIDIYA', 'ERMIAS', 'ABRAHAM']
-# Lets apply it with a lambda function
+# Let us apply it with a lambda function
names_upper_cased = map(lambda name: name.upper(), names)
print(list(names_upper_cased)) # ['ASABENEH', 'LIDIYA', 'ERMIAS', 'ABRAHAM']
```
@@ -310,16 +311,15 @@ print(list(long_names)) # ['Asabeneh']
### Python - Reduce Function
-The _reduce()_ function is defined in the functools module and we should import it from this module. Like map and filter it takes two parameters, a function and an iterable. However, it doesn't return another iterable, instead it returns a single value.
-
-**Example:2**
+The _reduce()_ function is defined in the functools module and we should import it from this module. Like map and filter it takes two parameters, a function and an iterable. However, it does not return another iterable, instead it returns a single value.
+**Example:1**
```py
numbers_str = ['1', '2', '3', '4', '5'] # iterable
-def add(x, y):
+def add_two_nums(x, y):
return int(x) + int(y)
-total = reduce(add_two, numbers_str)
+total = reduce(add_two_nums, numbers_str)
print(total) # 15
```
@@ -331,32 +331,40 @@ names = ['Asabeneh', 'Lidiya', 'Ermias', 'Abraham']
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
+### Exercises: Level 1
+
1. Explain the difference between map, filter, and reduce.
2. Explain the difference between higher order function, closure and decorator
3. Define a call function before map, filter or reduce, see examples.
4. Use for loop to print each country in the countries list.
5. Use for to print each name in the names list.
6. Use for to print each number in the numbers list.
-7. Use map to create a new list by changing each country to uppercase in the countries list
-8. Use map to create a new list by changing each number to its square in the numbers list
-9. Use map to change each name to uppercase in the names list
-10. Use filter to filter out countries containing 'land'.
-11. Use filter to filter out countries having exactly six characters.
-12. Use filter to filter out countries containing six letters and more in the country list.
-13. Use filter to filter out countries starting with an 'E'
-14. Chain two or more list iterators (eg. arr.map(callback).filter(callback).reduce(callback))
-15. Declare a function called get_string_lists which takes a list as a parameter and then returns a list containing only string items.
-16. Use reduce to sum all the numbers in the numbers list.
-17. Use reduce to concatenate all the countries and to produce this sentence: Estonia, Finland, Sweden, Denmark, Norway, and Iceland are north European countries
-18. Declare a function called categorize_countries that returns a list of countries with some common pattern (you can find the [countries list](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/countries.py) in this repository as countries.js(eg 'land', 'ia', 'island', 'stan')).
-19. Create a function returning a dictionary, where keys stand for starting letters of countries and values are the number of country names starting with that letter.
-20. Declare a get_first_ten_countries function - it returns a list of first ten countries from the countries.js list in the data folder.
-21. Declare a get_last_ten_countries function that returns the last ten countries in the countries list.
-23. Use the countries_data.py (https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/countries-data.py) file and follow the tasks below:
+
+### Exercises: Level 2
+
+1. Use map to create a new list by changing each country to uppercase in the countries list
+1. Use map to create a new list by changing each number to its square in the numbers list
+1. Use map to change each name to uppercase in the names list
+1. Use filter to filter out countries containing 'land'.
+1. Use filter to filter out countries having exactly six characters.
+1. Use filter to filter out countries containing six letters and more in the country list.
+1. Use filter to filter out countries starting with an 'E'
+1. Chain two or more list iterators (eg. arr.map(callback).filter(callback).reduce(callback))
+1. Declare a function called get_string_lists which takes a list as a parameter and then returns a list containing only string items.
+1. Use reduce to sum all the numbers in the numbers list.
+1. Use reduce to concatenate all the countries and to produce this sentence: Estonia, Finland, Sweden, Denmark, Norway, and Iceland are north European countries
+1. Declare a function called categorize_countries that returns a list of countries with some common pattern (you can find the [countries list](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/countries.py) in this repository as countries.js(eg 'land', 'ia', 'island', 'stan')).
+1. Create a function returning a dictionary, where keys stand for starting letters of countries and values are the number of country names starting with that letter.
+2. Declare a get_first_ten_countries function - it returns a list of first ten countries from the countries.js list in the data folder.
+1. Declare a get_last_ten_countries function that returns the last ten countries in the countries list.
+
+### Exercises: Level 3
+
+1. Use the countries_data.py (https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/countries-data.py) file and follow the tasks below:
- Sort countries by name, by capital, by population
- Sort out the ten most spoken languages by location.
- Sort out the ten most populated countries.
🎉 CONGRATULATIONS ! 🎉
-[<< Day 13](../13_Day/13_list_comprehension.md) | [Day 15>>](../15_Day/15_python_type_error.md)
\ No newline at end of file
+[<< Day 13](../13_Day_List_comprehension/13_list_comprehension.md) | [Day 15>>](../15_Day_Python_type_errors/15_python_type_errors.md)
\ No newline at end of file
diff --git a/15_Day/15_python_type_error.md b/15_Day_Python_type_errors/15_python_type_errors.md
similarity index 74%
rename from 15_Day/15_python_type_error.md
rename to 15_Day_Python_type_errors/15_python_type_errors.md
index bc2afc512..93b65430e 100644
--- a/15_Day/15_python_type_error.md
+++ b/15_Day_Python_type_errors/15_python_type_errors.md
@@ -9,15 +9,15 @@
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+ Second Edition: July, 2021
-
+
-[<< Day 14](../14_Day/14_higher_order_function.md) | [Day 16 >>](../16_Day/16_python_datetime.md)
+[<< Day 14](../14_Day_Higher_order_functions/14_higher_order_functions.md) | [Day 16 >>](../16_Day_Python_date_time/16_python_datetime.md)

-- [📘 Day 15](#%f0%9f%93%98-day-15)
+- [📘 Day 15](#-day-15)
- [Python Error Types](#python-error-types)
- [SyntaxError](#syntaxerror)
- [NameError](#nameerror)
@@ -29,15 +29,15 @@
- [ImportError](#importerror)
- [ValueError](#valueerror)
- [ZeroDivisionError](#zerodivisionerror)
- - [💻 Exercises: Day 15](#%f0%9f%92%bb-exercises-day-15)
+ - [💻 Exercises: Day 15](#-exercises-day-15)
# 📘 Day 15
## Python Error Types
-When we write code it's common that we make a typo or some other common error. If our code fails to run, the python interpreter will display a message, containing feedback with information on where the problem occurs and the type of an error. It will also sometimes gives us suggestions on a possible fix. Understanding different types of errors in programming languages will help us to debug our code quickly and also it makes us better at what we do.
+When we write code it is common that we make a typo or some other common error. If our code fails to run, the Python interpreter will display a message, containing feedback with information on where the problem occurs and the type of an error. It will also sometimes gives us suggestions on a possible fix. Understanding different types of errors in programming languages will help us to debug our code quickly and also it makes us better at what we do.
-Let's see the most common error types one by one. First let us open our python interactive shell. Go to your you computer terminal and write 'python'. The python interactive shell will be opened.
+Let us see the most common error types one by one. First let us open our Python interactive shell. Go to your you computer terminal and write 'python'. The python interactive shell will be opened.
### SyntaxError
@@ -45,7 +45,7 @@ Let's see the most common error types one by one. First let us open our python i
```py
asabeneh@Asabeneh:~$ python
-Python 3.7.5 (default, Nov 1 2019, 02:16:32)
+Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'hello world'
@@ -56,12 +56,11 @@ SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello w
>>>
```
-As you can see we made a syntax error because we forgot to enclose the string with parenthesis and python already suggests the solution. Let's fix it.
+As you can see we made a syntax error because we forgot to enclose the string with parenthesis and Python already suggests the solution. Let us fix it.
```py
-Last login: Tue Dec 3 15:20:41 on ttys002
asabeneh@Asabeneh:~$ python
-Python 3.7.5 (default, Nov 1 2019, 02:16:32)
+Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'hello world'
@@ -81,9 +80,8 @@ The error was a _SyntaxError_. After the fix our code was executed without a hit
**Example 1: NameError**
```py
-Last login: Tue Dec 3 15:20:41 on ttys002
asabeneh@Asabeneh:~$ python
-Python 3.7.5 (default, Nov 1 2019, 02:16:32)
+Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print(age)
@@ -93,12 +91,11 @@ NameError: name 'age' is not defined
>>>
```
-As you can see from the message above, name age is not defined. Yes, it is true. We did not define an age variable but we were trying to print it out as if we had had declared it. Now, lets fix this by declaring it and assigning with a value.
+As you can see from the message above, name age is not defined. Yes, it is true that we did not define an age variable but we were trying to print it out as if we had had declared it. Now, lets fix this by declaring it and assigning with a value.
```py
-Last login: Tue Dec 3 15:20:41 on ttys002
asabeneh@Asabeneh:~$ python
-Python 3.7.5 (default, Nov 1 2019, 02:16:32)
+Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print(age)
@@ -118,9 +115,8 @@ The type of error was a _NameError_. We debugged the error by defining the varia
**Example 1: IndexError**
```py
-Last login: Tue Dec 3 15:20:41 on ttys002
asabeneh@Asabeneh:~$ python
-Python 3.7.5 (default, Nov 1 2019, 02:16:32)
+Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> numbers = [1, 2, 3, 4, 5]
@@ -131,16 +127,15 @@ IndexError: list index out of range
>>>
```
-In the example above, python raised an _IndexError_, because the list has only indexes from 0 to 4 , so it was out of range.
+In the example above, Python raised an _IndexError_, because the list has only indexes from 0 to 4 , so it was out of range.
### ModuleNotFoundError
**Example 1: ModuleNotFoundError**
```py
-Last login: Tue Dec 3 15:20:41 on ttys002
asabeneh@Asabeneh:~$ python
-Python 3.7.5 (default, Nov 1 2019, 02:16:32)
+Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import maths
@@ -153,9 +148,8 @@ ModuleNotFoundError: No module named 'maths'
In the example above, I added an extra s to math deliberately and _ModuleNotFoundError_ was raised. Lets fix it by removing the extra s from math.
```py
-Last login: Tue Dec 3 15:20:41 on ttys002
asabeneh@Asabeneh:~$ python
-Python 3.7.5 (default, Nov 1 2019, 02:16:32)
+Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import maths
@@ -173,9 +167,8 @@ We fixed it, so let's use some of the functions from the math module.
**Example 1: AttributeError**
```py
-Last login: Tue Dec 3 15:20:41 on ttys002
asabeneh@Asabeneh:~$ python
-Python 3.7.5 (default, Nov 1 2019, 02:16:32)
+Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import maths
@@ -190,12 +183,11 @@ AttributeError: module 'math' has no attribute 'PI'
>>>
```
-As you can see, I made a mistake again! Instead of pi, I tried to call a PI function from maths module. It raised an attribute error, it means, that the function does not exist in the module. Lets fix it by changing from PI to pi.
+As you can see, I made a mistake again! Instead of pi, I tried to call a PI constant from maths module. It raised an attribute error, it means, that the attribute does not exist in the module. Lets fix it by changing from PI to pi.
```py
-Last login: Tue Dec 3 15:20:41 on ttys002
asabeneh@Asabeneh:~$ python
-Python 3.7.5 (default, Nov 1 2019, 02:16:32)
+Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import maths
@@ -219,9 +211,8 @@ Now, when we call pi from the math module we got the result.
**Example 1: KeyError**
```py
-Last login: Tue Dec 3 15:20:41 on ttys002
asabeneh@Asabeneh:~$ python
-Python 3.7.5 (default, Nov 1 2019, 02:16:32)
+Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> users = {'name':'Asab', 'age':250, 'country':'Finland'}
@@ -237,9 +228,8 @@ KeyError: 'county'
As you can see, there was a typo in the key used to get the dictionary value. so, this is a key error and the fix is quite straight forward. Let's do this!
```py
-Last login: Tue Dec 3 15:20:41 on ttys002
asabeneh@Asabeneh:~$ python
-Python 3.7.5 (default, Nov 1 2019, 02:16:32)
+Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> user = {'name':'Asab', 'age':250, 'country':'Finland'}
@@ -261,9 +251,8 @@ We debugged the error, our code ran and we got the value.
**Example 1: TypeError**
```py
-Last login: Tue Dec 3 15:20:41 on ttys002
asabeneh@Asabeneh:~$ python
-Python 3.7.5 (default, Nov 1 2019, 02:16:32)
+Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 4 + '3'
@@ -276,9 +265,8 @@ TypeError: unsupported operand type(s) for +: 'int' and 'str'
In the example above, a TypeError is raised because we cannot add a number to a string. First solution would be to convert the string to int or float. Another solution would be converting the number to a string (the result then would be '43'). Let us follow the first fix.
```py
-Last login: Tue Dec 3 15:20:41 on ttys002
asabeneh@Asabeneh:~$ python
-Python 3.7.5 (default, Nov 1 2019, 02:16:32)
+Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 4 + '3'
@@ -299,9 +287,8 @@ Error removed and we got the result we expected.
**Example 1: TypeError**
```py
-Last login: Tue Dec 3 15:20:41 on ttys002
asabeneh@Asabeneh:~$ python
-Python 3.7.5 (default, Nov 1 2019, 02:16:32)
+Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from math import power
@@ -314,9 +301,8 @@ ImportError: cannot import name 'power' from 'math'
There is no function called power in the math module, it goes with a different name: _pow_. Let's correct it:
```py
-Last login: Tue Dec 3 15:20:41 on ttys002
asabeneh@Asabeneh:~$ python
-Python 3.7.5 (default, Nov 1 2019, 02:16:32)
+Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from math import power
@@ -332,9 +318,8 @@ ImportError: cannot import name 'power' from 'math'
### ValueError
```py
-Last login: Tue Dec 3 15:20:41 on ttys002
asabeneh@Asabeneh:~$ python
-Python 3.7.5 (default, Nov 1 2019, 02:16:32)
+Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> int('12a')
@@ -349,9 +334,8 @@ In this case we cannot change the given string to a number, because of the 'a' l
### ZeroDivisionError
```py
-Last login: Tue Dec 3 15:20:41 on ttys002
asabeneh@Asabeneh:~$ python
-Python 3.7.5 (default, Nov 1 2019, 02:16:32)
+Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 1/0
@@ -364,7 +348,9 @@ ZeroDivisionError: division by zero
We cannot divide a number by zero.
We have covered some of the python error types, if you want to check more about it check the python documentation about python error types.
-If you are good at reading the error types then you will be able to fix your bugs fast and you will also become a better programmer.
+If you are good at reading the error types, then you will be able to fix your bugs fast and you will also become a better programmer.
+
+🌕 You are excelling. You made it to half way to your way to greatness. Now do some exercises for your brain and for your muscle.
## 💻 Exercises: Day 15
@@ -372,4 +358,4 @@ If you are good at reading the error types then you will be able to fix your bug
🎉 CONGRATULATIONS ! 🎉
-[<< Day 14](../14_Day/14_higher_order_function.md) | [Day 16 >>](../16_Day/16_python_datetime.md)
\ No newline at end of file
+[<< Day 14](../14_Day_Higher_order_functions/14_higher_order_functions.md) | [Day 16 >>](../16_Day_Python_date_time/16_python_datetime.md)
diff --git a/16_Day/16_python_datetime.md b/16_Day_Python_date_time/16_python_datetime.md
similarity index 66%
rename from 16_Day/16_python_datetime.md
rename to 16_Day_Python_date_time/16_python_datetime.md
index 7f62e8707..6e93ceb09 100644
--- a/16_Day/16_python_datetime.md
+++ b/16_Day_Python_date_time/16_python_datetime.md
@@ -9,23 +9,23 @@
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+ Second Edition: July, 2021
-
-[<< Day 15](../15_Day/15_python_type_error.md) | [Day 17 >>](../17_Day/17_exception_handling.md)
+[<< Day 15](../15_Day_Python_type_errors/15_python_type_errors.md) | [Day 17 >>](../17_Day_Exception_handling/17_exception_handling.md)
+

-- [📘 Day 16](#%f0%9f%93%98-day-16)
+- [📘 Day 16](#-day-16)
- [Python *datetime*](#python-datetime)
- [Getting *datetime* Information](#getting-datetime-information)
- - [Formating Date Output Using *strftime*](#formating-date-output-using-strftime)
+ - [Formatting Date Output Using *strftime*](#formatting-date-output-using-strftime)
- [String to Time Using *strptime*](#string-to-time-using-strptime)
- [Using *date* from *datetime*](#using-date-from-datetime)
- [Time Objects to Represent Time](#time-objects-to-represent-time)
- - [Difference Between Two Points in Time Using](#difference-between-two-points-in-time)
- - [Difference Between Two Points in Time Using *timedelata*](#difference-between-two-points-in-time-using-timedelata)
- - [💻 Exercises: Day 16](#%f0%9f%92%bb-exercises-day-16)
+ - [Difference Between Two Points in Time Using](#difference-between-two-points-in-time-using)
+ - [Difference Between Two Points in Time Using *timedelta*](#difference-between-two-points-in-time-using-timedelta)
+ - [💻 Exercises: Day 16](#-exercises-day-16)
# 📘 Day 16
## Python *datetime*
@@ -38,29 +38,29 @@ print(dir(datetime))
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo']
```
-With dir or help built-in commands it is possible to know the available functions in a certain module. As you can see, in the datetime module there are many functions, but we will focus on _date_, _datetime_, _time_ and _timedelta_. Let's see them one by one.
+With dir or help built-in commands it is possible to know the available functions in a certain module. As you can see, in the datetime module there are many functions, but we will focus on _date_, _datetime_, _time_ and _timedelta_. Let se see them one by one.
### Getting *datetime* Information
```py
from datetime import datetime
now = datetime.now()
-print(now) # 2019-12-04 23:34:46.549883
-day = now.day # 4
-month = now.month # 12
-year = now.year # 2019
-hour = now.hour # 23
+print(now) # 2021-07-08 07:34:46.549883
+day = now.day # 8
+month = now.month # 7
+year = now.year # 2021
+hour = now.hour # 7
minute = now.minute # 38
second = now.second
timestamp = now.timestamp()
print(day, month, year, hour, minute)
print('timestamp', timestamp)
-print(f'{day}/{month}/{year}, {hour}:{minute}') # 4/12/2019, 23:38
+print(f'{day}/{month}/{year}, {hour}:{minute}') # 8/7/2021, 7:38
```
Timestamp or Unix timestamp is the number of seconds elapsed from 1st of January 1970 UTC.
-### Formating Date Output Using *strftime*
+### Formatting Date Output Using *strftime*
```py
from datetime import datetime
@@ -77,20 +77,20 @@ print(f'{day}/{month}/{year}, {hour}:{minute}') # 1/1/2020, 0:0
```
-Time formating
+Formatting date time using *strftime* method and the documentation can be found [here](https://strftime.org/).
```py
from datetime import datetime
# current date and time
now = datetime.now()
t = now.strftime("%H:%M:%S")
-print("time:", t)
+print("time:", t) # time: 18:21:40
time_one = now.strftime("%m/%d/%Y, %H:%M:%S")
# mm/dd/YY H:M:S format
-print("time one:", time_one)
+print("time one:", time_one) # time one: 06/28/2022, 18:21:40
time_two = now.strftime("%d/%m/%Y, %H:%M:%S")
# dd/mm/YY H:M:S format
-print("time two:", time_two)
+print("time two:", time_two) # time two: 28/06/2022, 18:21:40
```
```sh
@@ -101,16 +101,17 @@ time two: 05/12/2019, 01:05:01
Here are all the _strftime_ symbols we use to format time. An example of all the formats for this module.
-
+
### String to Time Using *strptime*
+Here is a [documentation](https://www.programiz.com/python-programming/datetime/strptime) hat helps to understand the format.
```py
from datetime import datetime
date_string = "5 December, 2019"
-print("date_string =", date_string)
+print("date_string =", date_string) # date_string = 5 December, 2019
date_object = datetime.strptime(date_string, "%d %B, %Y")
-print("date_object =", date_object)
+print("date_object =", date_object) # date_object = 2019-12-05 00:00:00
```
```sh
@@ -123,7 +124,7 @@ date_object = 2019-12-05 00:00:00
```py
from datetime import date
d = date(2020, 1, 1)
-print(d)
+print(d) # 2020-01-01
print('Current date:', d.today()) # 2019-12-05
# date object of today's date
today = date.today()
@@ -138,16 +139,16 @@ print("Current day:", today.day) # 5
from datetime import time
# time(hour = 0, minute = 0, second = 0)
a = time()
-print("a =", a)
+print("a =", a) # a = 00:00:00
# time(hour, minute and second)
b = time(10, 30, 50)
-print("b =", b)
+print("b =", b) # b = 10:30:50
# time(hour, minute and second)
c = time(hour=10, minute=30, second=50)
-print("c =", c)
+print("c =", c) # c = 10:30:50
# time(hour, minute, second, microsecond)
d = time(10, 30, 50, 200555)
-print("d =", d)
+print("d =", d) # d = 10:30:50.200555
```
output
@@ -159,11 +160,12 @@ d = 10:30:50.200555
### Difference Between Two Points in Time Using
```py
+from datetime import date, datetime
today = date(year=2019, month=12, day=5)
new_year = date(year=2020, month=1, day=1)
time_left_for_newyear = new_year - today
# Time left for new year: 27 days, 0:00:00
-print('Time left for new year: ', time_left_for_newyear)
+print('Time left for new year: ', time_left_for_newyear) # Time left for new year: 27 days, 0:00:00
t1 = datetime(year = 2019, month = 12, day = 5, hour = 0, minute = 59, second = 0)
t2 = datetime(year = 2020, month = 1, day = 1, hour = 0, minute = 0, second = 0)
@@ -171,7 +173,7 @@ diff = t2 - t1
print('Time left for new year:', diff) # Time left for new year: 26 days, 23: 01: 00
```
-### Difference Between Two Points in Time Using *timedelata*
+### Difference Between Two Points in Time Using *timedelta*
```py
from datetime import timedelta
@@ -187,18 +189,20 @@ print("t3 =", t3)
t3 = 86 days, 22:56:50
```
+🌕 You are an extraordinary. You are 16 steps a head to your way to greatness. Now do some exercises for your brain and muscles.
+
## 💻 Exercises: Day 16
1. Get the current day, month, year, hour, minute and timestamp from datetime module
-1. Format the current date using this format: "%m/%d/%Y, %H:%M:%S")
-1. Today is 5 December, 2019. Change this time string to time.
-1. Calculate the time difference between now and new year.
-1. Calculate the time difference between 1 January 1970 and now.
-1. Think, what can you use the datetime module for? Examples:
+2. Format the current date using this format: "%m/%d/%Y, %H:%M:%S")
+3. Today is 5 December, 2019. Change this time string to time.
+4. Calculate the time difference between now and new year.
+5. Calculate the time difference between 1 January 1970 and now.
+6. Think, what can you use the datetime module for? Examples:
- Time series analysis
- To get a timestamp of any activities in an application
- Adding posts on a blog
🎉 CONGRATULATIONS ! 🎉
-[<< Day 15](../15_Day/15_python_type_error.md) | [Day 17 >>](../17_Day/17_exception_handling.md)
\ No newline at end of file
+[<< Day 15](../15_Day_Python_type_errors/15_python_type_errors.md) | [Day 17 >>](../17_Day_Exception_handling/17_exception_handling.md)
diff --git a/17_Day/17_exception_handling.md b/17_Day_Exception_handling/17_exception_handling.md
similarity index 77%
rename from 17_Day/17_exception_handling.md
rename to 17_Day_Exception_handling/17_exception_handling.md
index 70b6d10a5..1d5409a05 100644
--- a/17_Day/17_exception_handling.md
+++ b/17_Day_Exception_handling/17_exception_handling.md
@@ -9,14 +9,15 @@
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+ Second Edition: July, 2021
-
-[<< Day 16](../16_Day/16_python_datetime.md) | [Day 18 >>](../18_Day/18_regular_expression.md)
+[<< Day 16](../16_Day_Python_date_time/16_python_datetime.md) | [Day 18 >>](../18_Day_Regular_expressions/18_regular_expressions.md)
+

-- [📘 Day 17](#%f0%9f%93%98-day-17)
+
+- [📘 Day 17](#-day-17)
- [Exception Handling](#exception-handling)
- [Packing and Unpacking Arguments in Python](#packing-and-unpacking-arguments-in-python)
- [Unpacking](#unpacking)
@@ -30,14 +31,13 @@
- [Zip](#zip)
- [Exercises: Day 17](#exercises-day-17)
-
# 📘 Day 17
## Exception Handling
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.

@@ -66,7 +66,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')
@@ -76,7 +75,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.
@@ -101,7 +100,6 @@ Type error occured
```
In the code above the output is going to be _TypeError_.
-
Now, let's add an additional block:
```py
@@ -109,15 +107,13 @@ 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}.')
+ print(f'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:
@@ -132,6 +128,19 @@ 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(f'You are {name}. And your age is {age}.')
+except Exception as e:
+ print(e)
+
+```
+
## Packing and Unpacking Arguments in Python
We use two operators:
@@ -139,7 +148,7 @@ 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
@@ -149,17 +158,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
```
@@ -189,7 +198,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.
```
@@ -216,9 +225,9 @@ print(sum_all(1, 2, 3, 4, 5, 6, 7)) # 28
def packing_person_info(**kwargs):
# check the type of kwargs and it is a dict type
# print(type(kwargs))
- # Printing dictionary items
+ # Printing dictionary items
for key in kwargs:
- print("{key} = {kwargs[key]}")
+ print(f"{key} = {kwargs[key]}")
return kwargs
print(packing_person_info(name="Asabeneh",
@@ -235,37 +244,45 @@ 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 = [0, *list_one, *list_two]
+lst_two = [4, 5, 6, 7]
+lst = [0, *lst_one, *lst_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
+countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
for index, i in enumerate(countries):
- print('hi')
if i == 'Finland':
- print('The country {i} has been found at index {index}')
+ print(f'The country {i} has been found at index {index}')
```
+
```sh
-The country Finland has been found at index 1.
+The country Finland has been found at index 0.
```
## Zip
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):
@@ -273,16 +290,18 @@ for f, v in zip(fruits, vegetables):
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 muscles.
+
## Exercises: Day 17
1. names = ['Finland', 'Sweden', 'Norway','Denmark','Iceland', 'Estonia','Russia']. Unpack the first five countries and store them in a variable nordic_countries, store Estonia and Russia in es, and ru respectively.
-
🎉 CONGRATULATIONS ! 🎉
-[<< Day 16](../16_Day/16_python_datetime.md) | [Day 18 >>](../18_Day/18_regular_expression.md)
\ No newline at end of file
+[<< Day 16](../16_Day_Python_date_time/16_python_datetime.md) | [Day 18 >>](../18_Day_Regular_expressions/18_regular_expressions.md)
diff --git a/18_Day/18_regular_expression.md b/18_Day_Regular_expressions/18_regular_expressions.md
similarity index 69%
rename from 18_Day/18_regular_expression.md
rename to 18_Day_Regular_expressions/18_regular_expressions.md
index b5371c9da..b8b934e7e 100644
--- a/18_Day/18_regular_expression.md
+++ b/18_Day_Regular_expressions/18_regular_expressions.md
@@ -12,32 +12,34 @@
First Edition: Nov 22 - Dec 22, 2019
-
-[<< Day 17](../17_Day/17_exception_handling.md) | [Day 19>>](../19_Day/19_file_handling.md)
+
+[<< Day 17](../17_Day_Exception_handling/17_exception_handling.md) | [Day 19>>](../19_Day_File_handling/19_file_handling.md)

-- [📘 Day 18](#%f0%9f%93%98-day-18)
- - [Regular Expressions](#regular-expression)
- - [The *re* Module](#The-re-module)
- - [Functions in *re* Module](#functions-in-re-module)
+- [📘 Day 18](#-day-18)
+ - [Regular Expressions](#regular-expressions)
+ - [The *re* Module](#the-re-module)
+ - [Methods in *re* Module](#methods-in-re-module)
- [Match](#match)
- [Search](#search)
- [Searching for All Matches Using *findall*](#searching-for-all-matches-using-findall)
- - [Replacing a Substring](#replacing-a-Substring)
+ - [Replacing a Substring](#replacing-a-substring)
- [Splitting Text Using RegEx Split](#splitting-text-using-regex-split)
- [Writing RegEx Patterns](#writing-regex-patterns)
- - [Square Brackets](#square-brackets)
+ - [Square Bracket](#square-bracket)
- [Escape character(\\) in RegEx](#escape-character-in-regex)
- [One or more times(+)](#one-or-more-times)
- [Period(.)](#period)
- [Zero or more times(\*)](#zero-or-more-times)
- - [Zero or one times(?)](#zero-or-one-times)
- - [Quantifiers in RegEx](#quantifiers-in-regex)
- - [Cart ^](#cart)
- - [💻 Exercises: Day 18](#%f0%9f%92%bb-exercises-day-18)
-
+ - [Zero or one time(?)](#zero-or-one-time)
+ - [Quantifier in RegEx](#quantifier-in-regex)
+ - [Cart ^](#cart-)
+ - [💻 Exercises: Day 18](#-exercises-day-18)
+ - [Exercises: Level 1](#exercises-level-1)
+ - [Exercises: Level 2](#exercises-level-2)
+ - [Exercises: Level 3](#exercises-level-3)
# 📘 Day 18
@@ -53,19 +55,20 @@ After importing the module we can use it to detect or find patterns.
import re
```
-### Functions in *re* Module
+### Methods in *re* Module
To find a pattern we use different set of *re* character sets that allows to search for a match in a string.
-* *re.match()*: searches only in the beginning of the first line of the string and returns matched objects if found, else returns none.
-* *re.search*: Returns a match object if there is one anywhere in the string, including multiline strings.
-* *re.findall*: Returns a list containing all matches
-* *re.split*: Takes a string, splits it at the match points, returns a list
-* *re.sub*: Replaces one or many matches within a string
+
+- *re.match()*: searches only in the beginning of the first line of the string and returns matched objects if found, else returns None.
+- *re.search*: Returns a match object if there is one anywhere in the string, including multiline strings.
+- *re.findall*: Returns a list containing all matches
+- *re.split*: Takes a string, splits it at the match points, returns a list
+- *re.sub*: Replaces one or many matches within a string
#### Match
```py
-# syntac
+# syntax
re.match(substring, string, re.I)
# substring is a string or a pattern, string is the text we look for a pattern , re.I is case ignore
```
@@ -82,20 +85,31 @@ span = match.span()
print(span) # (0, 15)
# Lets find the start and stop position from the span
start, end = span
-print(start, end) # 0, 15
+print(start, end) # 0 15
substring = txt[start:end]
print(substring) # I love to teach
```
As you can see from the example above, the pattern we are looking for (or the substring we are looking for) is *I love to teach*. The match function returns an object **only** if the text starts with the pattern.
+```py
+import re
+
+txt = 'I love to teach python and javaScript'
+match = re.match('I like to teach', txt, re.I)
+print(match) # None
+```
+
+The string does not string with *I like to teach*, therefore there was no match and the match method returned None.
+
#### Search
```py
# syntax
-re.match(substring, string, re.I)
+re.search(substring, string, re.I)
# substring is a pattern, string is the text we look for a pattern , re.I is case ignore flag
```
+
```py
import re
@@ -115,7 +129,7 @@ substring = txt[start:end]
print(substring) # first
```
-As you can see, search is much better than match because it can look for the pattern throughout the text. Search returns a match object with a first match that was found, otherwise it returns _None_. A much better *re* function is *findall*. This function checks for the pattern through the whole string and returns all the matches as a list.
+As you can see, search is much better than match because it can look for the pattern throughout the text. Search returns a match object with a first match that was found, otherwise it returns *None*. A much better *re* function is *findall*. This function checks for the pattern through the whole string and returns all the matches as a list.
#### Searching for All Matches Using *findall*
@@ -128,10 +142,9 @@ I recommend python for a first programming language'''
# It return a list
matches = re.findall('language', txt, re.I)
print(matches) # ['language', 'language']
-
```
-As you can see, the word language was found two times in the string. Let's practice some more.
+As you can see, the word *language* was found two times in the string. Let us practice some more.
Now we will look for both Python and python words in the string:
```py
@@ -144,7 +157,7 @@ print(matches) # ['Python', 'python']
```
-Since we are using *re.I* both lowercase and uppercase letters are included. If we don't have that flag, then we will have to write our pattern differently. Let's check it out:
+Since we are using *re.I* both lowercase and uppercase letters are included. If we do not have the re.I flag, then we will have to write our pattern differently. Let us check it out:
```py
txt = '''Python is the most beautiful language that a human being has ever created.
@@ -166,13 +179,13 @@ txt = '''Python is the most beautiful language that a human being has ever creat
I recommend python for a first programming language'''
match_replaced = re.sub('Python|python', 'JavaScript', txt, re.I)
-print(match_replaced) # JavaScript is the most beautiful language that a human being has ever created.
+print(match_replaced) # JavaScript is the most beautiful language that a human being has ever created.I recommend python for a first programming language
# OR
match_replaced = re.sub('[Pp]ython', 'JavaScript', txt, re.I)
-print(match_replaced) # JavaScript is the most beautiful language that a human being has ever created.
+print(match_replaced) # JavaScript is the most beautiful language that a human being has ever created.I recommend python for a first programming language
```
-Let's add one more example. The following string is really hard to read unless we remove the % symbol. Replacing the % with an empty string will clean the text.
+Let us add one more example. The following string is really hard to read unless we remove the % symbol. Replacing the % with an empty string will clean the text.
```py
@@ -184,11 +197,11 @@ D%o%es thi%s m%ot%iv%a%te %y%o%u to b%e a t%e%a%cher?'''
matches = re.sub('%', '', txt)
print(matches)
```
+
```sh
-I am teacher and I love teaching.
+I am teacher and I love teaching.
There is nothing as rewarding as educating and empowering people.
-I found teaching more interesting than any other jobs.
-Does this motivate you to be a teacher?
+I found teaching more interesting than any other jobs. Does this motivate you to be a teacher?
```
## Splitting Text Using RegEx Split
@@ -200,6 +213,7 @@ I found teaching more interesting than any other jobs.
Does this motivate you to be a teacher?'''
print(re.split('\n', txt)) # splitting using \n - end of line symbol
```
+
```sh
['I am teacher and I love teaching.', 'There is nothing as rewarding as educating and empowering people.', 'I found teaching more interesting than any other jobs.', 'Does this motivate you to be a teacher?']
```
@@ -207,7 +221,7 @@ print(re.split('\n', txt)) # splitting using \n - end of line symbol
## Writing RegEx Patterns
To declare a string variable we use a single or double quote. To declare RegEx variable *r''*.
-The following pattern only identifies apple with lowercase, to make it case insensitive either we should rewrite our pattern or we should add a flag.
+The following pattern only identifies apple with lowercase, to make it case insensitive either we should rewrite our pattern or we should add a flag.
```py
import re
@@ -226,46 +240,47 @@ matches = re.findall(regex_pattern, txt)
print(matches) # ['Apple', 'apple']
```
+
* []: A set of characters
- * [a-c] means, a or b or c
- * [a-z] means, any letter from a to z
- * [A-Z] means, any character from A to Z
- * [0-3] means, 0 or 1 or 2 or 3
- * [0-9] means any number from 0 to 9
- * [A-Za-z0-9] any single character, that is a to z, A to Z or 0 to 9
-* \\: uses to escape special characters
- * \d means: match where the string contains digits (numbers from 0-9)
- * \D means: match where the string does not contain digits
-* . : any character except new line character(\n)
-* ^: starts with
- * r'^substring' eg r'^love', a sentence that starts with a word love
- * r'[^abc] means not a, not b, not c.
-* $: ends with
- * r'substring$' eg r'love$', sentence that ends with a word love
-* *: zero or more times
- * r'[a]*' means a optional or it can occur many times.
-* +: one or more times
- * r'[a]+' means at least once (or more)
-* ?: zero or one time
- * r'[a]?' means zero times or once
-* {3}: Exactly 3 characters
-* {3,}: At least 3 characters
-* {3,8}: 3 to 8 characters
-* |: Either or
- * r'apple|banana' means either apple or a banana
-* (): Capture and group
+ - [a-c] means, a or b or c
+ - [a-z] means, any letter from a to z
+ - [A-Z] means, any character from A to Z
+ - [0-3] means, 0 or 1 or 2 or 3
+ - [0-9] means any number from 0 to 9
+ - [A-Za-z0-9] any single character, that is a to z, A to Z or 0 to 9
+- \\: uses to escape special characters
+ - \d means: match where the string contains digits (numbers from 0-9)
+ - \D means: match where the string does not contain digits
+- . : any character except new line character(\n)
+- ^: starts with
+ - r'^substring' eg r'^love', a sentence that starts with a word love
+ - r'[^abc] means not a, not b, not c.
+- $: ends with
+ - r'substring$' eg r'love$', sentence that ends with a word love
+- *: zero or more times
+ - r'[a]*' means a optional or it can occur many times.
+- +: one or more times
+ - r'[a]+' means at least once (or more)
+- ?: zero or one time
+ - r'[a]?' means zero times or once
+- {3}: Exactly 3 characters
+- {3,}: At least 3 characters
+- {3,8}: 3 to 8 characters
+- |: Either or
+ - r'apple|banana' means either apple or a banana
+- (): Capture and group

-Let's use examples to clarify the meta characters above
+Let us use examples to clarify the meta characters above
### Square Bracket
-Let's use square bracket to include lower and upper case
+Let us use square bracket to include lower and upper case
```py
regex_pattern = r'[Aa]pple' # this square bracket mean either A or a
-txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away. '
+txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away.'
matches = re.findall(regex_pattern, txt)
print(matches) # ['Apple', 'apple']
```
@@ -274,7 +289,7 @@ If we want to look for the banana, we write the pattern as follows:
```py
regex_pattern = r'[Aa]pple|[Bb]anana' # this square bracket means either A or a
-txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away. '
+txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away.'
matches = re.findall(regex_pattern, txt)
print(matches) # ['Apple', 'banana', 'apple', 'banana']
```
@@ -285,31 +300,31 @@ Using the square bracket and or operator , we manage to extract Apple, apple, Ba
```py
regex_pattern = r'\d' # d is a special character which means digits
-txt = 'This regular expression example was made on December 6, 2019.'
+txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021'
matches = re.findall(regex_pattern, txt)
-print(matches) # ['6', '2', '0', '1', '9'], this is not what we want
+print(matches) # ['6', '2', '0', '1', '9', '8', '2', '0', '2', '1'], this is not what we want
```
### One or more times(+)
```py
regex_pattern = r'\d+' # d is a special character which means digits, + mean one or more times
-txt = 'This regular expression example was made on December 6, 2019.'
+txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021'
matches = re.findall(regex_pattern, txt)
-print(matches) # ['6', '2019'] - now, this is better!
+print(matches) # ['6', '2019', '8', '2021'] - now, this is better!
```
### Period(.)
+
```py
regex_pattern = r'[a].' # this square bracket means a and . means any character except new line
txt = '''Apple and banana are fruits'''
matches = re.findall(regex_pattern, txt)
print(matches) # ['an', 'an', 'an', 'a ', 'ar']
-regex_pattern = r'[a].+' # . any character, + any character one or more times
+regex_pattern = r'[a].+' # . any character, + any character one or more times
matches = re.findall(regex_pattern, txt)
print(matches) # ['and banana are fruits']
-
```
### Zero or more times(\*)
@@ -317,12 +332,10 @@ print(matches) # ['and banana are fruits']
Zero or many times. The pattern could may not occur or it can occur many times.
```py
-
-regex_pattern = r'[a].*' # . any character, * any character zero or more times
+regex_pattern = r'[a].*' # . any character, * any character zero or more times
txt = '''Apple and banana are fruits'''
matches = re.findall(regex_pattern, txt)
print(matches) # ['and banana are fruits']
-
```
### Zero or one time(?)
@@ -331,59 +344,61 @@ Zero or one time. The pattern may not occur or it may occur once.
```py
txt = '''I am not sure if there is a convention how to write the word e-mail.
-Some people write it email others may write it as Email or E-mail.'''
+Some people write it as email others may write it as Email or E-mail.'''
regex_pattern = r'[Ee]-?mail' # ? means here that '-' is optional
matches = re.findall(regex_pattern, txt)
print(matches) # ['e-mail', 'email', 'Email', 'E-mail']
-
```
### Quantifier in RegEx
-We can specify the length of the substring we are looking for in a text, using a curly bracket. Lets imagine, we are interested in a substring with a length of 4 characters:
+We can specify the length of the substring we are looking for in a text, using a curly bracket. Let us imagine, we are interested in a substring with a length of 4 characters:
```py
-txt = 'This regular expression example was made on December 6, 2019.'
+txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021'
regex_pattern = r'\d{4}' # exactly four times
matches = re.findall(regex_pattern, txt)
-print(matches) # ['2019']
+print(matches) # ['2019', '2021']
-txt = 'This regular expression example was made on December 6, 2019.'
-regex_pattern = r'\d{1, 4}' # 1 to 4
+txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021'
+regex_pattern = r'\d{1,4}'
matches = re.findall(regex_pattern, txt)
-print(matches) # ['6', '2019']
-
+print(matches) # ['6', '2019', '8', '2021']
```
### Cart ^
-* Starts with
-
+- Starts with
+
```py
-txt = 'This regular expression example was made on December 6, 2019.'
+txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021'
regex_pattern = r'^This' # ^ means starts with
matches = re.findall(regex_pattern, txt)
print(matches) # ['This']
```
-* Negation
+- Negation
```py
-txt = 'This regular expression example was made on December 6, 2019.'
+txt = 'This regular expression example was made on December 6, 2019 and revised on July 8, 2021'
regex_pattern = r'[^A-Za-z ]+' # ^ in set character means negation, not A to Z, not a to z, no space
matches = re.findall(regex_pattern, txt)
-print(matches) # ['6,', '2019.']
+print(matches) # ['6,', '2019', '8', '2021']
```
-
## 💻 Exercises: Day 18
- 1. What is the most frequent word in the following paragraph?
+### Exercises: Level 1
+
+ 1. What is the most frequent word in the following paragraph?
+
```py
paragraph = 'I love teaching. If you do not love teaching what else can you love. I love Python if you do not love something which can give you all the capabilities to develop an application what else can you love.
```
+
```sh
- [(6, 'love'),
+ [
+ (6, 'love'),
(5, 'you'),
(3, 'can'),
(2, 'what'),
@@ -404,18 +419,21 @@ print(matches) # ['6,', '2019.']
(1, 'an'),
(1, 'all'),
(1, 'Python'),
- (1, 'If')]
+ (1, 'If')
+ ]
```
-2. The position of some particles on the horizontal x-axis -12, -4, -3 and -1 in the negative direction, 0 at origin, 4 and 8 in the positive direction. Extract these numbers from this whole text and find the distance between the two furthest particles.
+2. The position of some particles on the horizontal x-axis are -12, -4, -3 and -1 in the negative direction, 0 at origin, 4 and 8 in the positive direction. Extract these numbers from this whole text and find the distance between the two furthest particles.
```py
-points = ['-1', '2', '-4', '-3', '-1', '0', '4', '8']
-sorted_points = [-4, -3, -1, -1, 0, 2, 4, 8]
-distance = 12
+points = ['-12', '-4', '-3', '-1', '0', '4', '8']
+sorted_points = [-12, -4, -3, -1, -1, 0, 2, 4, 8]
+distance = 8 -(-12) # 20
```
-3. Write a pattern which identifies if a string is a valid python variable
+### Exercises: Level 2
+
+1. Write a pattern which identifies if a string is a valid python variable
```sh
is_valid_variable('first_name') # True
@@ -424,7 +442,9 @@ distance = 12
is_valid_variable('firstname') # True
```
-4. Clean the following text. After cleaning, count three most frequent words in the string.
+### Exercises: Level 3
+
+1. Clean the following text. After cleaning, count three most frequent words in the string.
```py
sentence = '''%I $am@% a %tea@cher%, &and& I lo%#ve %tea@ching%;. There $is nothing; &as& mo@re rewarding as educa@ting &and& @emp%o@wering peo@ple. ;I found tea@ching m%o@re interesting tha@n any other %jo@bs. %Do@es thi%s mo@tivate yo@u to be a tea@cher!?'''
@@ -434,8 +454,6 @@ distance = 12
print(most_frequent_words(cleaned_text)) # [(3, 'I'), (2, 'teaching'), (2, 'teacher')]
```
-
-
🎉 CONGRATULATIONS ! 🎉
-[<< Day 17](../17_Day/17_exception_handling.md) | [Day 19>>](../19_Day/19_file_handling.md)
\ No newline at end of file
+[<< Day 17](../17_Day_Exception_handling/17_exception_handling.md) | [Day 19>>](../19_Day_File_handling/19_file_handling.md)
diff --git a/19_Day/19_file_handling.md b/19_Day_File_handling/19_file_handling.md
similarity index 76%
rename from 19_Day/19_file_handling.md
rename to 19_Day_File_handling/19_file_handling.md
index 143fe28d0..da1e12bf7 100644
--- a/19_Day/19_file_handling.md
+++ b/19_Day_File_handling/19_file_handling.md
@@ -6,49 +6,49 @@
-
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+Second Edition: July, 2021
-
-
-[<< Day 18](../18_Day/18_regular_expression.md) | [Day 20 >>](../20_Day/20_python_package_manager.md)
+[<< Day 18](../18_Day_Regular_expressions/18_regular_expressions.md) | [Day 20 >>](../20_Day_Python_package_manager/20_python_package_manager.md)

-- [📘 Day 19](#%f0%9f%93%98-day-19)
+- [📘 Day 19](#-day-19)
- [File Handling](#file-handling)
- - [Opening Files for Reading](#opening-file-for-reading)
- - [Opening Files for Writing and Updating](#opening-file-for-writing-and-updating)
+ - [Opening Files for Reading](#opening-files-for-reading)
+ - [Opening Files for Writing and Updating](#opening-files-for-writing-and-updating)
- [Deleting Files](#deleting-files)
- [File Types](#file-types)
- - [Files with txt Extension](#file-with-txt-extension)
- - [Files with json Extension](#file-with-json-extension)
+ - [File with txt Extension](#file-with-txt-extension)
+ - [File with json Extension](#file-with-json-extension)
- [Changing JSON to Dictionary](#changing-json-to-dictionary)
- [Changing Dictionary to JSON](#changing-dictionary-to-json)
- [Saving as JSON File](#saving-as-json-file)
- [File with csv Extension](#file-with-csv-extension)
- [File with xlsx Extension](#file-with-xlsx-extension)
- [File with xml Extension](#file-with-xml-extension)
- - [💻 Exercises: Day 19](#%f0%9f%92%bb-exercises-day-19)
+ - [💻 Exercises: Day 19](#-exercises-day-19)
+ - [Exercises: Level 1](#exercises-level-1)
+ - [Exercises: Level 2](#exercises-level-2)
+ - [Exercises: Level 3](#exercises-level-3)
# 📘 Day 19
## File Handling
-So far we have seen different python data types. We usually store our data in different file formats. In addition to handling files, we will also see different file formats(.txt, .json, .xml, .csv, .tsv, .excel) in this section. First, let's get familiar with handling files with common file format (.txt).
+So far we have seen different Python data types. We usually store our data in different file formats. In addition to handling files, we will also see different file formats(.txt, .json, .xml, .csv, .tsv, .excel) in this section. First, let us get familiar with handling files with common file format(.txt).
-File handling is an import part of programming which allows us to create, read, update and delete files. In python to handle data we use _open()_ built-in function.
+File handling is an import part of programming which allows us to create, read, update and delete files. In Python to handle data we use _open()_ built-in function.
```py
# Syntax
open('filename', mode) # mode(r, a, w, x, t,b) could be to read, write, update
```
-- "r" - Read - Default value. Opens a file for reading, error if the file does not exist
+- "r" - Read - Default value. Opens a file for reading, it returns an error if the file does not exist
- "a" - Append - Opens a file for appending, creates the file if it does not exist
- "w" - Write - Opens a file for writing, creates the file if it does not exist
- "x" - Create - Creates the specified file, returns an error if the file exists
@@ -57,16 +57,16 @@ open('filename', mode) # mode(r, a, w, x, t,b) could be to read, write, update
### Opening Files for Reading
-The default mode of _open_ is reading, so we do not have to specify 'r' or 'rt'. I have created and saved a file named reading_file_example.txt in the files directory. Let's see how it is done:
+The default mode of _open_ is reading, so we do not have to specify 'r' or 'rt'. I have created and saved a file named reading_file_example.txt in the files directory. Let us see how it is done:
```py
f = open('./files/reading_file_example.txt')
print(f) # <_io.TextIOWrapper name='./files/reading_file_example.txt' mode='r' encoding='UTF-8'>
```
-As you can see in the example above, I printed the opened file and it gave me some information about it. Opened file has different reading methods: _read()_, _readline_, _readlines_. An opened file has to be closed with _close()_ method.
+As you can see in the example above, I printed the opened file and it gave some information about it. Opened file has different reading methods: _read()_, _readline_, _readlines_. An opened file has to be closed with _close()_ method.
-- _read()_: read the whole text as string. If we want to limit the number of characters we read, we can limit it by passing int value to the methods.
+- _read()_: read the whole text as string. If we want to limit the number of characters we want to read, we can limit it by passing int value to the *read(number)* method.
```py
f = open('./files/reading_file_example.txt')
@@ -147,7 +147,7 @@ f.close()
['This is an example to show how to open a file and read.', 'This is the second line of the text.']
```
-After we open a file, we should close it. There is a high tendency of forgetting to close them. There is a new way of opening files using _with_ - closes the files by itself. Let's rewrite the the previous example with the _with_ method:
+After we open a file, we should close it. There is a high tendency of forgetting to close them. There is a new way of opening files using _with_ - closes the files by itself. Let us rewrite the the previous example with the _with_ method:
```py
with open('./files/reading_file_example.txt') as f:
@@ -166,10 +166,10 @@ with open('./files/reading_file_example.txt') as f:
To write to an existing file, we must add a mode as parameter to the _open()_ function:
-- "a" - append - will append to the end of the file, if the file does not exist it raise FileNotFoundError.
+- "a" - append - will append to the end of the file, if the file does not exist it creates a new file.
- "w" - write - will overwrite any existing content, if the file does not exist it creates.
-Let's append some text to the file we have been reading:
+Let us append some text to the file we have been reading:
```py
with open('./files/reading_file_example.txt','a') as f:
@@ -197,21 +197,21 @@ If the file does not exist, the remove method will raise an error, so it is good
```py
import os
-if os.path.exist('./files/example.txt'):
+if os.path.exists('./files/example.txt'):
os.remove('./files/example.txt')
else:
- os.remove('The file does not exist')
+ print('The file does not exist')
```
## File Types
### File with txt Extension
-File with _txt_ extension is a very common form of data and we have covered it in the previous section. Let's move to the JSON file
+File with _txt_ extension is a very common form of data and we have covered it in the previous section. Let us move to the JSON file
### File with json Extension
-JSON stands for JavaScript Object Notation. Actually, it's a stringified JavaScript object.
+JSON stands for JavaScript Object Notation. Actually, it is a stringified JavaScript object or Python dictionary.
_Example:_
@@ -250,12 +250,14 @@ person_json = '''{
}'''
# let's change JSON to dictionary
person_dct = json.loads(person_json)
+print(type(person_dct))
print(person_dct)
print(person_dct['name'])
```
```sh
# output
+
{'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'skills': ['JavaScrip', 'React', 'Python']}
Asabeneh
```
@@ -298,7 +300,7 @@ print(person_json)
### Saving as JSON File
-We can also save our data as a json file. Let's save it as a json file using the following steps.
+We can also save our data as a json file. Let us save it as a json file using the following steps. For writing a json file, we use the json.dump() method, it can take dictionary, output file, ensure_ascii and indent.
```py
import json
@@ -323,7 +325,7 @@ CSV stands for comma separated values. CSV is a simple file format used to store
```csv
"name","country","city","skills"
-"Asabeneh","Finland","Helsinki","JavaScrip"
+"Asabeneh","Finland","Helsinki","JavaScript"
```
**Example:**
@@ -331,7 +333,7 @@ CSV stands for comma separated values. CSV is a simple file format used to store
```py
import csv
with open('./files/csv_example.csv') as f:
- csv_reader = csv.reader(f, delimiter=',') # w use, reader method to read csv
+ csv_reader = csv.reader(f, delimiter=',') # we use, reader method to read csv
line_count = 0
for row in csv_reader:
if line_count == 0:
@@ -347,6 +349,7 @@ with open('./files/csv_example.csv') as f:
```sh
# output:
Column names are :name, country, city, skills
+Number of lines: 1
Asabeneh is a teacher. He lives in Finland, Helsinki.
Number of lines: 2
```
@@ -355,6 +358,13 @@ Number of lines: 2
To read excel files we need to install _xlrd_ package. We will cover this after we cover package installing using pip.
+```py
+import xlrd
+excel_book = xlrd.open_workbook('sample.xls')
+print(excel_book.nsheets)
+print(excel_book.sheet_names)
+```
+
### File with xml Extension
XML is another structured data format which looks like HTML. In XML the tags are not predefined. The first line is an XML declaration. The person tag is the root of the XML. The person has a gender attribute.
@@ -396,13 +406,17 @@ field: city
field: skills
```
+🌕 You are making a big progress. Maintain your momentum, keep the good work. Now do some exercises for your brain and muscles.
+
## 💻 Exercises: Day 19
+### Exercises: Level 1
+
1. Write a function which count number of lines and number of words in a text. All the files are in the data the folder:
- a) Read obama_speech.txt file and count number of lines and words
- b) Read michelle_obama_speech.txt file and count number of lines and words
- c) Read donald_speech.txt file and count number of lines and words
- d) Read melina_trump_speech.txt file and count number of lines and words
+ 1) Read obama_speech.txt file and count number of lines and words
+ 2) Read michelle_obama_speech.txt file and count number of lines and words
+ 3) Read donald_speech.txt file and count number of lines and words
+ 4) Read melina_trump_speech.txt file and count number of lines and words
2. Read the countries_data.json data file in data directory, create a function that finds the ten most spoken languages
```py
@@ -433,7 +447,8 @@ field: skills
# Your output should look like this
print(most_populated_countries(filename='./data/countries_data.json', 10))
- [{'country': 'China', 'population': 1377422166},
+ [
+ {'country': 'China', 'population': 1377422166},
{'country': 'India', 'population': 1295210000},
{'country': 'United States of America', 'population': 323947000},
{'country': 'Indonesia', 'population': 258705000},
@@ -442,22 +457,26 @@ field: skills
{'country': 'Nigeria', 'population': 186988000},
{'country': 'Bangladesh', 'population': 161006790},
{'country': 'Russian Federation', 'population': 146599183},
- {'country': 'Japan', 'population': 126960000}]
+ {'country': 'Japan', 'population': 126960000}
+ ]
# Your output should look like this
print(most_populated_countries(filename='./data/countries_data.json', 3))
- [{'country': 'China', 'population': 1377422166},
+ [
+ {'country': 'China', 'population': 1377422166},
{'country': 'India', 'population': 1295210000},
- {'country': 'United States of America', 'population': 323947000}]
+ {'country': 'United States of America', 'population': 323947000}
+ ]
```
-4. Extract all incoming email addresses as a list from the email_exchange_big.txt file.
-5. Find the most common words in the English language. Call the name of your function find_most_common_words, it will take two parameters - a string or a file and a positive integer, indicating the number of words. Your function will return an array of tuples in descending order. Check the output
+### Exercises: Level 2
+
+1. Extract all incoming email addresses as a list from the email_exchange_big.txt file.
+2. Find the most common words in the English language. Call the name of your function find_most_common_words, it will take two parameters - a string or a file and a positive integer, indicating the number of words. Your function will return an array of tuples in descending order. Check the output
```py
# Your output should look like this
-
print(find_most_common_words('sample.txt', 10))
[(10, 'the'),
(8, 'be'),
@@ -480,18 +499,18 @@ field: skills
(5, 'and')]
```
-6. Use the function, find_most_frequent_words to find:
- a) The ten most frequent words used in [Obama's speech](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/obama_speech.txt)
- b) The ten most frequent words used in [Michelle's speech](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/michelle_obama_speech.txt)
- c) The ten most frequent words used in [Trump's speech](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/donald_speech.txt)
- d) The ten most frequent words used in [Melina's speech](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/melina_trump_speech.txt)
-7. Write a python application that checks similarity between two texts. It takes a file or a string as a parameter and it will evaluate the similarity of the two texts. For instance check the similarity between the transcripts of [Michelle's](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/michelle_obama_speech.txt) and [Melina's](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/melina_trump_speech.txt) speech. You may need a couple of functions, function to clean the text(clean_text), function to remove support words(remove_support_words) and finally to check the similarity(check_text_similarity). List of [stop words](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/stop_words.py) are in the data directory
-8. Find the 10 most repeated words in the romeo_and_juliet.txt
-9. Read the [hacker news csv](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/hacker_news.csv) file and find out:
- a) Count the number of lines containing python or Python
- b) Count the number lines containing JavaScript, javascript or Javascript
- c) Count the number lines containing Java and not JavaScript
+3. Use the function, find_most_frequent_words to find:
+ 1) The ten most frequent words used in [Obama's speech](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/obama_speech.txt)
+ 2) The ten most frequent words used in [Michelle's speech](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/michelle_obama_speech.txt)
+ 3) The ten most frequent words used in [Trump's speech](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/donald_speech.txt)
+ 4) The ten most frequent words used in [Melina's speech](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/melina_trump_speech.txt)
+4. Write a python application that checks similarity between two texts. It takes a file or a string as a parameter and it will evaluate the similarity of the two texts. For instance check the similarity between the transcripts of [Michelle's](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/michelle_obama_speech.txt) and [Melina's](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/melina_trump_speech.txt) speech. You may need a couple of functions, function to clean the text(clean_text), function to remove support words(remove_support_words) and finally to check the similarity(check_text_similarity). List of [stop words](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/stop_words.py) are in the data directory
+5. Find the 10 most repeated words in the romeo_and_juliet.txt
+6. Read the [hacker news csv](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/hacker_news.csv) file and find out:
+ 1) Count the number of lines containing python or Python
+ 2) Count the number lines containing JavaScript, javascript or Javascript
+ 3) Count the number lines containing Java and not JavaScript
🎉 CONGRATULATIONS ! 🎉
-[<< Day 18](../18_Day/18_regular_expression.md) | [Day 20 >>](../20_Day/20_python_package_manager.md)
+[<< Day 18](../18_Day_Regular_expressions/18_regular_expressions.md) | [Day 20 >>](../20_Day_Python_package_manager/20_python_package_manager.md)
diff --git a/20_Day/20_python_package_manager.md b/20_Day_Python_package_manager/20_python_package_manager.md
similarity index 73%
rename from 20_Day/20_python_package_manager.md
rename to 20_Day_Python_package_manager/20_python_package_manager.md
index 833a93b66..7b583647c 100644
--- a/20_Day/20_python_package_manager.md
+++ b/20_Day_Python_package_manager/20_python_package_manager.md
@@ -9,21 +9,19 @@
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+Second Edition: July, 2021
-
-
-[<< Day 19](../19_Day/19_file_handling.md) | [Day 21 >>](../21_Day/21_class_and_object.md)
+[<< Day 19](../19_Day_File_handling/19_file_handling.md) | [Day 21 >>](../21_Day_Classes_and_objects/21_classes_and_objects.md)

-- [📘 Day 20](#%f0%9f%93%98-day-20)
+- [📘 Day 20](#-day-20)
- [Python PIP - Python Package Manager](#python-pip---python-package-manager)
- - [What is PIP ?](#what-is-pip)
+ - [What is PIP ?](#what-is-pip-)
- [Installing PIP](#installing-pip)
- - [Installing Packages Using PIP](#installing-packages-using-pip)
+ - [Installing packages using pip](#installing-packages-using-pip)
- [Uninstalling Packages](#uninstalling-packages)
- [List of Packages](#list-of-packages)
- [Show Package](#show-package)
@@ -39,19 +37,19 @@
### What is PIP ?
-PIP stands for Preferred installer program. We use _pip_ to install different python packages.
-Package is a python module that can contain one or more modules or other packages. A module or modules that we can install to our application is a package.
+PIP stands for Preferred installer program. We use _pip_ to install different Python packages.
+Package is a Python module that can contain one or more modules or other packages. A module or modules that we can install to our application is a package.
In programming, we do not have to write every utility program, instead we install packages and import them to our applications.
### Installing PIP
-If you did not install pip, let us do it now. Go to your terminal or command prompt and copy and paste this:
+If you did not install pip, let us install it now. Go to your terminal or command prompt and copy and paste this:
```sh
asabeneh@Asabeneh:~$ pip install pip
```
-Check if it is installed by writing
+Check if pip is installed by writing
```sh
pip --version
@@ -59,16 +57,16 @@ pip --version
```py
asabeneh@Asabeneh:~$ pip --version
-pip 19.3.1 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)
+pip 21.1.3 from /usr/local/lib/python3.7/site-packages/pip (python 3.9.6)
```
-As you can see, I am using pip version 19.3.1, if you see some number a bit below or above that, means you have pip installed.
+As you can see, I am using pip version 21.1.3, if you see some number a bit below or above that, means you have pip installed.
-Let's check some of the packages used in the python community for different purposes. Just to let you know that there are lots of packages available for use with different applications.
+Let us check some of the packages used in the Python community for different purposes. Just to let you know that there are lots of packages available for use with different applications.
### Installing packages using pip
-Let's try to install _numpy_, called numeric python. It is one of the most popular packages in machine learning and data science community.
+Let us try to install _numpy_, called numeric python. It is one of the most popular packages in machine learning and data science community.
- NumPy is the fundamental package for scientific computing with Python. It contains among other things:
- a powerful N-dimensional array object
@@ -80,16 +78,16 @@ Let's try to install _numpy_, called numeric python. It is one of the most popul
asabeneh@Asabeneh:~$ pip install numpy
```
-Lets start using numpy. Open your python interactive shell, write python and then import numpy as follows:
+Let us start using numpy. Open your python interactive shell, write python and then import numpy as follows:
```py
asabeneh@Asabeneh:~$ python
-Python 3.7.5 (default, Nov 1 2019, 02:16:32)
+Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> numpy.version.version
-'1.17.3'
+'1.20.1'
>>> lst = [1, 2, 3,4, 5]
>>> np_arr = numpy.array(lst)
>>> np_arr
@@ -103,7 +101,7 @@ array([3, 4, 5, 6, 7])
>>>
```
-Pandas is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language. Let's install the big brother of numpy, _pandas_:
+Pandas is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language. Let us install the big brother of numpy, _pandas_:
```sh
asabeneh@Asabeneh:~$ pip install pandas
@@ -111,7 +109,7 @@ asabeneh@Asabeneh:~$ pip install pandas
```py
asabeneh@Asabeneh:~$ python
-Python 3.7.5 (default, Nov 1 2019, 02:16:32)
+Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas
@@ -119,7 +117,7 @@ Type "help", "copyright", "credits" or "license" for more information.
This section is not about numpy nor pandas, here we are trying to learn how to install packages and how to import them. If it is needed, we will talk about different packages in other sections.
-Let's import a web browser module, which can help us to open any website. We do not install this module, it is already installed by default with python 3. For instance if you like to open any number of websites at any time or if you like to schedule something, this _webbrowser_ module can be of use.
+Let us import a web browser module, which can help us to open any website. We do not need to install this module, it is already installed by default with Python 3. For instance if you like to open any number of websites at any time or if you like to schedule something, this _webbrowser_ module can be used.
```py
import webbrowser # web browser module to open websites
@@ -128,7 +126,7 @@ import webbrowser # web browser module to open websites
url_lists = [
'http://www.python.org',
'https://www.linkedin.com/in/asabeneh/',
- 'https://twitter.com/Asabeneh',
+ 'https://github.com/Asabeneh',
'https://twitter.com/Asabeneh',
]
@@ -139,7 +137,7 @@ for url in url_lists:
### Uninstalling Packages
-If you do not like to keep the installed packages, you can remove them.
+If you do not like to keep the installed packages, you can remove them using the following command.
```sh
pip uninstall packagename
@@ -164,7 +162,7 @@ pip show packagename
```sh
asabeneh@Asabeneh:~$ pip show pandas
Name: pandas
-Version: 0.25.3
+Version: 1.2.3
Summary: Powerful data structures for data analysis, time series, and statistics
Home-page: http://pandas.pydata.org
Author: None
@@ -180,7 +178,7 @@ If we want even more details, just add --verbose
```sh
asabeneh@Asabeneh:~$ pip show --verbose pandas
Name: pandas
-Version: 0.25.3
+Version: 1.2.3
Summary: Powerful data structures for data analysis, time series, and statistics
Home-page: http://pandas.pydata.org
Author: None
@@ -211,7 +209,7 @@ Entry-points:
### PIP Freeze
-Generate output suitable for a requirements file.
+Generate installed Python packages with their version and the output is suitable to use it in a requirements file. A requirements.txt file is a file that should contain all the installed Python packages in a Python project.
```sh
asabeneh@Asabeneh:~$ pip freeze
@@ -227,9 +225,9 @@ The pip freeze gave us the packages used, installed and their version. We use it
### Reading from URL
By now you are familiar with how to read or write on a file located on you local machine. Sometimes, we would like to read from a website using url or from an API.
-API stands for Application Program Interface. It is a means to exchange structured data between servers primarily as json data. To open a network connection, we need a package called _requests_ - it allows to open a network connection and to implement CRUD(create, read, update and delete) operations. In this section, we will cover only reading part of a CRUD.
+API stands for Application Program Interface. It is a means to exchange structured data between servers primarily as json data. To open a network connection, we need a package called _requests_ - it allows to open a network connection and to implement CRUD(create, read, update and delete) operations. In this section, we will cover only reading ore getting part of a CRUD.
-Let's install _requests_:
+Let us install _requests_:
```py
asabeneh@Asabeneh:~$ pip install requests
@@ -237,11 +235,11 @@ asabeneh@Asabeneh:~$ pip install requests
We will see _get_, _status_code_, _headers_, _text_ and _json_ methods in _requests_ module:
- _get()_: to open a network and fetch data from url - it returns a response object
- - _status_code_: After we fetched data, we can check the status of the operation (succes, error, etc)
+ - _status_code_: After we fetched data, we can check the status of the operation (success, error, etc)
- _headers_: To check the header types
- _text_: to extract the text from the fetched response object
- _json_: to extract json data
-Let's read a txt file form this website, https://www.w3.org/TR/PNG/iso_8859-1.txt.
+Let's read a txt file from this website, https://www.w3.org/TR/PNG/iso_8859-1.txt.
```py
import requests # importing the request module
@@ -261,7 +259,7 @@ print(response.text) # gives all the text from the page
{'date': 'Sun, 08 Dec 2019 18:00:31 GMT', 'last-modified': 'Fri, 07 Nov 2003 05:51:11 GMT', 'etag': '"17e9-3cb82080711c0;50c0b26855880-gzip"', 'accept-ranges': 'bytes', 'cache-control': 'max-age=31536000', 'expires': 'Mon, 07 Dec 2020 18:00:31 GMT', 'vary': 'Accept-Encoding', 'content-encoding': 'gzip', 'access-control-allow-origin': '*', 'content-length': '1616', 'content-type': 'text/plain', 'strict-transport-security': 'max-age=15552000; includeSubdomains; preload', 'content-security-policy': 'upgrade-insecure-requests'}
```
-- Let's read from an api. API stands for Application Program Interface. It is a means to exchange structure data between servers primarily a json data. An example of an api:https://restcountries.eu/rest/v2/all. Let's read this API using _requests_ module.
+- Let us read from an API. API stands for Application Program Interface. It is a means to exchange structure data between servers primarily a json data. An example of an API:https://restcountries.eu/rest/v2/all. Let us read this API using _requests_ module.
```py
import requests
@@ -329,10 +327,10 @@ We use _json()_ method from response object, if the we are fetching JSON data. F
### Creating a Package
-We organize a large number of files in different folders and subfolders based on some criteria, so that we can find and manage them easily. As you know, a module can contain multiple objects, such as classes, functions, etc. A package can contain one or more relevant modules. A package is actually a folder containing one or more module files. Let's create a package named mypackage, using the following steps:
+We organize a large number of files in different folders and sub-folders based on some criteria, so that we can find and manage them easily. As you know, a module can contain multiple objects, such as classes, functions, etc. A package can contain one or more relevant modules. A package is actually a folder containing one or more module files. Let us create a package named mypackage, using the following steps:
-Create a new folder named mypacakge inside 30DaysOfPython folder
-Create an empty **init**.py file in the mypackage folder.
+Create a new folder named mypackage inside 30DaysOfPython folder
+Create an empty **__init__**.py file in the mypackage folder.
Create modules arithmetic.py and greet.py with following code:
```py
@@ -385,11 +383,11 @@ Now let's open the python interactive shell and try the package we have created:
```sh
asabeneh@Asabeneh:~/Desktop/30DaysOfPython$ python
-Python 3.7.5 (default, Nov 1 2019, 02:16:32)
+Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from mypackage import arithmetics
->>> arithmetics.add_numbers(1,2,3,5)
+>>> arithmetics.add_numbers(1, 2, 3, 5)
11
>>> arithmetics.subtract(5, 3)
2
@@ -407,8 +405,8 @@ Type "help", "copyright", "credits" or "license" for more information.
>>>
```
-As you can see our package works perfectly. The package folder contains a special file called **init**.py - it stores the package's content. If we put **init**.py in the package folder, python start recognizes it as a package.
-The **init**.py exposes specified resources from its modules to be imported to other python files. An empty **init**.py file makes all functions available when a package is imported. The **init**.py is essential for the folder to be recognized by Python as a package.
+As you can see our package works perfectly. The package folder contains a special file called **__init__**.py - it stores the package's content. If we put **__init__**.py in the package folder, python start recognizes it as a package.
+The **__init__**.py exposes specified resources from its modules to be imported to other python files. An empty **__init__**.py file makes all functions available when a package is imported. The **__init__**.py is essential for the folder to be recognized by Python as a package.
### Further Information About Packages
@@ -418,10 +416,9 @@ The **init**.py exposes specified resources from its modules to be imported to o
- Web Development
- Django - High-level web framework.
- _pip install django_
- - Flask - microframework for Python based on Werkzeug, Jinja 2. (It's BSD licensed)
+ - Flask - micro framework for Python based on Werkzeug, Jinja 2. (It's BSD licensed)
- _pip install flask_
- HTML Parser
-
- [Beautiful Soup](https://www.crummy.com/software/BeautifulSoup/bs4/doc/) - HTML/XML parser designed for quick turnaround projects like screen-scraping, will accept bad markup.
- _pip install beautifulsoup4_
- PyQuery - implements jQuery in Python; faster than BeautifulSoup, apparently.
@@ -433,7 +430,7 @@ The **init**.py exposes specified resources from its modules to be imported to o
- TkInter - The traditional Python user interface toolkit.
- Data Analysis, Data Science and Machine learning
- Numpy: Numpy(numeric python) is known as one of the most popular machine learning library in Python.
- - Pandas: is a machine learning library in Python that provides data structures of high-level and a wide variety of tools for analysis.
+ - Pandas: is a data analysis, data science and a machine learning library in Python that provides data structures of high-level and a wide variety of tools for analysis.
- SciPy: SciPy is a machine learning library for application developers and engineers. SciPy library contains modules for optimization, linear algebra, integration, image processing, and statistics.
- Scikit-Learn: It is NumPy and SciPy. It is considered as one of the best libraries for working with complex data.
- TensorFlow: is a machine learning library built by Google.
@@ -442,13 +439,21 @@ The **init**.py exposes specified resources from its modules to be imported to o
- requests: is a package which we can use to send requests to a server(GET, POST, DELETE, PUT)
- _pip install requests_
+🌕 You are always progressing and you are a head of 20 steps to your way to greatness. Now do some exercises for your brain and muscles.
+
## Exercises: Day 20
-1. Read this url and find the 10 most frequent words. Romeo_and_juliet = 'http://www.gutenberg.org/files/1112/1112.txt'
-2. Read the cats api and cats_api = 'https://api.thecatapi.com/v1/breeds' and find the avarage weight of a cat in metric units.
-3. Read the countries api and find the 10 largest countries
-4. UCI is one the most common places to get data sets for data science and machine learning. Read the content of UCL (http://mlr.cs.umass.edu/ml/datasets.html). Without additional libraries it will be difficult, so you may try it with BeautifulSoup4
+1. Read this url and find the 10 most frequent words. romeo_and_juliet = 'http://www.gutenberg.org/files/1112/1112.txt'
+2. Read the cats API and cats_api = 'https://api.thecatapi.com/v1/breeds' and find :
+ 1. the min, max, mean, median, standard deviation of cats' weight in metric units.
+ 2. the min, max, mean, median, standard deviation of cats' lifespan in years.
+ 3. Create a frequency table of country and breed of cats
+3. Read the [countries API](https://restcountries.eu/rest/v2/all) and find
+ 1. the 10 largest countries
+ 2. the 10 most spoken languages
+ 3. the total number of languages in the countries API
+4. UCI is one of the most common places to get data sets for data science and machine learning. Read the content of UCL (https://archive.ics.uci.edu/ml/datasets.php). Without additional libraries it will be difficult, so you may try it with BeautifulSoup4
🎉 CONGRATULATIONS ! 🎉
-[<< Day 19](../19_Day/19_file_handling.md) | [Day 21 >>](../21_Day/21_class_and_object.md)
+[<< Day 19](../19_Day_File_handling/19_file_handling.md) | [Day 21 >>](../21_Day_Classes_and_objects/21_classes_and_objects.md)
diff --git a/20_Day_Python_package_manager/__init__.py b/20_Day_Python_package_manager/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/20_Day_Python_package_manager/arithmetic.py b/20_Day_Python_package_manager/arithmetic.py
new file mode 100644
index 000000000..bdb5c1fb2
--- /dev/null
+++ b/20_Day_Python_package_manager/arithmetic.py
@@ -0,0 +1,25 @@
+def add_numbers(*args):
+ total = 0
+ for num in args:
+ total += num
+ return total
+
+
+def subtract(a, b):
+ return (a - b)
+
+
+def multiple(a, b):
+ return a * b
+
+
+def division(a, b):
+ return a / b
+
+
+def remainder(a, b):
+ return a % b
+
+
+def power(a, b):
+ return a ** b
\ No newline at end of file
diff --git a/20_Day_Python_package_manager/greet.py b/20_Day_Python_package_manager/greet.py
new file mode 100644
index 000000000..997787d11
--- /dev/null
+++ b/20_Day_Python_package_manager/greet.py
@@ -0,0 +1,2 @@
+def greet_person(firstname, lastname):
+ return f'{firstname} {lastname}, welcome to 30DaysOfPython Challenge!'
\ No newline at end of file
diff --git a/21_Day/21_class_and_object.md b/21_Day_Classes_and_objects/21_classes_and_objects.md
similarity index 72%
rename from 21_Day/21_class_and_object.md
rename to 21_Day_Classes_and_objects/21_classes_and_objects.md
index 89e9a8062..7e0e85198 100644
--- a/21_Day/21_class_and_object.md
+++ b/21_Day_Classes_and_objects/21_classes_and_objects.md
@@ -9,17 +9,16 @@
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+Second Edition: July, 2021
-
-[<< Day 20](../20_Day/20_python_package_manager.md) | [Day 22 >>](../22_Day/22_web_scraping.md)
+[<< Day 20](../20_Day_Python_package_manager/20_python_package_manager.md) | [Day 22 >>](../22_Day_Web_scraping/22_web_scraping.md)

-- [📘 Day 21](#%f0%9f%93%98-day-21)
+- [📘 Day 21](#-day-21)
- [Classes and Objects](#classes-and-objects)
- [Creating a Class](#creating-a-class)
- [Creating an Object](#creating-an-object)
@@ -28,24 +27,24 @@
- [Object Default Methods](#object-default-methods)
- [Method to Modify Class Default Values](#method-to-modify-class-default-values)
- [Inheritance](#inheritance)
- - [Overriding Parent Method](#overriding-parent-method)
- - [💻 Exercises: Day 21](#%f0%9f%92%bb-exercises-day-21)
+ - [Overriding parent method](#overriding-parent-method)
+ - [💻 Exercises: Day 21](#-exercises-day-21)
+ - [Exercises: Level 1](#exercises-level-1)
+ - [Exercises: Level 2](#exercises-level-2)
+ - [Exercises: Level 3](#exercises-level-3)
# 📘 Day 21
## Classes and Objects
-Python is an object oriented programming language. Everything in Python is an object, with its properties and methods. A number, string, list, dictionary, tuple, set etc. used in a program is an object of a corresponding built-in class. We create class to create an object. A Class is like an object constructor, or a "blueprint" for creating objects. We instantiate a class to create an object. The class defines attributes and the behavior of the object, while the object, on the other hand, represents the class.
+Python is an object oriented programming language. Everything in Python is an object, with its properties and methods. A number, string, list, dictionary, tuple, set etc. used in a program is an object of a corresponding built-in class. We create class to create an object. A class is like an object constructor, or a "blueprint" for creating objects. We instantiate a class to create an object. The class defines attributes and the behavior of the object, while the object, on the other hand, represents the class.
We have been working with classes and objects right from the beginning of this challenge unknowingly. Every element in a Python program is an object of a class.
-Let's check if everything in python is a class:
+Let us check if everything in python is a class:
```py
-Last login: Tue Dec 10 09:35:28 on console
-asabeneh@Asabeneh:~$ pyhton
--bash: pyhton: command not found
asabeneh@Asabeneh:~$ python
-Python 3.7.5 (default, Nov 1 2019, 02:16:32)
+Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> num = 10
@@ -86,6 +85,7 @@ class ClassName:
```py
class Person:
pass
+print(Person)
```
```sh
@@ -103,12 +103,13 @@ print(p)
### Class Constructor
-In the examples above, we have created an object from the Person class. However, Class without a constructor is not really useful in real applications. Let's use constructor function to make our class more useful. Like the constructor function in Java or JavaScript, python has also a built-in _**init**()_ constructor function. The _**init**_ constructor function has self parameter which is a reference to the current instance of the class
+In the examples above, we have created an object from the Person class. However, a class without a constructor is not really useful in real applications. Let us use constructor function to make our class more useful. Like the constructor function in Java or JavaScript, Python has also a built-in **__init__**() constructor function. The **__init__** constructor function has self parameter which is a reference to the current instance of the class
**Examples:**
```py
class Person:
def __init__ (self, name):
+ # self allows to attach parameter to the class
self.name =name
p = Person('Asabeneh')
@@ -122,7 +123,7 @@ Asabeneh
<__main__.Person object at 0x2abf46907e80>
```
-Let's add more parameters to the constructor function.
+Let us add more parameters to the constructor function.
```py
class Person:
@@ -165,11 +166,9 @@ class Person:
self.age = age
self.country = country
self.city = city
-
def person_info(self):
return f'{self.firstname} {self.lastname} is {self.age} years old. He lives in {self.city}, {self.country}'
-
p = Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')
print(p.person_info())
```
@@ -181,7 +180,7 @@ Asabeneh Yetayeh is 250 years old. He lives in Helsinki, Finland
### Object Default Methods
-Sometimes, you may want to have a default values for you object methods. If we give default values for the parameters in the constructor, we can avoid errors when we call or instantiate our class without parameters. Let's see how it looks:
+Sometimes, you may want to have default values for your object methods. If we give default values for the parameters in the constructor, we can avoid errors when we call or instantiate our class without parameters. Let's see how it looks:
**Example:**
@@ -211,7 +210,7 @@ John Doe is 30 years old. He lives in Noman city, Nomanland.
### Method to Modify Class Default Values
-In the example below, the person class, all the constructor parameters have default values. In addition to that, we have skills parameter, which we can access using a method. Let's create add_skill method to add skills to the skills list.
+In the example below, the person class, all the constructor parameters have default values. In addition to that, we have skills parameter, which we can access using a method. Let us create add_skill method to add skills to the skills list.
```py
class Person:
@@ -249,8 +248,8 @@ John Doe is 30 years old. He lives in Noman city, Nomanland.
### Inheritance
-Using inheritance we can reuse parent class code. Inheritance allows us to define a class that inherits all the methods and properties from another class. The parent class or super or base class is the class which gives all the methods and properties. Child class is the class that inherits from another class.
-Let's create a student class by inheriting from person class.
+Using inheritance we can reuse parent class code. Inheritance allows us to define a class that inherits all the methods and properties from parent class. The parent class or super or base class is the class which gives all the methods and properties. Child class is the class that inherits from another or parent class.
+Let us create a student class by inheriting from person class.
```py
class Student(Person):
@@ -281,8 +280,8 @@ Lidiya Teklemariam is 28 years old. He lives in Espoo, Finland.
['Organizing', 'Marketing', 'Digital Marketing']
```
-We didn't call the _**init**()_ constructor in the child class. If we didn't call it then we can still access all the properties from the parent. But if we do call the constructor we can access the parent properties by calling _super_.
-We can add a new method to the child or we can overwrite the parent class by creating the same method name in the child class. When we add the **init**() function, the child class will no longer inherit the parent's **init**() function.
+We did not call the **__init__**() constructor in the child class. If we didn't call it then we can still access all the properties from the parent. But if we do call the constructor we can access the parent properties by calling _super_.
+We can add a new method to the child or we can override the parent class methods by creating the same method name in the child class. When we add the **__init__**() function, the child class will no longer inherit the parent's **__init__**() function.
### Overriding parent method
@@ -317,11 +316,15 @@ Lidiya Teklemariam is 28 years old. She lives in Espoo, Finland.
['Organizing', 'Marketing', 'Digital Marketing']
```
-We can use super() function or the parent name Person to automatically inherit the methods and properties from its parent. In the example above we override the parant method. The child method has a different feature, it can identify, if the gender is male or female and assign the proper pronoun(He/She).
+We can use super() built-in function or the parent name Person to automatically inherit the methods and properties from its parent. In the example above we override the parent method. The child method has a different feature, it can identify, if the gender is male or female and assign the proper pronoun(He/She).
+
+🌕 Now, you are fully charged with a super power of programming. Now do some exercises for your brain and muscles.
## 💻 Exercises: Day 21
-1. Python has the module called _statistics_ and we can use this module to do all the statistical caluculations. However to challlenge ourselves, let's try to develop a program, which calculates the measure of central tendency of a sample (mean, median, mode) and measure of variability (range, variance, standard deviation). In addition to those measures, find the min, max, count, percentile, and frequency distribution of the sample. You can create a class called Statistics and create all the functions that do statistical calculations as methods for the Statistics class. Check the output below.
+### Exercises: Level 1
+
+1. Python has the module called _statistics_ and we can use this module to do all the statistical calculations. However, to learn how to make function and reuse function let us try to develop a program, which calculates the measure of central tendency of a sample (mean, median, mode) and measure of variability (range, variance, standard deviation). In addition to those measures, find the min, max, count, percentile, and frequency distribution of the sample. You can create a class called Statistics and create all the functions that do statistical calculations as methods for the Statistics class. Check the output below.
```py
ages = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26]
@@ -330,11 +333,10 @@ print('Count:', data.count()) # 25
print('Sum: ', data.sum()) # 744
print('Min: ', data.min()) # 24
print('Max: ', data.max()) # 38
-print('Range: ', data.range() # 14
+print('Range: ', data.range()) # 14
print('Mean: ', data.mean()) # 30
print('Median: ', data.median()) # 29
print('Mode: ', data.mode()) # {'mode': 26, 'count': 5}
-print('Variance: ', data.var()) # 17.5
print('Standard Deviation: ', data.std()) # 4.2
print('Variance: ', data.var()) # 17.5
print('Frequency Distribution: ', data.freq_dist()) # [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
@@ -356,8 +358,10 @@ Standard Deviation: 4.2
Frequency Distribution: [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
```
-2. Create a class called PersonAccount. It has firstname, lastname, incomes, expenses properties and it has total_income, total_expense, account_info, add_income, add_expense and account_balance methods. Incomes is a set of incomes and its description. The same goes for expenses.
+### Exercises: Level 2
+
+1. Create a class called PersonAccount. It has firstname, lastname, incomes, expenses properties and it has total_income, total_expense, account_info, add_income, add_expense and account_balance methods. Incomes is a set of incomes and its description. The same goes for expenses.
🎉 CONGRATULATIONS ! 🎉
-[<< Day 20](../20_Day/20_python_package_manager.md) | [Day 22 >>](../22_Day/22_web_scraping.md)
+[<< Day 20](../20_Day_Python_package_manager/20_python_package_manager.md) | [Day 22 >>](../22_Day_Web_scraping/22_web_scraping.md)
diff --git a/22_Day/22_web_scraping.md b/22_Day_Web_scraping/22_web_scraping.md
similarity index 72%
rename from 22_Day/22_web_scraping.md
rename to 22_Day_Web_scraping/22_web_scraping.md
index da1014ad1..5c6a69bc9 100644
--- a/22_Day/22_web_scraping.md
+++ b/22_Day_Web_scraping/22_web_scraping.md
@@ -9,20 +9,18 @@
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+ Second Edition: July, 2021
-
-
-[<< Day 21](../21_Day/21_class_and_object.md) | [Day 23 >>](../23_Day/23_virtual_environment.md)
+[<< Day 21](../21_Day_Classes_and_objects/21_classes_and_objects.md) | [Day 23 >>](../23_Day_Virtual_environment/23_virtual_environment.md)

-- [📘 Day 22](#%f0%9f%93%98-day-22)
+- [📘 Day 22](#-day-22)
- [Python Web Scraping](#python-web-scraping)
- [What is Web Scrapping](#what-is-web-scrapping)
- - [💻 Exercises: Day 22](#%f0%9f%92%bb-exercises-day-22)
+ - [💻 Exercises: Day 22](#-exercises-day-22)
# 📘 Day 22
@@ -36,28 +34,28 @@ Web scraping is the process of extracting and collecting data from websites and
In this section, we will use beautifulsoup and requests package to scrape data. The package version we are using is beautifulsoup 4.
-To start scraping websites you need _requests_, _beautifoulSoup4_ and _website_.
+To start scraping websites you need _requests_, _beautifoulSoup4_ and a _website_.
```sh
pip install requests
pip install beautifulsoup4
```
-To scrape data from websites, basic understanding of HTML tags and css selectors is needed. We target content from a website using HTML tags, classes or/and ids.
-Let's import the requests and BeautifulSoup module
+To scrape data from websites, basic understanding of HTML tags and CSS selectors is needed. We target content from a website using HTML tags, classes or/and ids.
+Let us import the requests and BeautifulSoup module
```py
import requests
from bs4 import BeautifulSoup
```
-Let's declare url variable for the website which we are going to scrape.
+Let us declare url variable for the website which we are going to scrape.
```py
import requests
from bs4 import BeautifulSoup
-url = 'http://mlr.cs.umass.edu/ml/datasets.html'
+url = 'https://archive.ics.uci.edu/ml/datasets.php'
# Lets use the requests get method to fetch the data from url
@@ -76,7 +74,7 @@ Using beautifulSoup to parse content from the page
```py
import requests
from bs4 import BeautifulSoup
-url = 'http://mlr.cs.umass.edu/ml/datasets.html'
+url = 'https://archive.ics.uci.edu/ml/datasets.php'
response = requests.get(url)
content = response.content # we get all the content from the website
@@ -97,11 +95,14 @@ for td in table.find('tr').find_all('td'):
If you run this code, you can see that the extraction is half done. You can continue doing it because it is part of exercise 1.
For reference check the [beautifulsoup documentation](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#quick-start)
+🌕 You are so special, you are progressing everyday. You are left with only eight days to your way to greatness. Now do some exercises for your brain and muscles.
+
## 💻 Exercises: Day 22
-1. Extract the table in this url (http://mlr.cs.umass.edu/ml/datasets.html) and change it to a json file
-2. Scrape the presidents table and store the data as json(https://en.wikipedia.org/wiki/List_of_presidents_of_the_United_States)
+1. Scrape the following website and store the data as json file(url = 'http://www.bu.edu/president/boston-university-facts-stats/').
+1. Extract the table in this url (https://archive.ics.uci.edu/ml/datasets.php) and change it to a json file
+2. Scrape the presidents table and store the data as json(https://en.wikipedia.org/wiki/List_of_presidents_of_the_United_States). The table is not very structured and the scrapping may take very long time.
🎉 CONGRATULATIONS ! 🎉
-[<< Day 21](../21_Day/21_class_and_object.md) | [Day 23 >>](../23_Day/23_virtual_environment.md)
+[<< Day 21](../21_Day_Web_scraping/21_class_and_object.md) | [Day 23 >>](../23_Day_Virtual_environment/23_virtual_environment.md)
diff --git a/22_Day_Web_scraping/scrapped_data.json b/22_Day_Web_scraping/scrapped_data.json
new file mode 100644
index 000000000..5a1f226e5
--- /dev/null
+++ b/22_Day_Web_scraping/scrapped_data.json
@@ -0,0 +1,73 @@
+[
+ {
+ "category": "Community",
+ "Student Body": "34,589",
+ "Living Alumni": "398,195",
+ "Total Employees": "10,517",
+ "Faculty": "4,171",
+ "Nondegree Students": "2,008",
+ "Graduate & Professional Students": "15,645",
+ "Undergraduate Students": "16,936"
+ },
+ {
+ "category": "Campus",
+ "Classrooms": "834",
+ "Buildings": "370",
+ "Laboratories": "1,681",
+ "Libraries": "21",
+ "Campus Area (acres)": "169"
+ },
+ {
+ "category": "Academics",
+ "Study Abroad Programs": "70+",
+ "Average Class Size": "27",
+ "Faculty": "4,171",
+ "Student/Faculty Ratio": "10:1",
+ "Schools and Colleges": "17",
+ "Programs of Study": "300+"
+ },
+ {
+ "category": "Grant & Contract Awards",
+ "Research Awards": "$574.1M",
+ "BMC Clinical Research Grants": "$88.0M"
+ },
+ {
+ "category": "Undergraduate Financial Aid & Scholarships",
+ "Average Total Need-Based Financial Aid": "$46,252",
+ "Average Need-Based Grant/Scholarship": "$40,969",
+ "Grants & Scholarships (need-based)": "$275.6M",
+ "Grants & Scholarships (non-need-based)": "$28.7M"
+ },
+ {
+ "category": "Student Life",
+ "Community Service Hours": "1.6M+",
+ "Alternative Service Breaks Participants": "300+",
+ "BU on Social": "new accounts daily",
+ "Cultural & Religious Organizations": "60+",
+ "Community Service & Justice Organizations": "80+",
+ "Academic & Professional Organizations": "120+",
+ "Art & Performance Organizations": "60+",
+ "Student Organizations": "450+",
+ "First-Year Student Outreach Project Volunteers": "800+"
+ },
+ {
+ "category": "Research",
+ "Faculty Publications": "6,000+",
+ "Student UROP Participants": "450+",
+ "Centers & Institutes": "130+"
+ },
+ {
+ "category": "International Community",
+ "Global Initiatives": "300+",
+ "Cultural Student Groups": "40+",
+ "Alumni Countries": "180+",
+ "International Students": "11,000+"
+ },
+ {
+ "category": "Athletics",
+ "Intramural Sports & Tournaments": "15+",
+ "Club and Intramural Sports Participants": "7,000+",
+ "Club Sports Teams": "50",
+ "Varsity Sports": "24"
+ }
+]
\ No newline at end of file
diff --git a/23_Day/23_virtual_environment.md b/23_Day_Virtual_environment/23_virtual_environment.md
similarity index 71%
rename from 23_Day/23_virtual_environment.md
rename to 23_Day_Virtual_environment/23_virtual_environment.md
index 92c19570e..d23b45ce0 100644
--- a/23_Day/23_virtual_environment.md
+++ b/23_Day_Virtual_environment/23_virtual_environment.md
@@ -9,19 +9,17 @@
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+ Second Edition: July, 2021
-
-
-[<< Day 22](../22_Day/22_web_scraping.md) | [Day 24 >>](../24_Day/24_statistics.md)
+[<< Day 22](../22_Day_Web_scraping/22_web_scraping.md) | [Day 24 >>](../24_Day_Statistics/24_statistics.md)

-- [📘 Day 23](#%f0%9f%93%98-day-23)
+- [📘 Day 23](#-day-23)
- [Setting up Virtual Environments](#setting-up-virtual-environments)
- - [💻 Exercises: Day 23](#%f0%9f%92%bb-exercises-day-23)
+ - [💻 Exercises: Day 23](#-exercises-day-23)
# 📘 Day 23
@@ -30,9 +28,11 @@
To start with project, it would be better to have a virtual environment. Virtual environment can help us to create an isolated or separate environment. This will help us to avoid conflicts in dependencies across projects. If you write pip freeze on your terminal you will see all the installed packages on your computer. If we use virtualenv, we will access only packages which are specific for that project. Open your terminal and install virtualenv
```sh
-asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ pip install virtualenv
+asabeneh@Asabeneh:~$ pip install virtualenv
```
+Inside the 30DaysOfPython folder create a flask_project folder.
+
After installing the virtualenv package go to your project folder and create a virtual env by writing:
For Mac/Linux:
@@ -43,27 +43,33 @@ asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project\$ virtualenv venv
For Windows:
```sh
-C:\Users\User\Documents\30DaysOfPython\flask_project>python3 -m venv venv
+C:\Users\User\Documents\30DaysOfPython\flask_project>python -m venv venv
```
-I prefer to call the new project venv, but feel free to name it differently. Let's check if the the venv was created by using ls (or dir for windows command prompt) command.
+I prefer to call the new project venv, but feel free to name it differently. Let us check if the the venv was created by using ls (or dir for windows command prompt) command.
```sh
asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ ls
venv/
```
-Let's activate the virtual environment by writing the following command at our project folder.
+Let us activate the virtual environment by writing the following command at our project folder.
For Mac/Linux:
```sh
asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ source venv/bin/activate
```
-For Windows:
+Activation of the virtual environment in Windows may very on Windows Power shell and git bash.
+
+For Windows Power Shell:
```sh
C:\Users\User\Documents\30DaysOfPython\flask_project> venv\Scripts\activate
```
+For Windows Git bash:
+```sh
+C:\Users\User\Documents\30DaysOfPython\flask_project> venv\Scripts\. activate
+```
After you write the activation command, your project directory will start with venv. See the example below.
@@ -73,13 +79,13 @@ After you write the activation command, your project directory will start with v
Now, lets check the available packages in this project by writing pip freeze. You will not see any packages.
-We are going to do a small flask project so let's install flask to this project.
+We are going to do a small flask project so let us install flask package to this project.
```sh
(venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ pip install Flask
```
-Now, let's write pip freeze to see a list of installed packages in the project:
+Now, let us write pip freeze to see a list of installed packages in the project:
```sh
(venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ pip freeze
@@ -104,4 +110,5 @@ The necessary modules to work with flask are installed. Now, your project direct
1. Create a project directory with a virtual environment based on the example given above.
🎉 CONGRATULATIONS ! 🎉
-[<< Day 22](../22_Day/22_web_scraping.md) | [Day 24 >>](../24_Day/24_statistics.md)
+
+[<< Day 22](../22_Day_Web_scraping/22_web_scraping.md) | [Day 24 >>](../24_Day_Statistics/24_statistics.md)
diff --git a/24_Day/24_statistics.md b/24_Day/24_statistics.md
deleted file mode 100644
index 3e42e0eca..000000000
--- a/24_Day/24_statistics.md
+++ /dev/null
@@ -1,63 +0,0 @@
-
-
30 Days Of Python: Day 24 - Statistics
-
-
-
-
Author:
-Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
-
-
-
-
-
-[<< Day 23](../23_Day/23_virtual_environment.md) | [Day 25 >>](../25_Day/25_pandas.md)
-
-
-
-- [📘 Day 24](#%f0%9f%93%98-day-24)
- - [Python for Statistical Analysis](#python-for-statistical-analysis)
- - [Statistics](#statistics)
- - [Data](#data)
- - [Statistics Module](#statistics-module)
-- [NumPy](#numpy)
-
-# 📘 Day 24
-
-## Python for Statistical Analysis
-
-## Statistics
-
-Statistics is the discipline that studies the _collection_, _organization_, _displaying_, _analysis_, _interpretation_ and _presentation_ of data.
-Statistics is a branch of mathematics that is recommended to be a prerequisite for data science and machine learning. Statistics is a very broad field but we will focus in this section only on the most relevant part.
-After completing this challenge, you may go onto the web development, data analysis, machine learning and data science path. Whatever path you may follow, at some point in your career you will get data which you may work on. Having some statistical knowledge will help you to make decisions based on data, _data tells as they say_.
-
-## Data
-
-What is data? Data is any set of characters that is gathered and translated for some purpose, usually analysis. It can be any character, including text and numbers, pictures, sound, or video. If data is not put in a context, it doesn't make any sense to a human or computer. To make sense from data we need to work on the data using different tools.
-
-The work flow of data analysis, data science or machine learning starts from data. Data can be provided from some data source or it can be created. There are structured and unstructured data.
-
-Data can be found in small or big format. Most of the data types we will get have been covered in the file handling section.
-
-## Statistics Module
-
-The python _statistics_ module provides functions for calculating mathematical statistics of numerical data. The module is not intended to be a competitor to third-party libraries such as NumPy, SciPy, or proprietary full-featured statistics packages aimed at professional statisticians such as Minitab, SAS and Matlab. It is aimed at the level of graphing and scientific calculators.
-
-# NumPy
-
-In the first section we defined python as a great general-purpose programming language on its own, but with the help of other popular libraries (numpy, scipy, matplotlib, pandas etc) it becomes a powerful environment for scientific computing.
-
-Numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with arrays.
-
-So far, we have been using vscode but from now on I would recommend using Jupyter Notebook. To access jupter notebook let's install [anaconda](https://www.anaconda.com/). If you are using anaconda, most of the common packages are included, so you don't have to install more packages.
-
-[continue](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/numpy.md)
-
-🎉 CONGRATULATIONS ! 🎉
-
-[<< Day 23](../23_Day/23_virtual_environment.md) | [Day 25 >>](../25_Day/25_pandas.md)
diff --git a/24_Day_Statistics/24_statistics.md b/24_Day_Statistics/24_statistics.md
new file mode 100644
index 000000000..70ffaddf7
--- /dev/null
+++ b/24_Day_Statistics/24_statistics.md
@@ -0,0 +1,1240 @@
+
+
30 Days Of Python: Day 24 - Statistics
+
+
+
+
Author:
+Asabeneh Yetayeh
+Second Edition: July, 2021
+
+
+
+[<< Day 23](../23_Day_Virtual_environment/23_virtual_environment.md) | [Day 25 >>](../25_Day_Pandas/25_pandas.md)
+
+
+
+- [📘 Day 24](#-day-24)
+ - [Python for Statistical Analysis](#python-for-statistical-analysis)
+ - [Statistics](#statistics)
+ - [Data](#data)
+ - [Statistics Module](#statistics-module)
+- [NumPy](#numpy)
+
+# 📘 Day 24
+
+## Python for Statistical Analysis
+
+## Statistics
+
+Statistics is the discipline that studies the _collection_, _organization_, _displaying_, _analysing_, _interpretation_ and _presentation_ of data.
+Statistics is a branch of Mathematics that is recommended to be a prerequisite for data science and machine learning. Statistics is a very broad field but we will focus in this section only on the most relevant part.
+After completing this challenge, you may go onto the web development, data analysis, machine learning and data science path. Whatever path you may follow, at some point in your career you will get data which you may work on. Having some statistical knowledge will help you to make decisions based on data, _data tells as they say_.
+
+## Data
+
+What is data? Data is any set of characters that is gathered and translated for some purpose, usually analysis. It can be any character, including text and numbers, pictures, sound, or video. If data is not put in a context, it doesn't make any sense to a human or computer. To make sense from data we need to work on the data using different tools.
+
+The work flow of data analysis, data science or machine learning starts from data. Data can be provided from some data source or it can be created. There are structured and unstructured data.
+
+Data can be found in small or big format. Most of the data types we will get have been covered in the file handling section.
+
+## Statistics Module
+
+The Python _statistics_ module provides functions for calculating mathematical statistics of numerical data. The module is not intended to be a competitor to third-party libraries such as NumPy, SciPy, or proprietary full-featured statistics packages aimed at professional statisticians such as Minitab, SAS and Matlab. It is aimed at the level of graphing and scientific calculators.
+
+# NumPy
+
+In the first section we defined Python as a great general-purpose programming language on its own, but with the help of other popular libraries as(numpy, scipy, matplotlib, pandas etc) it becomes a powerful environment for scientific computing.
+
+NumPy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with arrays.
+
+So far, we have been using vscode but from now on I would recommend using Jupyter Notebook. To access jupyter notebook let's install [anaconda](https://www.anaconda.com/). If you are using anaconda most of the common packages are included and you don't have install packages if you installed anaconda.
+
+```sh
+asabeneh@Asabeneh:~/Desktop/30DaysOfPython$ pip install numpy
+```
+
+## Importing NumPy
+
+Jupyter notebook is available if your are in favor of [jupyter notebook](https://github.com/Asabeneh/data-science-for-everyone/blob/master/numpy/numpy.ipynb)
+
+```py
+ # How to import numpy
+ import numpy as np
+ # How to check the version of the numpy package
+ print('numpy:', np.__version__)
+ # Checking the available methods
+ print(dir(np))
+```
+
+## Creating numpy array using
+
+### Creating int numpy arrays
+
+```py
+ # Creating python List
+ python_list = [1,2,3,4,5]
+
+ # Checking data types
+ print('Type:', type (python_list)) #
+ #
+ print(python_list) # [1, 2, 3, 4, 5]
+
+ two_dimensional_list = [[0,1,2], [3,4,5], [6,7,8]]
+
+ print(two_dimensional_list) # [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
+
+ # Creating Numpy(Numerical Python) array from python list
+
+ numpy_array_from_list = np.array(python_list)
+ print(type (numpy_array_from_list)) #
+ print(numpy_array_from_list) # array([1, 2, 3, 4, 5])
+```
+
+### Creating float numpy arrays
+
+Creating a float numpy array from list with a float data type parameter
+
+```py
+ # Python list
+ python_list = [1,2,3,4,5]
+
+ numy_array_from_list2 = np.array(python_list, dtype=float)
+ print(numy_array_from_list2) # array([1., 2., 3., 4., 5.])
+```
+
+### Creating boolean numpy arrays
+
+Creating a boolean a numpy array from list
+
+```py
+ numpy_bool_array = np.array([0, 1, -1, 0, 0], dtype=bool)
+ print(numpy_bool_array) # array([False, True, True, False, False])
+```
+
+### Creating multidimensional array using numpy
+
+A numpy array may have one or multiple rows and columns
+
+```py
+ two_dimensional_list = [[0,1,2], [3,4,5], [6,7,8]]
+ numpy_two_dimensional_list = np.array(two_dimensional_list)
+ print(type (numpy_two_dimensional_list))
+ print(numpy_two_dimensional_list)
+```
+
+```sh
+
+ [[0 1 2]
+ [3 4 5]
+ [6 7 8]]
+```
+
+### Converting numpy array to list
+
+```python
+# We can always convert an array back to a python list using tolist().
+np_to_list = numpy_array_from_list.tolist()
+print(type (np_to_list))
+print('one dimensional array:', np_to_list)
+print('two dimensional array: ', numpy_two_dimensional_list.tolist())
+```
+
+```sh
+
+ one dimensional array: [1, 2, 3, 4, 5]
+ two dimensional array: [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
+```
+
+### Creating numpy array from tuple
+
+```py
+# Numpy array from tuple
+# Creating tuple in Python
+python_tuple = (1,2,3,4,5)
+print(type (python_tuple)) #
+print('python_tuple: ', python_tuple) # python_tuple: (1, 2, 3, 4, 5)
+
+numpy_array_from_tuple = np.array(python_tuple)
+print(type (numpy_array_from_tuple)) #
+print('numpy_array_from_tuple: ', numpy_array_from_tuple) # numpy_array_from_tuple: [1 2 3 4 5]
+```
+
+### Shape of numpy array
+
+The shape method provide the shape of the array as a tuple. The first is the row and the second is the column. If the array is just one dimensional it returns the size of the array.
+
+```py
+ nums = np.array([1, 2, 3, 4, 5])
+ print(nums)
+ print('shape of nums: ', nums.shape)
+ numpy_two_dimensional_list = np.array([[0,1,2],[3,4,5],[6,7,8]])
+ print(numpy_two_dimensional_list)
+ print('shape of numpy_two_dimensional_list: ', numpy_two_dimensional_list.shape)
+ three_by_four_array = np.array([[0, 1, 2, 3],
+ [4,5,6,7],
+ [8,9,10,11]]
+ print(three_by_four_array)
+ print('shape of three_by_four_array: ', three_by_four_array.shape)
+
+```
+
+```sh
+ [1 2 3 4 5]
+ shape of nums: (5,)
+ [[0 1 2]
+ [3 4 5]
+ [6 7 8]]
+ shape of numpy_two_dimensional_list: (3, 3)
+ (3, 4)
+```
+
+### Data type of numpy array
+
+Type of data types: str, int, float, complex, bool, list, None
+
+```py
+int_lists = [-3, -2, -1, 0, 1, 2,3]
+int_array = np.array(int_lists)
+float_array = np.array(int_lists, dtype=float)
+
+print(int_array)
+print(int_array.dtype)
+print(float_array)
+print(float_array.dtype)
+```
+
+```sh
+ [-3 -2 -1 0 1 2 3]
+ int64
+ [-3. -2. -1. 0. 1. 2. 3.]
+ float64
+```
+
+### Size of a numpy array
+
+In numpy to know the number of items in a numpy array list we use size
+
+```py
+numpy_array_from_list = np.array([1, 2, 3, 4, 5])
+two_dimensional_list = np.array([[0, 1, 2],
+ [3, 4, 5],
+ [6, 7, 8]])
+
+print('The size:', numpy_array_from_list.size) # 5
+print('The size:', two_dimensional_list.size) # 3
+
+```
+
+```sh
+ The size: 5
+ The size: 9
+```
+
+## Mathematical Operation using numpy
+
+NumPy array is not like exactly like python list. To do mathematical operation in Python list we have to loop through the items but numpy can allow to do any mathematical operation without looping.
+Mathematical Operation:
+
+- Addition (+)
+- Subtraction (-)
+- Multiplication (\*)
+- Division (/)
+- Modules (%)
+- Floor Division(//)
+- Exponential(\*\*)
+
+### Addition
+
+```py
+# Mathematical Operation
+# Addition
+numpy_array_from_list = np.array([1, 2, 3, 4, 5])
+print('original array: ', numpy_array_from_list)
+ten_plus_original = numpy_array_from_list + 10
+print(ten_plus_original)
+
+```
+
+```sh
+ original array: [1 2 3 4 5]
+ [11 12 13 14 15]
+```
+
+### Subtraction
+
+```python
+# Subtraction
+numpy_array_from_list = np.array([1, 2, 3, 4, 5])
+print('original array: ', numpy_array_from_list)
+ten_minus_original = numpy_array_from_list - 10
+print(ten_minus_original)
+```
+
+```sh
+ original array: [1 2 3 4 5]
+ [-9 -8 -7 -6 -5]
+```
+
+### Multiplication
+
+```python
+# Multiplication
+numpy_array_from_list = np.array([1, 2, 3, 4, 5])
+print('original array: ', numpy_array_from_list)
+ten_times_original = numpy_array_from_list * 10
+print(ten_times_original)
+```
+
+```sh
+ original array: [1 2 3 4 5]
+ [10 20 30 40 50]
+```
+
+### Division
+
+```python
+# Division
+numpy_array_from_list = np.array([1, 2, 3, 4, 5])
+print('original array: ', numpy_array_from_list)
+ten_times_original = numpy_array_from_list / 10
+print(ten_times_original)
+```
+
+```sh
+ original array: [1 2 3 4 5]
+ [0.1 0.2 0.3 0.4 0.5]
+```
+
+### Modulus
+
+```python
+# Modulus; Finding the remainder
+numpy_array_from_list = np.array([1, 2, 3, 4, 5])
+print('original array: ', numpy_array_from_list)
+ten_times_original = numpy_array_from_list % 3
+print(ten_times_original)
+```
+
+```sh
+ original array: [1 2 3 4 5]
+ [1 2 0 1 2]
+```
+
+### Floor Division
+
+```py
+# Floor division: the division result without the remainder
+numpy_array_from_list = np.array([1, 2, 3, 4, 5])
+print('original array: ', numpy_array_from_list)
+ten_times_original = numpy_array_from_list // 10
+print(ten_times_original)
+```
+
+### Exponential
+
+```py
+# Exponential is finding some number the power of another:
+numpy_array_from_list = np.array([1, 2, 3, 4, 5])
+print('original array: ', numpy_array_from_list)
+ten_times_original = numpy_array_from_list ** 2
+print(ten_times_original)
+```
+
+```sh
+ original array: [1 2 3 4 5]
+ [ 1 4 9 16 25]
+```
+
+## Checking data types
+
+```py
+#Int, Float numbers
+numpy_int_arr = np.array([1,2,3,4])
+numpy_float_arr = np.array([1.1, 2.0,3.2])
+numpy_bool_arr = np.array([-3, -2, 0, 1,2,3], dtype='bool')
+
+print(numpy_int_arr.dtype)
+print(numpy_float_arr.dtype)
+print(numpy_bool_arr.dtype)
+```
+
+```sh
+ int64
+ float64
+ bool
+```
+
+### Converting types
+
+We can convert the data types of numpy array
+
+1. Int to Float
+
+```py
+numpy_int_arr = np.array([1,2,3,4], dtype = 'float')
+numpy_int_arr
+```
+
+ array([1., 2., 3., 4.])
+
+2. Float to Int
+
+```py
+numpy_int_arr = np.array([1., 2., 3., 4.], dtype = 'int')
+numpy_int_arr
+```
+
+```sh
+ array([1, 2, 3, 4])
+```
+
+3. Int ot boolean
+
+```py
+np.array([-3, -2, 0, 1,2,3], dtype='bool')
+
+```
+
+```sh
+ array([ True, True, False, True, True, True])
+```
+
+4. Int to str
+
+```py
+numpy_float_list.astype('int').astype('str')
+```
+
+```sh
+ array(['1', '2', '3'], dtype='
+ [[1 2 3]
+ [4 5 6]
+ [7 8 9]]
+ Shape: (3, 3)
+ Size: 9
+ Data type: int64
+```
+
+### Getting items from a numpy array
+
+```py
+# 2 Dimension Array
+two_dimension_array = np.array([[1,2,3],[4,5,6], [7,8,9]])
+first_row = two_dimension_array[0]
+second_row = two_dimension_array[1]
+third_row = two_dimension_array[2]
+print('First row:', first_row)
+print('Second row:', second_row)
+print('Third row: ', third_row)
+```
+
+```sh
+ First row: [1 2 3]
+ Second row: [4 5 6]
+ Third row: [7 8 9]
+```
+
+```py
+first_column= two_dimension_array[:,0]
+second_column = two_dimension_array[:,1]
+third_column = two_dimension_array[:,2]
+print('First column:', first_column)
+print('Second column:', second_column)
+print('Third column: ', third_column)
+print(two_dimension_array)
+
+```
+
+```sh
+ First column: [1 4 7]
+ Second column: [2 5 8]
+ Third column: [3 6 9]
+ [[1 2 3]
+ [4 5 6]
+ [7 8 9]]
+```
+
+## Slicing Numpy array
+
+Slicing in numpy is similar to slicing in python list
+
+```py
+two_dimension_array = np.array([[1,2,3],[4,5,6], [7,8,9]])
+first_two_rows_and_columns = two_dimension_array[0:2, 0:2]
+print(first_two_rows_and_columns)
+```
+
+```sh
+ [[1 2]
+ [4 5]]
+```
+
+### How to reverse the rows and the whole array?
+
+```py
+two_dimension_array[::]
+```
+
+```sh
+ array([[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]])
+```
+
+### Reverse the row and column positions
+
+```py
+ two_dimension_array = np.array([[1,2,3],[4,5,6], [7,8,9]])
+ two_dimension_array[::-1,::-1]
+```
+
+```sh
+ array([[9, 8, 7],
+ [6, 5, 4],
+ [3, 2, 1]])
+```
+
+## How to represent missing values ?
+
+```python
+ print(two_dimension_array)
+ two_dimension_array[1,1] = 55
+ two_dimension_array[1,2] =44
+ print(two_dimension_array)
+```
+
+```sh
+ [[1 2 3]
+ [4 5 6]
+ [7 8 9]]
+ [[ 1 2 3]
+ [ 4 55 44]
+ [ 7 8 9]]
+```
+
+```py
+ # Numpy Zeroes
+ # numpy.zeros(shape, dtype=float, order='C')
+ numpy_zeroes = np.zeros((3,3),dtype=int,order='C')
+ numpy_zeroes
+```
+
+```sh
+ array([[0, 0, 0],
+ [0, 0, 0],
+ [0, 0, 0]])
+```
+
+```py
+# Numpy Zeroes
+numpy_ones = np.ones((3,3),dtype=int,order='C')
+print(numpy_ones)
+```
+
+```sh
+ [[1 1 1]
+ [1 1 1]
+ [1 1 1]]
+```
+
+```py
+twoes = numpy_ones * 2
+```
+
+```py
+# Reshape
+# numpy.reshape(), numpy.flatten()
+first_shape = np.array([(1,2,3), (4,5,6)])
+print(first_shape)
+reshaped = first_shape.reshape(3,2)
+print(reshaped)
+
+```
+
+```sh
+ [[1 2 3]
+ [4 5 6]]
+ [[1 2]
+ [3 4]
+ [5 6]]
+```
+
+```py
+flattened = reshaped.flatten()
+flattened
+```
+
+```sh
+ array([1, 2, 3, 4, 5, 6])
+```
+
+```py
+ ## Horitzontal Stack
+ np_list_one = np.array([1,2,3])
+ np_list_two = np.array([4,5,6])
+
+ print(np_list_one + np_list_two)
+
+ print('Horizontal Append:', np.hstack((np_list_one, np_list_two)))
+```
+
+```sh
+ [5 7 9]
+ Horizontal Append: [1 2 3 4 5 6]
+```
+
+```py
+ ## Vertical Stack
+ print('Vertical Append:', np.vstack((np_list_one, np_list_two)))
+```
+
+```sh
+ Vertical Append: [[1 2 3]
+ [4 5 6]]
+```
+
+#### Generating Random Numbers
+
+```py
+ # Generate a random float number
+ random_float = np.random.random()
+ random_float
+```
+
+```sh
+ 0.018929887384753874
+```
+
+```py
+ # Generate a random float number
+ random_floats = np.random.random(5)
+ random_floats
+```
+
+```sh
+ array([0.26392192, 0.35842215, 0.87908478, 0.41902195, 0.78926418])
+```
+
+```py
+ # Generating a random integers between 0 and 10
+
+ random_int = np.random.randint(0, 11)
+ random_int
+```
+
+```sh
+ 4
+```
+
+```py
+ # Generating a random integers between 2 and 11, and creating a one row array
+ random_int = np.random.randint(2,10, size=4)
+ random_int
+```
+
+```sh
+ array([8, 8, 8, 2])
+```
+
+```py
+ # Generating a random integers between 0 and 10
+ random_int = np.random.randint(2,10, size=(3,3))
+ random_int
+```
+
+```sh
+ array([[3, 5, 3],
+ [7, 3, 6],
+ [2, 3, 3]])
+```
+
+### Generationg random numbers
+
+```py
+ # np.random.normal(mu, sigma, size)
+ normal_array = np.random.normal(79, 15, 80)
+ normal_array
+
+```
+
+```sh
+ array([ 89.49990595, 82.06056961, 107.21445842, 38.69307086,
+ 47.85259157, 93.07381061, 76.40724259, 78.55675184,
+ 72.17358173, 47.9888899 , 65.10370622, 76.29696568,
+ 95.58234254, 68.14897213, 38.75862686, 122.5587927 ,
+ 67.0762565 , 95.73990864, 81.97454563, 92.54264805,
+ 59.37035153, 77.76828101, 52.30752166, 64.43109931,
+ 62.63695351, 90.04616138, 75.70009094, 49.87586877,
+ 80.22002414, 68.56708848, 76.27791052, 67.24343975,
+ 81.86363935, 78.22703433, 102.85737041, 65.15700341,
+ 84.87033426, 76.7569997 , 64.61321853, 67.37244562,
+ 74.4068773 , 58.65119655, 71.66488727, 53.42458179,
+ 70.26872028, 60.96588544, 83.56129414, 72.14255326,
+ 81.00787609, 71.81264853, 72.64168853, 86.56608717,
+ 94.94667321, 82.32676973, 70.5165446 , 85.43061003,
+ 72.45526212, 87.34681775, 87.69911217, 103.02831489,
+ 75.28598596, 67.17806893, 92.41274447, 101.06662611,
+ 87.70013935, 70.73980645, 46.40368207, 50.17947092,
+ 61.75618542, 90.26191397, 78.63968639, 70.84550744,
+ 88.91826581, 103.91474733, 66.3064638 , 79.49726264,
+ 70.81087439, 83.90130623, 87.58555972, 59.95462521])
+```
+
+## Numpy and Statistics
+
+```py
+import matplotlib.pyplot as plt
+import seaborn as sns
+sns.set()
+plt.hist(normal_array, color="grey", bins=50)
+```
+
+```sh
+ (array([2., 0., 0., 0., 1., 2., 2., 0., 2., 0., 0., 1., 2., 2., 1., 4., 3.,
+ 4., 2., 7., 2., 2., 5., 4., 2., 4., 3., 2., 1., 5., 3., 0., 3., 2.,
+ 1., 0., 0., 1., 3., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 1.]),
+ array([ 38.69307086, 40.37038529, 42.04769973, 43.72501417,
+ 45.4023286 , 47.07964304, 48.75695748, 50.43427191,
+ 52.11158635, 53.78890079, 55.46621523, 57.14352966,
+ 58.8208441 , 60.49815854, 62.17547297, 63.85278741,
+ 65.53010185, 67.20741628, 68.88473072, 70.56204516,
+ 72.23935959, 73.91667403, 75.59398847, 77.27130291,
+ 78.94861734, 80.62593178, 82.30324622, 83.98056065,
+ 85.65787509, 87.33518953, 89.01250396, 90.6898184 ,
+ 92.36713284, 94.04444727, 95.72176171, 97.39907615,
+ 99.07639058, 100.75370502, 102.43101946, 104.1083339 ,
+ 105.78564833, 107.46296277, 109.14027721, 110.81759164,
+ 112.49490608, 114.17222052, 115.84953495, 117.52684939,
+ 119.20416383, 120.88147826, 122.5587927 ]),
+ )
+```
+
+### Matrix in numpy
+
+```py
+
+four_by_four_matrix = np.matrix(np.ones((4,4), dtype=float))
+```
+
+```py
+four_by_four_matrix
+```
+
+```sh
+matrix([[1., 1., 1., 1.],
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.]])
+```
+
+```py
+np.asarray(four_by_four_matrix)[2] = 2
+four_by_four_matrix
+```
+
+```sh
+
+matrix([[1., 1., 1., 1.],
+ [1., 1., 1., 1.],
+ [2., 2., 2., 2.],
+ [1., 1., 1., 1.]])
+```
+
+### Numpy numpy.arange()
+
+#### What is Arrange?
+
+Sometimes, you want to create values that are evenly spaced within a defined interval. For instance, you want to create values from 1 to 10; you can use numpy.arange() function
+
+```py
+# creating list using range(starting, stop, step)
+lst = range(0, 11, 2)
+lst
+```
+
+```python
+range(0, 11, 2)
+```
+
+```python
+for l in lst:
+ print(l)
+```
+
+```sh 0
+ 2
+ 4
+ 6
+ 8
+ 10
+```
+
+```py
+# Similar to range arange numpy.arange(start, stop, step)
+whole_numbers = np.arange(0, 20, 1)
+whole_numbers
+```
+
+```sh
+array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
+ 17, 18, 19])
+```
+
+```py
+natural_numbers = np.arange(1, 20, 1)
+natural_numbers
+```
+
+```py
+odd_numbers = np.arange(1, 20, 2)
+odd_numbers
+```
+
+```sh
+ array([ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19])
+```
+
+```py
+even_numbers = np.arange(2, 20, 2)
+even_numbers
+```
+
+```sh
+ array([ 2, 4, 6, 8, 10, 12, 14, 16, 18])
+```
+
+### Creating sequence of numbers using linspace
+
+```py
+# numpy.linspace()
+# numpy.logspace() in Python with Example
+# For instance, it can be used to create 10 values from 1 to 5 evenly spaced.
+np.linspace(1.0, 5.0, num=10)
+```
+
+```sh
+ array([1. , 1.44444444, 1.88888889, 2.33333333, 2.77777778,
+ 3.22222222, 3.66666667, 4.11111111, 4.55555556, 5. ])
+```
+
+```py
+# not to include the last value in the interval
+np.linspace(1.0, 5.0, num=5, endpoint=False)
+```
+
+```
+array([1. , 1.8, 2.6, 3.4, 4.2])
+```
+
+```py
+# LogSpace
+# LogSpace returns even spaced numbers on a log scale. Logspace has the same parameters as np.linspace.
+
+# Syntax:
+
+# numpy.logspace(start, stop, num, endpoint)
+
+np.logspace(2, 4.0, num=4)
+```
+
+```sh
+
+array([ 100. , 464.15888336, 2154.43469003, 10000. ])
+```
+
+```py
+# to check the size of an array
+x = np.array([1,2,3], dtype=np.complex128)
+```
+
+```py
+x
+```
+
+```sh
+ array([1.+0.j, 2.+0.j, 3.+0.j])
+```
+
+```py
+x.itemsize
+```
+
+```sh
+16
+```
+
+```py
+# indexing and Slicing NumPy Arrays in Python
+np_list = np.array([(1,2,3), (4,5,6)])
+np_list
+
+```
+
+```sh
+ array([[1, 2, 3],
+ [4, 5, 6]])
+```
+
+```py
+print('First row: ', np_list[0])
+print('Second row: ', np_list[1])
+
+```
+
+```sh
+
+ First row: [1 2 3]
+ Second row: [4 5 6]
+```
+
+```p
+print('First column: ', np_list[:,0])
+print('Second column: ', np_list[:,1])
+print('Third column: ', np_list[:,2])
+
+```
+
+```sh
+ First column: [1 4]
+ Second column: [2 5]
+ Third column: [3 6]
+```
+
+### NumPy Statistical Functions with Example
+
+NumPy has quite useful statistical functions for finding minimum, maximum, mean, median, percentile,standard deviation and variance, etc from the given elements in the array.
+The functions are explained as follows −
+Statistical function
+Numpy is equipped with the robust statistical function as listed below
+
+- Numpy Functions
+ - Min np.min()
+ - Max np.max()
+ - Mean np.mean()
+ - Median np.median()
+ - Variance
+ - Percentile
+ - Standard deviation np.std()
+
+```python
+np_normal_dis = np.random.normal(5, 0.5, 100)
+np_normal_dis
+## min, max, mean, median, sd
+print('min: ', two_dimension_array.min())
+print('max: ', two_dimension_array.max())
+print('mean: ',two_dimension_array.mean())
+# print('median: ', two_dimension_array.median())
+print('sd: ', two_dimension_array.std())
+```
+
+ min: 1
+ max: 55
+ mean: 14.777777777777779
+ sd: 18.913709183069525
+
+```python
+min: 1
+max: 55
+mean: 14.777777777777779
+sd: 18.913709183069525
+```
+
+```python
+print(two_dimension_array)
+print('Column with minimum: ', np.amin(two_dimension_array,axis=0))
+print('Column with maximum: ', np.amax(two_dimension_array,axis=0))
+print('=== Row ==')
+print('Row with minimum: ', np.amin(two_dimension_array,axis=1))
+print('Row with maximum: ', np.amax(two_dimension_array,axis=1))
+```
+
+ [[ 1 2 3]
+ [ 4 55 44]
+ [ 7 8 9]]
+ Column with minimum: [1 2 3]
+ Column with maximum: [ 7 55 44]
+ === Row ==
+ Row with minimum: [1 4 7]
+ Row with maximum: [ 3 55 9]
+
+### How to create repeating sequences?
+
+```python
+a = [1,2,3]
+
+# Repeat whole of 'a' two times
+print('Tile: ', np.tile(a, 2))
+
+# Repeat each element of 'a' two times
+print('Repeat: ', np.repeat(a, 2))
+
+```
+
+ Tile: [1 2 3 1 2 3]
+ Repeat: [1 1 2 2 3 3]
+
+### How to generate random numbers?
+
+```python
+# One random number between [0,1)
+one_random_num = np.random.random()
+one_random_in = np.random
+print(one_random_num)
+```
+
+ 0.6149403282678213
+
+```python
+0.4763968133790438
+```
+
+ 0.4763968133790438
+
+```python
+# Random numbers between [0,1) of shape 2,3
+r = np.random.random(size=[2,3])
+print(r)
+```
+
+ [[0.13031737 0.4429537 0.1129527 ]
+ [0.76811539 0.88256594 0.6754075 ]]
+
+```python
+print(np.random.choice(['a', 'e', 'i', 'o', 'u'], size=10))
+```
+
+ ['u' 'o' 'o' 'i' 'e' 'e' 'u' 'o' 'u' 'a']
+
+```python
+['i' 'u' 'e' 'o' 'a' 'i' 'e' 'u' 'o' 'i']
+```
+
+ ['iueoaieuoi']
+
+```python
+## Random numbers between [0, 1] of shape 2, 2
+rand = np.random.rand(2,2)
+rand
+```
+
+ array([[0.97992598, 0.79642484],
+ [0.65263629, 0.55763145]])
+
+```python
+rand2 = np.random.randn(2,2)
+rand2
+
+```
+
+ array([[ 1.65593322, -0.52326621],
+ [ 0.39071179, -2.03649407]])
+
+```python
+# Random integers between [0, 10) of shape 2,5
+rand_int = np.random.randint(0, 10, size=[5,3])
+rand_int
+```
+
+ array([[0, 7, 5],
+ [4, 1, 4],
+ [3, 5, 3],
+ [4, 3, 8],
+ [4, 6, 7]])
+
+```py
+from scipy import stats
+np_normal_dis = np.random.normal(5, 0.5, 1000) # mean, standard deviation, number of samples
+np_normal_dis
+## min, max, mean, median, sd
+print('min: ', np.min(np_normal_dis))
+print('max: ', np.max(np_normal_dis))
+print('mean: ', np.mean(np_normal_dis))
+print('median: ', np.median(np_normal_dis))
+print('mode: ', stats.mode(np_normal_dis))
+print('sd: ', np.std(np_normal_dis))
+```
+
+```sh
+
+ min: 3.557811005458804
+ max: 6.876317743643499
+ mean: 5.035832048106663
+ median: 5.020161980441937
+ mode: ModeResult(mode=array([3.55781101]), count=array([1]))
+ sd: 0.489682424165213
+
+```
+
+```python
+plt.hist(np_normal_dis, color="grey", bins=21)
+plt.show()
+```
+
+
+
+```python
+# numpy.dot(): Dot Product in Python using Numpy
+# Dot Product
+# Numpy is powerful library for matrices computation. For instance, you can compute the dot product with np.dot
+
+# Syntax
+
+# numpy.dot(x, y, out=None)
+```
+
+### Linear Algebra
+
+1. Dot Product
+
+```python
+## Linear algebra
+### Dot product: product of two arrays
+f = np.array([1,2,3])
+g = np.array([4,5,3])
+### 1*4+2*5 + 3*6
+np.dot(f, g) # 23
+```
+
+### NumPy Matrix Multiplication with np.matmul()
+
+```python
+### Matmul: matruc product of two arrays
+h = [[1,2],[3,4]]
+i = [[5,6],[7,8]]
+### 1*5+2*7 = 19
+np.matmul(h, i)
+```
+
+```sh
+ array([[19, 22],
+ [43, 50]])
+
+```
+
+```py
+## Determinant 2*2 matrix
+### 5*8-7*6np.linalg.det(i)
+```
+
+```python
+np.linalg.det(i)
+```
+
+ -1.999999999999999
+
+```python
+Z = np.zeros((8,8))
+Z[1::2,::2] = 1
+Z[::2,1::2] = 1
+```
+
+```python
+Z
+```
+
+ array([[0., 1., 0., 1., 0., 1., 0., 1.],
+ [1., 0., 1., 0., 1., 0., 1., 0.],
+ [0., 1., 0., 1., 0., 1., 0., 1.],
+ [1., 0., 1., 0., 1., 0., 1., 0.],
+ [0., 1., 0., 1., 0., 1., 0., 1.],
+ [1., 0., 1., 0., 1., 0., 1., 0.],
+ [0., 1., 0., 1., 0., 1., 0., 1.],
+ [1., 0., 1., 0., 1., 0., 1., 0.]])
+
+```python
+new_list = [ x + 2 for x in range(0, 11)]
+```
+
+```python
+new_list
+```
+
+ [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
+
+```python
+[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
+```
+
+ [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
+
+```python
+np_arr = np.array(range(0, 11))
+np_arr + 2
+```
+
+array([ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
+
+We use linear equation for quantities which have linear relationship. Let's see the example below:
+
+```python
+temp = np.array([1,2,3,4,5])
+pressure = temp * 2 + 5
+pressure
+```
+
+array([ 7, 9, 11, 13, 15])
+
+```python
+plt.plot(temp,pressure)
+plt.xlabel('Temperature in oC')
+plt.ylabel('Pressure in atm')
+plt.title('Temperature vs Pressure')
+plt.xticks(np.arange(0, 6, step=0.5))
+plt.show()
+```
+
+
+
+To draw the Gaussian normal distribution using numpy. As you can see below, the numpy can generate random numbers. To create random sample, we need the mean(mu), sigma(standard deviation), number of data points.
+
+```python
+mu = 28
+sigma = 15
+samples = 100000
+
+x = np.random.normal(mu, sigma, samples)
+ax = sns.distplot(x);
+ax.set(xlabel="x", ylabel='y')
+plt.show()
+```
+
+
+
+# Summary
+
+To summarize, the main differences with python lists are:
+
+1. Arrays support vectorized operations, while lists don’t.
+1. Once an array is created, you cannot change its size. You will have to create a new array or overwrite the existing one.
+1. Every array has one and only one dtype. All items in it should be of that dtype.
+1. An equivalent numpy array occupies much less space than a python list of lists.
+1. numpy arrays support boolean indexing.
+
+## 💻 Exercises: Day 24
+
+1. Repeat all the examples
+
+🎉 CONGRATULATIONS ! 🎉
+
+[<< Day 23](../23_Day_Virtual_environment/23_virtual_environment.md) | [Day 25 >>](../25_Day_Pandas/25_pandas.md)
diff --git a/25_Day/25_pandas.md b/25_Day_Pandas/25_pandas.md
similarity index 88%
rename from 25_Day/25_pandas.md
rename to 25_Day_Pandas/25_pandas.md
index e8992b8de..4e4d8bc74 100644
--- a/25_Day/25_pandas.md
+++ b/25_Day_Pandas/25_pandas.md
@@ -9,23 +9,24 @@
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+ Second Edition: July, 2021
-
+
-[<< Day 24](../24_Day/24_statistics.md) | [Day 26 >>](../26_Day/26_python_web.md)
+[<< Day 24](../24_Day_Statistics/24_statistics.md) | [Day 26 >>](../26_Day_Python_web/26_python_web.md)

-- [📘 Day 25](#%f0%9f%93%98-day-25)
+- [📘 Day 25](#-day-25)
- [Pandas](#pandas)
- - [Importing Pandas](#importing-pandas)
+ - [Installing Pandas](#installing-pandas)
+ - [Importing Pandas](#importing-pandas)
- [Creating Pandas Series with Default Index](#creating-pandas-series-with-default-index)
- - [Creating Pandas Series with Custom Index](#creating-pandas-series-with-custom-index)
+ - [Creating Pandas Series with custom index](#creating--pandas-series-with-custom-index)
- [Creating Pandas Series from a Dictionary](#creating-pandas-series-from-a-dictionary)
- [Creating a Constant Pandas Series](#creating-a-constant-pandas-series)
- - [Creating a Pandas Series Using Linspace](#creating-a-pandas-series-using-linspace)
+ - [Creating a Pandas Series Using Linspace](#creating-a--pandas-series-using-linspace)
- [DataFrames](#dataframes)
- [Creating DataFrames from List of Lists](#creating-dataframes-from-list-of-lists)
- [Creating DataFrame Using Dictionary](#creating-dataframe-using-dictionary)
@@ -35,17 +36,29 @@
- [Modifying a DataFrame](#modifying-a-dataframe)
- [Creating a DataFrame](#creating-a-dataframe)
- [Adding a New Column](#adding-a-new-column)
- - [Modifying Column Values](#modifying-column-values)
- - [Formating DataFrame Columns](#formating-dataframe-columns)
- - [Checking Data Types of Column Values](#checking-data-types-of-column-values)
+ - [Modifying column values](#modifying-column-values)
+ - [Formatting DataFrame columns](#formatting-dataframe-columns)
+ - [Checking data types of Column values](#checking-data-types-of-column-values)
- [Boolean Indexing](#boolean-indexing)
- [Exercises: Day 25](#exercises-day-25)
+
# 📘 Day 25
+
## Pandas
Pandas is an open source, high-performance, easy-to-use data structures and data analysis tools for the Python programming language.
-Pandas adds data structures and tools designed to work with table-like data which is Series and Data Frames.
-Pandas provides tools for data manipulation: reshaping, merging, sorting, slicing, aggregation and imputation.
+Pandas adds data structures and tools designed to work with table-like data which is *Series* and *Data Frames*.
+Pandas provides tools for data manipulation:
+
+- reshaping
+- merging
+- sorting
+- slicing
+- aggregation
+- imputation.
+If you are using anaconda, you do not have install pandas.
+
+### Installing Pandas
For Mac:
```py
@@ -59,17 +72,18 @@ pip install conda
pip install pandas
```
-Pandas data structure is based on *Series* and *DataFrames*
-A series is a column and a DataFrame is a multidimensional table made up of collection of series. In order to create a pandas series we should use numpy to create a one dimensional arrays or a python list.
-Let's see an example of a series:
+Pandas data structure is based on *Series* and *DataFrames*.
+
+A *series* is a *column* and a DataFrame is a *multidimensional table* made up of collection of *series*. In order to create a pandas series we should use numpy to create a one dimensional arrays or a python list.
+Let us see an example of a series:
Names Pandas Series
-
+
Countries Series
-
+
Cities Series
@@ -77,19 +91,17 @@ Cities Series
As you can see, pandas series is just one column of data. If we want to have multiple columns we use data frames. The example below shows pandas DataFrames.
-Let's see, an example of a pandas data frame:
+Let us see, an example of a pandas data frame:

Data frame is a collection of rows and columns. Look at the table below; it has many more columns than the example above:
-

Next, we will see how to import pandas and how to create Series and DataFrames using pandas
-## Importing Pandas
-
+### Importing Pandas
```python
import pandas as pd # importing pandas as pd
@@ -98,14 +110,12 @@ import numpy as np # importing numpy as np
### Creating Pandas Series with Default Index
-
```python
nums = [1, 2, 3, 4,5]
s = pd.Series(nums)
print(s)
```
-
```sh
0 1
1 2
@@ -115,19 +125,14 @@ print(s)
dtype: int64
```
-
### Creating Pandas Series with custom index
-
```python
nums = [1, 2, 3, 4, 5]
s = pd.Series(nums, index=[1, 2, 3, 4, 5])
print(s)
-
```
-
-
```sh
1 1
2 2
@@ -137,39 +142,30 @@ print(s)
dtype: int64
```
-
-
```python
-fruits = ['Orange','Banana','Mangao']
+fruits = ['Orange','Banana','Mango']
fruits = pd.Series(fruits, index=[1, 2, 3])
print(fruits)
```
-
-
```sh
1 Orange
2 Banana
- 3 Mangao
+ 3 Mango
dtype: object
```
-
### Creating Pandas Series from a Dictionary
-
```python
dct = {'name':'Asabeneh','country':'Finland','city':'Helsinki'}
```
-
```python
s = pd.Series(dct)
print(s)
```
-
-
```sh
name Asabeneh
country Finland
@@ -177,17 +173,13 @@ print(s)
dtype: object
```
-
### Creating a Constant Pandas Series
-
```python
-s = pd.Series(10, index = [1, 2,3])
+s = pd.Series(10, index = [1, 2, 3])
print(s)
```
-
-
```sh
1 10
2 10
@@ -195,17 +187,13 @@ print(s)
dtype: int64
```
-
### Creating a Pandas Series Using Linspace
-
```python
s = pd.Series(np.linspace(5, 20, 10)) # linspace(starting, end, items)
print(s)
```
-
-
```sh
0 5.000000
1 6.666667
@@ -226,10 +214,9 @@ Pandas data frames can be created in different ways.
### Creating DataFrames from List of Lists
-
```python
data = [
- ['Asabeneh', 'Finland', 'Helsink'],
+ ['Asabeneh', 'Finland', 'Helsink'],
['David', 'UK', 'London'],
['John', 'Sweden', 'Stockholm']
]
@@ -270,7 +257,6 @@ print(df)
### Creating DataFrame Using Dictionary
-
```python
data = {'Name': ['Asabeneh', 'David', 'John'], 'Country':[
'Finland', 'UK', 'Sweden'], 'City': ['Helsiki', 'London', 'Stockholm']}
@@ -278,7 +264,6 @@ df = pd.DataFrame(data)
print(df)
```
-
@@ -310,10 +295,8 @@ print(df)
-
### Creating DataFrames from a List of Dictionaries
-
```python
data = [
{'Name': 'Asabeneh', 'Country': 'Finland', 'City': 'Helsinki'},
@@ -323,7 +306,6 @@ df = pd.DataFrame(data)
print(df)
```
-
@@ -355,17 +337,16 @@ print(df)
-
-
-
## Reading CSV File Using Pandas
-To download the csv file, needed in this example, console/command line is enough:
+To download the CSV file, what is needed in this example, console/command line is enough:
```sh
curl -O https://raw.githubusercontent.com/Asabeneh/30-Days-Of-Python/master/data/weight-height.csv
```
+Put the downloaded file in your working directory.
+
```python
import pandas as pd
@@ -374,8 +355,8 @@ print(df)
```
### Data Exploration
-Let's read only the first 5 rows using head()
+Let us read only the first 5 rows using head()
```python
print(df.head()) # give five rows we can increase the number of rows by passing argument to the head() method
@@ -425,45 +406,12 @@ print(df.head()) # give five rows we can increase the number of rows by passing
-
-
-As you can see the csv file has three rows: Gender, Height and Weight. But we don't know the number of rows. Let's use shape meathod.
-
-
-```python
-print(df.shape) # as you can see 10000 rows and three columns
-```
-
-
-
-
- (10000, 3)
-
-
-
-Let's get all the columns using columns.
-
-
-
-```python
-print(df.columns)
-```
-
-
-
-
- Index(['Gender', 'Height', 'Weight'], dtype='object')
-
-
-
-Let's read only the last 5 rows using tail()
-
+Let us also explore the last recordings of the dataframe using the tail() methods.
```python
print(df.tail()) # tails give the last five rows, we can increase the rows by passing argument to tail method
```
-
@@ -507,21 +455,31 @@ print(df.tail()) # tails give the last five rows, we can increase the rows by pa
+As you can see the csv file has three rows: Gender, Height and Weight. If the DataFrame would have a long rows, it would be hard to know all the columns. Therefore, we should use a method to know the columns. we do not know the number of rows. Let's use shape method.
-Now, lets get a specific column using the column key
+```python
+print(df.shape) # as you can see 10000 rows and three columns
+```
+ (10000, 3)
+Let us get all the columns using columns.
```python
-heights = df['Height'] # this is now a series
+print(df.columns)
```
+ Index(['Gender', 'Height', 'Weight'], dtype='object')
+
+Now, let us get a specific column using the column key
```python
-print(heights)
+heights = df['Height'] # this is now a series
```
-
+```python
+print(heights)
+```
```sh
0 73.847017
@@ -529,7 +487,7 @@ print(heights)
2 74.110105
3 71.730978
4 69.881796
- ...
+ ...
9995 66.172652
9996 67.067155
9997 63.867992
@@ -538,25 +496,21 @@ print(heights)
Name: Height, Length: 10000, dtype: float64
```
-
-
```python
weights = df['Weight'] # this is now a series
```
-
```python
print(weights)
```
-
```sh
0 241.893563
1 162.310473
2 212.740856
3 220.042470
4 206.349801
- ...
+ ...
9995 136.777454
9996 170.867906
9997 128.475319
@@ -565,25 +519,18 @@ print(weights)
Name: Weight, Length: 10000, dtype: float64
```
-
-
```python
print(len(heights) == len(weights))
```
-
-
-
True
-
-
+The describe() method provides a descriptive statistical values of a dataset.
```python
-print(heights.describe()) # give statisical information about height data
+print(heights.describe()) # give statistical information about height data
```
-
```sh
count 10000.000000
mean 66.367560
@@ -596,14 +543,10 @@ print(heights.describe()) # give statisical information about height data
Name: Height, dtype: float64
```
-
-
```python
print(weights.describe())
```
-
-
```sh
count 10000.000000
mean 161.440357
@@ -616,13 +559,10 @@ print(weights.describe())
Name: Weight, dtype: float64
```
-
-
```python
print(df.describe()) # describe can also give statistical information from a dataFrame
```
-
@@ -675,23 +615,21 @@ print(df.describe()) # describe can also give statistical information from a da
+Similar to describe(), the info() method also give information about the dataset.
## Modifying a DataFrame
-
-
Modifying a DataFrame:
* We can create a new DataFrame
- * We can create a new column and add it to the DataFrame,
- * we can remove an existing column from a DataFrame,
- * we can modify an existing column in a DataFrame,
+ * We can create a new column and add it to the DataFrame,
+ * we can remove an existing column from a DataFrame,
+ * we can modify an existing column in a DataFrame,
* we can change the data type of column values in the DataFrame
### Creating a DataFrame
As always, first we import the necessary packages. Now, lets import pandas and numpy, two best friends ever.
-
```python
import pandas as pd
import numpy as np
@@ -734,14 +672,13 @@ print(df)
-
Adding a column to a DataFrame is like adding a key to a dictionary.
First let's use the previous example to create a DataFrame. After we create the DataFrame, we will start modifying the columns and column values.
### Adding a New Column
-Let's add a weight column in the DataFrame
+Let's add a weight column in the DataFrame
```python
weights = [74, 78, 69]
@@ -749,7 +686,6 @@ df['Weight'] = weights
df
```
-
@@ -787,14 +723,12 @@ df
Let's add a height column into the DataFrame aswell
-
```python
heights = [173, 175, 169]
df['Height'] = heights
print(df)
```
-
@@ -840,7 +774,6 @@ As you can see, the height is in centimeters, so we shoud change it to meters. L
### Modifying column values
-
```python
df['Height'] = df['Height'] * 0.01
df
@@ -895,7 +828,7 @@ def calculate_bmi ():
b = w/(h*h)
bmi.append(b)
return bmi
-
+
bmi = calculate_bmi()
```
@@ -949,19 +882,15 @@ df
-
-
-### Formating DataFrame columns
+### Formatting DataFrame columns
The BMI column values of the DataFrame are float with many significant digits after decimal. Let's change it to one significant digit after point.
-
```python
df['BMI'] = round(df['BMI'], 1)
print(df)
```
-
@@ -1007,7 +936,6 @@ print(df)
The information in the DataFrame seems not yet complete, let's add birth year and current year columns.
-
```python
birth_year = ['1769', '1985', '1990']
current_year = pd.Series(2020, index=[0, 1,2])
@@ -1016,7 +944,6 @@ df['Current Year'] = current_year
df
```
-
@@ -1068,36 +995,26 @@ df
-
## Checking data types of Column values
-
```python
print(df.Weight.dtype)
```
-
-
```sh
dtype('int64')
```
-
-
```python
df['Birth Year'].dtype # it gives string object , we should change this to number
```
-
-
```python
df['Birth Year'] = df['Birth Year'].astype('int')
print(df['Birth Year'].dtype) # let's check the data type now
```
-
-
```sh
dtype('int32')
```
@@ -1113,32 +1030,23 @@ df['Current Year'].dtype
dtype('int32')
```
-
Now, the column values of birth year and current year are integers. We can calculate the age.
-
```python
ages = df['Current Year'] - df['Birth Year']
ages
```
-
-
-
0 251
1 35
2 30
dtype: int32
-
-
-
```python
df['Ages'] = ages
print(df)
```
-
@@ -1194,31 +1102,25 @@ print(df)
-The person in the first row lived so far for 251 years. It is unlikely for someone to live so long. Either it is a typo or the data is cooked. So lets fill that data with average of the columns without including outlier.
+The person in the first row lived so far for 251 years. It is unlikely for someone to live so long. Either it is a typo or the data is cooked. So lets fill that data with average of the columns without including outlier.
mean = (35 + 30)/ 2
-
```python
mean = (35 + 30)/ 2
print('Mean: ',mean) #it is good to add some description to the output, so we know what is what
```
-
-
```sh
Mean: 32.5
```
-
### Boolean Indexing
-
```python
print(df[df['Ages'] > 120])
```
-
@@ -1255,8 +1157,6 @@ print(df[df['Ages'] > 120])
print(df[df['Ages'] < 120])
```
-
-
@@ -1300,17 +1200,17 @@ print(df[df['Ages'] < 120])
-
## Exercises: Day 25
-1. Read the hacker_ness.csv file from data directory
+
+1. Read the hacker_news.csv file from data directory
1. Get the first five rows
1. Get the last five rows
1. Get the title column as pandas series
1. Count the number of rows and columns
- * Filter the titles which contain python
- * Filter the titles which contain JavaScript
- * Explore the data and make sense of it
+ - Filter the titles which contain python
+ - Filter the titles which contain JavaScript
+ - Explore the data and make sense of it
🎉 CONGRATULATIONS ! 🎉
-[<< Day 24](../24_Day/24_statistics.md) | [Day 26 >>](../26_Day/26_python_web.md)
+[<< Day 24](../24_Day_Statistics/24_statistics.md) | [Day 26 >>](../26_Day_Python_web/26_python_web.md)
diff --git a/26_Day/26_python_web.md b/26_Day_Python_web/26_python_web.md
similarity index 87%
rename from 26_Day/26_python_web.md
rename to 26_Day_Python_web/26_python_web.md
index fc138d885..9c6efd684 100644
--- a/26_Day/26_python_web.md
+++ b/26_Day_Python_web/26_python_web.md
@@ -9,16 +9,16 @@
Author:
Asabeneh Yetayeh
- First Edition: Nov 22 - Dec 22, 2019
+ Second Edition: July, 2021
-[<< Day 25 ](../25_Day/25_pandas.md) | [Day 27 >>](../27_Day/27_python_with_mongodb.md)
+[<< Day 25 ](../25_Day_Pandas/25_pandas.md) | [Day 27 >>](../27_Day_Python_with_mongodb/27_python_with_mongodb.md)

-- [📘 Day 26](#%f0%9f%93%98-day-26)
+- [📘 Day 26](#-day-26)
- [Python for Web](#python-for-web)
- [Flask](#flask)
- [Folder structure](#folder-structure)
@@ -28,6 +28,7 @@
- [Python Script](#python-script)
- [Navigation](#navigation)
- [Creating a layout](#creating-a-layout)
+ - [Serving Static File](#serving-static-file)
- [Deployment](#deployment)
- [Creating Heroku account](#creating-heroku-account)
- [Login to Heroku](#login-to-heroku)
@@ -39,16 +40,17 @@
## Python for Web
-Python is a general purpose programming language and it can be used for many places. In this section, we will see how we use python for the web. There are many python web frame works. Django and Flask are the most popular ones. Today, we will see how to use Flask for web development.
+Python is a general purpose programming language and it can be used for many places. In this section, we will see how we use Python for the web. There are many Python web frame works. Django and Flask are the most popular ones. Today, we will see how to use Flask for web development.
### Flask
-Flask is a web development framework written in python. Flask uses Jinja2 template engine. Flask can be also used with other modern frond libraries such as react.
-If you did not install the virtualenv package ye install it first. Virtual environment will allows to isolate project dependencies.
+Flask is a web development framework written in Python. Flask uses Jinja2 template engine. Flask can be also used with other modern front libraries such as React.
+
+If you did not install the virtualenv package yet install it first. Virtual environment will allows to isolate project dependencies from the local machine dependencies.
#### Folder structure
-After completing all the step your project file structure should look like this:
+After completing all the step, your project file structure should look like this:
```sh
@@ -70,7 +72,8 @@ After completing all the step your project file structure should look like this:
### Setting up your project directory
-Follow, the following steps to get started with Flask.
+Follow the following steps to get started with Flask.
+
Step 1: install virtualenv using the following command.
```sh
@@ -82,8 +85,8 @@ Step 2:
```sh
asabeneh@Asabeneh:~/Desktop$ mkdir python_for_web
asabeneh@Asabeneh:~/Desktop$ cd python_for_web/
-asabeneh@Asabeneh:~/Desktop/python_for_web$ virtualenv env
-asabeneh@Asabeneh:~/Desktop/python_for_web$ source env/bin/activate
+asabeneh@Asabeneh:~/Desktop/python_for_web$ virtualenv venv
+asabeneh@Asabeneh:~/Desktop/python_for_web$ source venv/bin/activate
(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze
(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ pip install Flask
(env) asabeneh@Asabeneh:~/Desktop/python_for_web$ pip freeze
@@ -96,7 +99,7 @@ Werkzeug==0.16.0
(env) asabeneh@Asabeneh:~/Desktop/python_for_web$
```
-We created a project director named python*for_web. Inside the project we created a virtual environment \_env* which could be any name but I prefer to call it _env_. Then we activated the virtual environment. We used pip freeze to check the installed packages in the project directory. The result of pip freeze was empty because a package was not installed yet.
+We created a project director named python_for_web. Inside the project we created a virtual environment *venv* which could be any name but I prefer to call it _venv_. Then we activated the virtual environment. We used pip freeze to check the installed packages in the project directory. The result of pip freeze was empty because a package was not installed yet.
Now, let's create app.py file in the project directory and write the following code. The app.py file will be the main file in the project. The following code has flask module, os module.
@@ -115,11 +118,6 @@ app = Flask(__name__)
def home ():
return 'Welcome
'
-@app.route('/about')
-def about():
- return 'About us
'
-
-
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
@@ -127,9 +125,11 @@ if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=port)
```
+To run the flask application, write python app.py in the main flask application directory.
+
After you run _python app.py_ check local host 5000.
-Let's add additional route.
+Let us add additional route.
Creating about route
```py
@@ -154,7 +154,7 @@ if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=port)
```
-Now, we added the about route in the above code. How about if we want to render an HTML file instead of string? It is possible to render HTML file using the function _render_templae_. Let's create a folder called templates and create home.html and about.html in the project directory. Let's also import the _render_template_ function from flask.
+Now, we added the about route in the above code. How about if we want to render an HTML file instead of string? It is possible to render HTML file using the function *render_template*. Let us create a folder called templates and create home.html and about.html in the project directory. Let us also import the *render_template* function from flask.
### Creating templates
@@ -231,7 +231,7 @@ As you can see to go to different pages or to navigate we need a navigation. Let
```
-Now, we can navigate between the pages using the above link. Let's create additional page which handle form data. You can call it any name, I like to call it post.html.
+Now, we can navigate between the pages using the above link. Let us create additional page which handle form data. You can call it any name, I like to call it post.html.
We can inject data to the HTML files using Jinja2 template engine.
@@ -285,11 +285,11 @@ home.html
About
Welcome to {{name}}
+
{% for tech in techs %}
-
{% endfor %}
+