16 |
17 | [<< Day 1](../readme.md) | [Day 3 >>](../03_Day_Operators/03_operators.md)
18 |
19 | 
20 |
21 | - [📘 Day 2](#-day-2)
22 | - [Built in functions](#built-in-functions)
23 | - [Variables](#variables)
24 | - [Declaring Multiple Variable in a Line](#declaring-multiple-variable-in-a-line)
25 | - [Data Types](#data-types)
26 | - [Checking Data types and Casting](#checking-data-types-and-casting)
27 | - [Numbers](#numbers)
28 | - [💻 Exercises - Day 2](#-exercises---day-2)
29 | - [Exercises: Level 1](#exercises-level-1)
30 | - [Exercises: Level 2](#exercises-level-2)
31 |
32 | # 📘 Day 2
33 |
34 | ## Built in functions
35 |
36 | 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.9/library/functions.html).
37 |
38 | 
39 |
40 | Let us open the Python shell and start using some of the most common built-in functions.
41 |
42 | 
43 |
44 | Let us practice more by using different built-in functions
45 |
46 | 
47 |
48 | 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.
49 |
50 | 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.
51 |
52 | 
53 |
54 | ## Variables
55 |
56 | 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.
57 | 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.
58 |
59 | Python Variable Name Rules
60 |
61 | - A variable name must start with a letter or the underscore character
62 | - A variable name cannot start with a number
63 | - A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and \_ )
64 | - Variable names are case-sensitive (firstname, Firstname, FirstName and FIRSTNAME) are different variables)
65 |
66 | Let us se valid variable names
67 |
68 | ```shell
69 | firstname
70 | lastname
71 | age
72 | country
73 | city
74 | first_name
75 | last_name
76 | capital_city
77 | _if # if we want to use reserved word as a variable
78 | year_2021
79 | year2021
80 | current_year_2021
81 | birth_year
82 | num1
83 | num2
84 | ```
85 |
86 | Invalid variables names
87 |
88 | ```shell
89 | first-name
90 | first@name
91 | first$name
92 | num-1
93 | 1num
94 | ```
95 |
96 | 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.
97 |
98 | 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.
99 |
100 | _Example:_
101 |
102 | ```py
103 | # Variables in Python
104 | first_name = 'Asabeneh'
105 | last_name = 'Yetayeh'
106 | country = 'Finland'
107 | city = 'Helsinki'
108 | age = 250
109 | is_married = True
110 | skills = ['HTML', 'CSS', 'JS', 'React', 'Python']
111 | person_info = {
112 | 'firstname':'Asabeneh',
113 | 'lastname':'Yetayeh',
114 | 'country':'Finland',
115 | 'city':'Helsinki'
116 | }
117 | ```
118 |
119 | 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.
120 |
121 | **Example:**
122 |
123 | ```py
124 | print('Hello, World!') # The text Hello, World! is an argument
125 | print('Hello',',', 'World','!') # it can take multiple arguments, four arguments have been passed
126 | print(len('Hello, World!')) # it takes only one argument
127 | ```
128 |
129 | Let us print and also find the length of the variables declared at the top:
130 |
131 | **Example:**
132 |
133 | ```py
134 | # Printing the values stored in the variables
135 |
136 | print('First name:', first_name)
137 | print('First name length:', len(first_name))
138 | print('Last name: ', last_name)
139 | print('Last name length: ', len(last_name))
140 | print('Country: ', country)
141 | print('City: ', city)
142 | print('Age: ', age)
143 | print('Married: ', is_married)
144 | print('Skills: ', skills)
145 | print('Person information: ', person_info)
146 | ```
147 |
148 | ### Declaring Multiple Variable in a Line
149 |
150 | Multiple variables can also be declared in one line:
151 |
152 | **Example:**
153 |
154 | ```py
155 | first_name, last_name, country, age, is_married = 'Asabeneh', 'Yetayeh', 'Helsink', 250, True
156 |
157 | print(first_name, last_name, country, age, is_married)
158 | print('First name:', first_name)
159 | print('Last name: ', last_name)
160 | print('Country: ', country)
161 | print('Age: ', age)
162 | print('Married: ', is_married)
163 | ```
164 |
165 | 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.
166 | **Example:**
167 |
168 | ```py
169 | first_name = input('What is your name: ')
170 | age = input('How old are you? ')
171 |
172 | print(first_name)
173 | print(age)
174 | ```
175 |
176 | ## Data Types
177 |
178 | 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.
179 |
180 | ## Checking Data types and Casting
181 |
182 | - Check Data types: To check the data type of certain data/variable we use the _type_
183 | **Example:**
184 |
185 | ```py
186 | # Different python data types
187 | # Let's declare variables with various data types
188 |
189 | first_name = 'Asabeneh' # str
190 | last_name = 'Yetayeh' # str
191 | country = 'Finland' # str
192 | city= 'Helsinki' # str
193 | age = 250 # int, it is not my real age, don't worry about it
194 |
195 | # Printing out types
196 | print(type('Asabeneh')) # str
197 | print(type(first_name)) # str
198 | print(type(10)) # int
199 | print(type(3.14)) # float
200 | print(type(1 + 1j)) # complex
201 | print(type(True)) # bool
202 | print(type([1, 2, 3, 4])) # list
203 | print(type({'name':'Asabeneh','age':250, 'is_married':250})) # dict
204 | print(type((1,2))) # tuple
205 | print(type(zip([1,2],[3,4]))) # set
206 | ```
207 |
208 | - Casting: Converting one data type to another data type. We use _int()_, _float()_, _str()_, _list_, _set_
209 | 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.
210 |
211 | **Example:**
212 |
213 | ```py
214 | # int to float
215 | num_int = 10
216 | print('num_int',num_int) # 10
217 | num_float = float(num_int)
218 | print('num_float:', num_float) # 10.0
219 |
220 | # float to int
221 | gravity = 9.81
222 | print(int(gravity)) # 9
223 |
224 | # int to str
225 | num_int = 10
226 | print(num_int) # 10
227 | num_str = str(num_int)
228 | print(num_str) # '10'
229 |
230 | # str to int or float
231 | num_str = '10.6'
232 | print('num_int', int(num_str)) # 10
233 | print('num_float', float(num_str)) # 10.6
234 |
235 | # str to list
236 | first_name = 'Asabeneh'
237 | print(first_name) # 'Asabeneh'
238 | first_name_to_list = list(first_name)
239 | print(first_name_to_list) # ['A', 's', 'a', 'b', 'e', 'n', 'e', 'h']
240 | ```
241 |
242 | ## Numbers
243 |
244 | Number data types in Python:
245 |
246 | 1. Integers: Integer(negative, zero and positive) numbers
247 | Example:
248 | ... -3, -2, -1, 0, 1, 2, 3 ...
249 |
250 | 2. Floating Point Numbers(Decimal numbers)
251 | Example:
252 | ... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ...
253 |
254 | 3. Complex Numbers
255 | Example:
256 | 1 + j, 2 + 4j, 1 - 1j
257 |
258 | 🌕 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.
259 |
260 | ## 💻 Exercises - Day 2
261 |
262 | ### Exercises: Level 1
263 |
264 | 1. Inside 30DaysOfPython create a folder called day_2. Inside this folder create a file named variables.py
265 | 2. Write a python comment saying 'Day 2: 30 Days of python programming'
266 | 3. Declare a first name variable and assign a value to it
267 | 4. Declare a last name variable and assign a value to it
268 | 5. Declare a full name variable and assign a value to it
269 | 6. Declare a country variable and assign a value to it
270 | 7. Declare a city variable and assign a value to it
271 | 8. Declare an age variable and assign a value to it
272 | 9. Declare a year variable and assign a value to it
273 | 10. Declare a variable is_married and assign a value to it
274 | 11. Declare a variable is_true and assign a value to it
275 | 12. Declare a variable is_light_on and assign a value to it
276 | 13. Declare multiple variable on one line
277 |
278 | ### Exercises: Level 2
279 |
280 | 1. Check the data type of all your variables using type() built-in function
281 | 1. Using the _len()_ built-in function, find the length of your first name
282 | 1. Compare the length of your first name and your last name
283 | 1. Declare 5 as num_one and 4 as num_two
284 | 1. Add num_one and num_two and assign the value to a variable total
285 | 2. Subtract num_two from num_one and assign the value to a variable diff
286 | 3. Multiply num_two and num_one and assign the value to a variable product
287 | 4. Divide num_one by num_two and assign the value to a variable division
288 | 5. Use modulus division to find num_two divided by num_one and assign the value to a variable remainder
289 | 6. Calculate num_one to the power of num_two and assign the value to a variable exp
290 | 7. Find floor division of num_one by num_two and assign the value to a variable floor_division
291 | 1. The radius of a circle is 30 meters.
292 | 1. Calculate the area of a circle and assign the value to a variable name of _area_of_circle_
293 | 2. Calculate the circumference of a circle and assign the value to a variable name of _circum_of_circle_
294 | 3. Take radius as user input and calculate the area.
295 | 1. 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
296 | 1. Run help('keywords') in Python shell or in your file to check for the Python reserved words or keywords
297 |
298 | 🎉 CONGRATULATIONS ! 🎉
299 |
300 | [<< Day 1](../readme.md) | [Day 3 >>](../03_Day_Operators/03_operators.md)
301 |
--------------------------------------------------------------------------------
/02_Day_Variables_builtin_functions/variables.py:
--------------------------------------------------------------------------------
1 |
2 | # Variables in Python
3 |
4 | first_name = 'Asabeneh'
5 | last_name = 'Yetayeh'
6 | country = 'Finland'
7 | city = 'Helsinki'
8 | age = 250
9 | is_married = True
10 | skills = ['HTML', 'CSS', 'JS', 'React', 'Python']
11 | person_info = {
12 | 'firstname':'Asabeneh',
13 | 'lastname':'Yetayeh',
14 | 'country':'Finland',
15 | 'city':'Helsinki'
16 | }
17 |
18 | # Printing the values stored in the variables
19 |
20 | print('First name:', first_name)
21 | print('First name length:', len(first_name))
22 | print('Last name: ', last_name)
23 | print('Last name length: ', len(last_name))
24 | print('Country: ', country)
25 | print('City: ', city)
26 | print('Age: ', age)
27 | print('Married: ', is_married)
28 | print('Skills: ', skills)
29 | print('Person information: ', person_info)
30 |
31 | # Declaring multiple variables in one line
32 |
33 | first_name, last_name, country, age, is_married = 'Asabeneh', 'Yetayeh', 'Helsink', 250, True
34 |
35 | print(first_name, last_name, country, age, is_married)
36 | print('First name:', first_name)
37 | print('Last name: ', last_name)
38 | print('Country: ', country)
39 | print('Age: ', age)
40 | print('Married: ', is_married)
--------------------------------------------------------------------------------
/03_Day_Operators/03_operators.md:
--------------------------------------------------------------------------------
1 |
15 |
16 | [<< Day 2](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) | [Day 4 >>](../04_Day_Strings/04_strings.md)
17 |
18 | 
19 |
20 | - [📘 Day 3](#-day-3)
21 | - [Boolean](#boolean)
22 | - [Operators](#operators)
23 | - [Assignment Operators](#assignment-operators)
24 | - [Arithmetic Operators:](#arithmetic-operators)
25 | - [Comparison Operators](#comparison-operators)
26 | - [Logical Operators](#logical-operators)
27 | - [💻 Exercises - Day 3](#-exercises---day-3)
28 |
29 | # 📘 Day 3
30 |
31 | ## Boolean
32 |
33 | A boolean data type represents one of the two values: _True_ or _False_. The use of these data types will be clear once we start using the comparison operator. The first letter **T** for True and **F** for False should be capital unlike JavaScript.
34 | **Example: Boolean Values**
35 |
36 | ```py
37 | print(True)
38 | print(False)
39 | ```
40 |
41 | ## Operators
42 |
43 | Python language supports several types of operators. In this section, we will focus on few of them.
44 |
45 | ### Assignment Operators
46 |
47 | 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).
48 |
49 | 
50 |
51 | ### Arithmetic Operators:
52 |
53 | - Addition(+): a + b
54 | - Subtraction(-): a - b
55 | - Multiplication(*): a * b
56 | - Division(/): a / b
57 | - Modulus(%): a % b
58 | - Floor division(//): a // b
59 | - Exponentiation(**): a ** b
60 |
61 | 
62 |
63 | **Example:Integers**
64 |
65 | ```py
66 | # Arithmetic Operations in Python
67 | # Integers
68 |
69 | print('Addition: ', 1 + 2) # 3
70 | print('Subtraction: ', 2 - 1) # 1
71 | print('Multiplication: ', 2 * 3) # 6
72 | print ('Division: ', 4 / 2) # 2.0 Division in Python gives floating number
73 | print('Division: ', 6 / 2) # 3.0
74 | print('Division: ', 7 / 2) # 3.5
75 | print('Division without the remainder: ', 7 // 2) # 3, gives without the floating number or without the remaining
76 | print ('Division without the remainder: ',7 // 3) # 2
77 | print('Modulus: ', 3 % 2) # 1, Gives the remainder
78 | print('Exponentiation: ', 2 ** 3) # 9 it means 2 * 2 * 2
79 | ```
80 |
81 | **Example:Floats**
82 |
83 | ```py
84 | # Floating numbers
85 | print('Floating Point Number, PI', 3.14)
86 | print('Floating Point Number, gravity', 9.81)
87 | ```
88 |
89 | **Example:Complex numbers**
90 |
91 | ```py
92 | # Complex numbers
93 | print('Complex number: ', 1 + 1j)
94 | print('Multiplying complex numbers: ',(1 + 1j) * (1 - 1j))
95 | ```
96 |
97 | 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.
98 |
99 | **Example:**
100 |
101 | ```python
102 | # Declaring the variable at the top first
103 |
104 | a = 3 # a is a variable name and 3 is an integer data type
105 | b = 2 # b is a variable name and 3 is an integer data type
106 |
107 | # Arithmetic operations and assigning the result to a variable
108 | total = a + b
109 | diff = a - b
110 | product = a * b
111 | division = a / b
112 | remainder = a % b
113 | floor_division = a // b
114 | exponential = a ** b
115 |
116 | # I should have used sum instead of total but sum is a built-in function - try to avoid overriding built-in functions
117 | print(total) # if you do not label your print with some string, you never know where the result is coming from
118 | print('a + b = ', total)
119 | print('a - b = ', diff)
120 | print('a * b = ', product)
121 | print('a / b = ', division)
122 | print('a % b = ', remainder)
123 | print('a // b = ', floor_division)
124 | print('a ** b = ', exponentiation)
125 | ```
126 |
127 | **Example:**
128 |
129 | ```py
130 | print('== Addition, Subtraction, Multiplication, Division, Modulus ==')
131 |
132 | # Declaring values and organizing them together
133 | num_one = 3
134 | num_two = 4
135 |
136 | # Arithmetic operations
137 | total = num_one + num_two
138 | diff = num_two - num_one
139 | product = num_one * num_two
140 | div = num_two / num_one
141 | remainder = num_two % num_one
142 |
143 | # Printing values with label
144 | print('total: ', total)
145 | print('difference: ', diff)
146 | print('product: ', product)
147 | print('division: ', div)
148 | print('remainder: ', remainder)
149 | ```
150 |
151 | Let us start start connecting the dots and start making use of what we already know to calculate (area, volume,density, weight, perimeter, distance, force).
152 |
153 | **Example:**
154 |
155 | ```py
156 | # Calculating area of a circle
157 | radius = 10 # radius of a circle
158 | area_of_circle = 3.14 * radius ** 2 # two * sign means exponent or power
159 | print('Area of a circle:', area_of_circle)
160 |
161 | # Calculating area of a rectangle
162 | length = 10
163 | width = 20
164 | area_of_rectangle = length * width
165 | print('Area of rectangle:', area_of_rectangle)
166 |
167 | # Calculating a weight of an object
168 | mass = 75
169 | gravity = 9.81
170 | weight = mass * gravity
171 | print(weight, 'N') # Adding unit to the weight
172 |
173 | # Calculate the density of a liquid
174 | mass = 75 # in Kg
175 | volume = 0.075 # in cubic meter
176 | density = mass / volume # 1000 Kg/m^3
177 |
178 | ```
179 |
180 | ### Comparison Operators
181 |
182 | 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).
183 |
184 | 
185 | **Example: Comparison Operators**
186 |
187 | ```py
188 | print(3 > 2) # True, because 3 is greater than 2
189 | print(3 >= 2) # True, because 3 is greater than 2
190 | print(3 < 2) # False, because 3 is greater than 2
191 | print(2 < 3) # True, because 2 is less than 3
192 | print(2 <= 3) # True, because 2 is less than 3
193 | print(3 == 2) # False, because 3 is not equal to 2
194 | print(3 != 2) # True, because 3 is not equal to 2
195 | print(len('mango') == len('avocado')) # False
196 | print(len('mango') != len('avocado')) # True
197 | print(len('mango') < len('avocado')) # True
198 | print(len('milk') != len('meat')) # False
199 | print(len('milk') == len('meat')) # True
200 | print(len('tomato') == len('potato')) # True
201 | print(len('python') > len('dragon')) # False
202 |
203 |
204 | # Comparing something gives either a True or False
205 |
206 | print('True == True: ', True == True)
207 | print('True == False: ', True == False)
208 | print('False == False:', False == False)
209 | ```
210 |
211 | In addition to the above comparison operator Python uses:
212 |
213 | - _is_: Returns true if both variables are the same object(x is y)
214 | - _is not_: Returns true if both variables are not the same object(x is not y)
215 | - _in_: Returns True if the queried list contains a certain item(x in y)
216 | - _not in_: Returns True if the queried list doesn't have a certain item(x in y)
217 |
218 | ```py
219 | print('1 is 1', 1 is 1) # True - because the data values are the same
220 | print('1 is not 2', 1 is not 2) # True - because 1 is not 2
221 | print('A in Asabeneh', 'A' in 'Asabeneh') # True - A found in the string
222 | print('B in Asabeneh', 'B' in 'Asabeneh') # False - there is no uppercase B
223 | print('coding' in 'coding for all') # True - because coding for all has the word coding
224 | print('a in an:', 'a' in 'an') # True
225 | print('4 is 2 ** 2:', 4 is 2 ** 2) # True
226 | ```
227 |
228 | ### Logical Operators
229 |
230 | Unlike other programming languages python uses keywords _and_, _or_ and _not_ for logical operators. Logical operators are used to combine conditional statements:
231 |
232 | 
233 |
234 | ```py
235 | print(3 > 2 and 4 > 3) # True - because both statements are true
236 | print(3 > 2 and 4 < 3) # False - because the second statement is false
237 | print(3 < 2 and 4 < 3) # False - because both statements are false
238 | print('True and True: ', True and True)
239 | print(3 > 2 or 4 > 3) # True - because both statements are true
240 | print(3 > 2 or 4 < 3) # True - because one of the statements is true
241 | print(3 < 2 or 4 < 3) # False - because both statements are false
242 | print('True or False:', True or False)
243 | print(not 3 > 2) # False - because 3 > 2 is true, then not True gives False
244 | print(not True) # False - Negation, the not operator turns true to false
245 | print(not False) # True
246 | print(not not True) # True
247 | print(not not False) # False
248 |
249 | ```
250 |
251 | 🌕 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.
252 |
253 | ## 💻 Exercises - Day 3
254 |
255 | 1. Declare your age as integer variable
256 | 2. Declare your height as a float variable
257 | 3. Declare a variable that store a complex number
258 | 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).
259 |
260 | ```py
261 | Enter base: 20
262 | Enter height: 10
263 | The area of the triangle is 100
264 | ```
265 |
266 | 5. Write a script that prompts the user to enter side a, side b, and side c of the triangle. Calculate the perimeter of the triangle (perimeter = a + b + c).
267 |
268 | ```py
269 | Enter side a: 5
270 | Enter side b: 4
271 | Enter side c: 3
272 | The perimeter of the triangle is 12
273 | ```
274 |
275 | 6. Get length and width of a rectangle using prompt. Calculate its area (area = length x width) and perimeter (perimeter = 2 x (length + width))
276 | 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.
277 | 8. Calculate the slope, x-intercept and y-intercept of y = 2x -2
278 | 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)
279 | 10. Compare the slopes in tasks 8 and 9.
280 | 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.
281 | 12. Find the length of 'python' and 'dragon' and make a falsy comparison statement.
282 | 13. Use _and_ operator to check if 'on' is found in both 'python' and 'dragon'
283 | 14. _I hope this course is not full of jargon_. Use _in_ operator to check if _jargon_ is in the sentence.
284 | 15. There is no 'on' in both dragon and python
285 | 16. Find the length of the text _python_ and convert the value to float and convert it to string
286 | 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?
287 | 18. Check if the floor division of 7 by 3 is equal to the int converted value of 2.7.
288 | 19. Check if type of '10' is equal to type of 10
289 | 20. Check if int('9.8') is equal to 10
290 | 21. Writ a script that prompts the user to enter hours and rate per hour. Calculate pay of the person?
291 |
292 | ```py
293 | Enter hours: 40
294 | Enter rate per hour: 28
295 | Your weekly earning is 1120
296 | ```
297 |
298 | 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
299 |
300 | ```py
301 | Enter number of years you have lived: 100
302 | You have lived for 3153600000 seconds.
303 | ```
304 |
305 | 23. Write a Python script that displays the following table
306 |
307 | ```py
308 | 1 1 1 1 1
309 | 2 1 2 4 8
310 | 3 1 3 9 27
311 | 4 1 4 16 64
312 | 5 1 5 25 125
313 | ```
314 |
315 | 🎉 CONGRATULATIONS ! 🎉
316 |
317 | [<< Day 2](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) | [Day 4 >>](../04_Day_Strings/04_strings.md)
318 |
--------------------------------------------------------------------------------
/03_Day_Operators/day-3.py:
--------------------------------------------------------------------------------
1 | # Arithmetic Operations in Python
2 | # Integers
3 |
4 | print('Addition: ', 1 + 2)
5 | print('Subtraction: ', 2 - 1)
6 | print('Multiplication: ', 2 * 3)
7 | print ('Division: ', 4 / 2) # Division in python gives floating number
8 | print('Division: ', 6 / 2)
9 | print('Division: ', 7 / 2)
10 | print('Division without the remainder: ', 7 // 2) # gives without the floating number or without the remaining
11 | print('Modulus: ', 3 % 2) # Gives the remainder
12 | print ('Division without the remainder: ', 7 // 3)
13 | print('Exponential: ', 3 ** 2) # it means 3 * 3
14 |
15 | # Floating numbers
16 | print('Floating Number,PI', 3.14)
17 | print('Floating Number, gravity', 9.81)
18 |
19 | # Complex numbers
20 | print('Complex number: ', 1 + 1j)
21 | print('Multiplying complex number: ',(1 + 1j) * (1-1j))
22 |
23 | # Declaring the variable at the top first
24 |
25 | a = 3 # a is a variable name and 3 is an integer data type
26 | b = 2 # b is a variable name and 3 is an integer data type
27 |
28 | # Arithmetic operations and assigning the result to a variable
29 | total = a + b
30 | diff = a - b
31 | product = a * b
32 | division = a / b
33 | remainder = a % b
34 | floor_division = a // b
35 | exponential = a ** b
36 |
37 | # I should have used sum instead of total but sum is a built-in function try to avoid overriding builtin functions
38 | print(total) # if you don't label your print with some string, you never know from where is the result is coming
39 | print('a + b = ', total)
40 | print('a - b = ', diff)
41 | print('a * b = ', product)
42 | print('a / b = ', division)
43 | print('a % b = ', remainder)
44 | print('a // b = ', floor_division)
45 | print('a ** b = ', exponential)
46 |
47 | # Declaring values and organizing them together
48 | num_one = 3
49 | num_two = 4
50 |
51 | # Arithmetic operations
52 | total = num_one + num_two
53 | diff = num_two - num_one
54 | product = num_one * num_two
55 | div = num_two / num_two
56 | remainder = num_two % num_one
57 |
58 | # Printing values with label
59 | print('total: ', total)
60 | print('difference: ', diff)
61 | print('product: ', product)
62 | print('division: ', div)
63 | print('remainder: ', remainder)
64 |
65 |
66 | # Calculating area of a circle
67 | radius = 10 # radius of a circle
68 | area_of_circle = 3.14 * radius ** 2 # two * sign means exponent or power
69 | print('Area of a circle:', area_of_circle)
70 |
71 | # Calculating area of a rectangle
72 | length = 10
73 | width = 20
74 | area_of_rectangle = length * width
75 | print('Area of rectangle:', area_of_rectangle)
76 |
77 | # Calculating a weight of an object
78 | mass = 75
79 | gravity = 9.81
80 | weight = mass * gravity
81 | print(weight, 'N')
82 |
83 | print(3 > 2) # True, because 3 is greater than 2
84 | print(3 >= 2) # True, because 3 is greater than 2
85 | print(3 < 2) # False, because 3 is greater than 2
86 | print(2 < 3) # True, because 2 is less than 3
87 | print(2 <= 3) # True, because 2 is less than 3
88 | print(3 == 2) # False, because 3 is not equal to 2
89 | print(3 != 2) # True, because 3 is not equal to 2
90 | print(len('mango') == len('avocado')) # False
91 | print(len('mango') != len('avocado')) # True
92 | print(len('mango') < len('avocado')) # True
93 | print(len('milk') != len('meat')) # False
94 | print(len('milk') == len('meat')) # True
95 | print(len('tomato') == len('potato')) # True
96 | print(len('python') > len('dragon')) # False
97 |
98 | # Boolean comparison
99 | print('True == True: ', True == True)
100 | print('True == False: ', True == False)
101 | print('False == False:', False == False)
102 | print('True and True: ', True and True)
103 | print('True or False:', True or False)
104 |
105 | # Another way comparison
106 | print('1 is 1', 1 is 1) # True - because the data values are the same
107 | print('1 is not 2', 1 is not 2) # True - because 1 is not 2
108 | print('A in Asabeneh', 'A' in 'Asabeneh') # True - A found in the string
109 | print('B in Asabeneh', 'B' in 'Asabeneh') # False -there is no uppercase B
110 | print('coding' in 'coding for all') # True - because coding for all has the word coding
111 | print('a in an:', 'a' in 'an') # True
112 | print('4 is 2 ** 2:', 4 is 2 ** 2) # True
113 |
114 | print(3 > 2 and 4 > 3) # True - because both statements are true
115 | print(3 > 2 and 4 < 3) # False - because the second statement is false
116 | print(3 < 2 and 4 < 3) # False - because both statements are false
117 | print(3 > 2 or 4 > 3) # True - because both statements are true
118 | print(3 > 2 or 4 < 3) # True - because one of the statement is true
119 | print(3 < 2 or 4 < 3) # False - because both statements are false
120 | print(not 3 > 2) # False - because 3 > 2 is true, then not True gives False
121 | print(not True) # False - Negation, the not operator turns true to false
122 | print(not False) # True
123 | print(not not True) # True
124 | print(not not False) # False
--------------------------------------------------------------------------------
/04_Day_Strings/day_4.py:
--------------------------------------------------------------------------------
1 |
2 | # Single line comment
3 | letter = 'P' # A string could be a single character or a bunch of texts
4 | print(letter) # P
5 | print(len(letter)) # 1
6 | greeting = 'Hello, World!' # String could be a single or double quote,"Hello, World!"
7 | print(greeting) # Hello, World!
8 | print(len(greeting)) # 13
9 | sentence = "I hope you are enjoying 30 days of python challenge"
10 | print(sentence)
11 |
12 | # Multiline String
13 | multiline_string = '''I am a teacher and enjoy teaching.
14 | I didn't find anything as rewarding as empowering people.
15 | That is why I created 30 days of python.'''
16 | print(multiline_string)
17 | # Another way of doing the same thing
18 | multiline_string = """I am a teacher and enjoy teaching.
19 | I didn't find anything as rewarding as empowering people.
20 | That is why I created 30 days of python."""
21 | print(multiline_string)
22 |
23 | # String Concatenation
24 | first_name = 'Asabeneh'
25 | last_name = 'Yetayeh'
26 | space = ' '
27 | full_name = first_name + space + last_name
28 | print(full_name) # Asabeneh Yetayeh
29 | # Checking length of a string using len() builtin function
30 | print(len(first_name)) # 8
31 | print(len(last_name)) # 7
32 | print(len(first_name) > len(last_name)) # True
33 | print(len(full_name)) # 15
34 |
35 | #### Unpacking characters
36 | language = 'Python'
37 | a,b,c,d,e,f = language # unpacking sequence characters into variables
38 | print(a) # P
39 | print(b) # y
40 | print(c) # t
41 | print(d) # h
42 | print(e) # o
43 | print(f) # n
44 |
45 | # Accessing characters in strings by index
46 | language = 'Python'
47 | first_letter = language[0]
48 | print(first_letter) # P
49 | second_letter = language[1]
50 | print(second_letter) # y
51 | last_index = len(language) - 1
52 | last_letter = language[last_index]
53 | print(last_letter) # n
54 |
55 | # If we want to start from right end we can use negative indexing. -1 is the last index
56 | language = 'Python'
57 | last_letter = language[-1]
58 | print(last_letter) # n
59 | second_last = language[-2]
60 | print(second_last) # o
61 |
62 | # Slicing
63 |
64 | language = 'Python'
65 | first_three = language[0:3] # starts at zero index and up to 3 but not include 3
66 | last_three = language[3:6]
67 | print(last_three) # hon
68 | # Another way
69 | last_three = language[-3:]
70 | print(last_three) # hon
71 | last_three = language[3:]
72 | print(last_three) # hon
73 |
74 | # Skipping character while splitting Python strings
75 | language = 'Python'
76 | pto = language[0:6:2] #
77 | print(pto) # pto
78 |
79 | # Escape sequence
80 | print('I hope every one enjoying the python challenge.\nDo you ?') # line break
81 | print('Days\tTopics\tExercises')
82 | print('Day 1\t3\t5')
83 | print('Day 2\t3\t5')
84 | print('Day 3\t3\t5')
85 | print('Day 4\t3\t5')
86 | print('This is a back slash symbol (\\)') # To write a back slash
87 | print('In every programming language it starts with \"Hello, World!\"')
88 |
89 | ## String Methods
90 | # capitalize(): Converts the first character the string to Capital Letter
91 |
92 | challenge = 'thirty days of python'
93 | print(challenge.capitalize()) # 'Thirty days of python'
94 |
95 | # count(): returns occurrences of substring in string, count(substring, start=.., end=..)
96 |
97 | challenge = 'thirty days of python'
98 | print(challenge.count('y')) # 3
99 | print(challenge.count('y', 7, 14)) # 1
100 | print(challenge.count('th')) # 2`
101 |
102 | # endswith(): Checks if a string ends with a specified ending
103 |
104 | challenge = 'thirty days of python'
105 | print(challenge.endswith('on')) # True
106 | print(challenge.endswith('tion')) # False
107 |
108 | # expandtabs(): Replaces tab character with spaces, default tab size is 8. It takes tab size argument
109 |
110 | challenge = 'thirty\tdays\tof\tpython'
111 | print(challenge.expandtabs()) # 'thirty days of python'
112 | print(challenge.expandtabs(10)) # 'thirty days of python'
113 |
114 | # find(): Returns the index of first occurrence of substring
115 |
116 | challenge = 'thirty days of python'
117 | print(challenge.find('y')) # 5
118 | print(challenge.find('th')) # 0
119 |
120 | # format() formats string into nicer output
121 | first_name = 'Asabeneh'
122 | last_name = 'Yetayeh'
123 | job = 'teacher'
124 | country = 'Finland'
125 | sentence = 'I am {} {}. I am a {}. I live in {}.'.format(first_name, last_name, job, country)
126 | print(sentence) # I am Asabeneh Yetayeh. I am a teacher. I live in Finland.
127 |
128 | radius = 10
129 | pi = 3.14
130 | area = pi # radius ## 2
131 | result = 'The area of circle with {} is {}'.format(str(radius), str(area))
132 | print(result) # The area of circle with 10 is 314.0
133 |
134 | # index(): Returns the index of substring
135 | challenge = 'thirty days of python'
136 | print(challenge.find('y')) # 5
137 | print(challenge.find('th')) # 0
138 |
139 | # isalnum(): Checks alphanumeric character
140 |
141 | challenge = 'ThirtyDaysPython'
142 | print(challenge.isalnum()) # True
143 |
144 | challenge = '30DaysPython'
145 | print(challenge.isalnum()) # True
146 |
147 | challenge = 'thirty days of python'
148 | print(challenge.isalnum()) # False
149 |
150 | challenge = 'thirty days of python 2019'
151 | print(challenge.isalnum()) # False
152 |
153 | # isalpha(): Checks if all characters are alphabets
154 |
155 | challenge = 'thirty days of python'
156 | print(challenge.isalpha()) # True
157 | num = '123'
158 | print(num.isalpha()) # False
159 |
160 | # isdecimal(): Checks Decimal Characters
161 |
162 | challenge = 'thirty days of python'
163 | print(challenge.find('y')) # 5
164 | print(challenge.find('th')) # 0
165 |
166 | # isdigit(): Checks Digit Characters
167 |
168 | challenge = 'Thirty'
169 | print(challenge.isdigit()) # False
170 | challenge = '30'
171 | print(challenge.digit()) # True
172 |
173 | # isdecimal():Checks decimal characters
174 |
175 | num = '10'
176 | print(num.isdecimal()) # True
177 | num = '10.5'
178 | print(num.isdecimal()) # False
179 |
180 |
181 | # isidentifier():Checks for valid identifier means it check if a string is a valid variable name
182 |
183 | challenge = '30DaysOfPython'
184 | print(challenge.isidentifier()) # False, because it starts with a number
185 | challenge = 'thirty_days_of_python'
186 | print(challenge.isidentifier()) # True
187 |
188 |
189 | # islower():Checks if all alphabets in a string are lowercase
190 |
191 | challenge = 'thirty days of python'
192 | print(challenge.islower()) # True
193 | challenge = 'Thirty days of python'
194 | print(challenge.islower()) # False
195 |
196 | # isupper(): returns if all characters are uppercase characters
197 |
198 | challenge = 'thirty days of python'
199 | print(challenge.isupper()) # False
200 | challenge = 'THIRTY DAYS OF PYTHON'
201 | print(challenge.isupper()) # True
202 |
203 |
204 | # isnumeric():Checks numeric characters
205 |
206 | num = '10'
207 | print(num.isnumeric()) # True
208 | print('ten'.isnumeric()) # False
209 |
210 | # join(): Returns a concatenated string
211 |
212 | web_tech = ['HTML', 'CSS', 'JavaScript', 'React']
213 | result = '#, '.join(web_tech)
214 | print(result) # 'HTML# CSS# JavaScript# React'
215 |
216 | # strip(): Removes both leading and trailing characters
217 |
218 | challenge = ' thirty days of python '
219 | print(challenge.strip('y')) # 5
220 |
221 | # replace(): Replaces substring inside
222 |
223 | challenge = 'thirty days of python'
224 | print(challenge.replace('python', 'coding')) # 'thirty days of coding'
225 |
226 | # split():Splits String from Left
227 |
228 | challenge = 'thirty days of python'
229 | print(challenge.split()) # ['thirty', 'days', 'of', 'python']
230 |
231 | # title(): Returns a Title Cased String
232 |
233 | challenge = 'thirty days of python'
234 | print(challenge.title()) # Thirty Days Of Python
235 |
236 | # swapcase(): Checks if String Starts with the Specified String
237 |
238 | challenge = 'thirty days of python'
239 | print(challenge.swapcase()) # THIRTY DAYS OF PYTHON
240 | challenge = 'Thirty Days Of Python'
241 | print(challenge.swapcase()) # tHIRTY dAYS oF pYTHON
242 |
243 | # startswith(): Checks if String Starts with the Specified String
244 |
245 | challenge = 'thirty days of python'
246 | print(challenge.startswith('thirty')) # True
247 | challenge = '30 days of python'
248 | print(challenge.startswith('thirty')) # False
--------------------------------------------------------------------------------
/05_Day_Lists/day_5.py:
--------------------------------------------------------------------------------
1 | empty_list = list() # this is an empty list, no item in the list
2 | print(len(empty_list)) # 0
3 |
4 | fruits = ['banana', 'orange', 'mango', 'lemon'] # list of fruits
5 | vegetables = ['Tomato', 'Potato', 'Cabbage','Onion', 'Carrot'] # list of vegetables
6 | animal_products = ['milk', 'meat', 'butter', 'yoghurt'] # list of animal products
7 | web_techs = ['HTML', 'CSS', 'JS', 'React','Redux', 'Node', 'MongDB'] # list of web technologies
8 | countries = ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway']
9 |
10 | # Print the lists and it length
11 | print('Fruits:', fruits)
12 | print('Number of fruits:', len(fruits))
13 | print('Vegetables:', vegetables)
14 | print('Number of vegetables:', len(vegetables))
15 | print('Animal products:',animal_products)
16 | print('Number of animal products:', len(animal_products))
17 | print('Web technologies:', web_techs)
18 | print('Number of web technologies:', len(web_techs))
19 | print('Number of countries:', len(countries))
20 |
21 | # Modifying list
22 |
23 | fruits = ['banana', 'orange', 'mango', 'lemon']
24 | first_fruit = fruits[0] # we are accessing the first item using its index
25 | print(first_fruit) # banana
26 | second_fruit = fruits[1]
27 | print(second_fruit) # orange
28 | last_fruit = fruits[3]
29 | print(last_fruit) # lemon
30 | # Last index
31 | last_index = len(fruits) - 1
32 | last_fruit = fruits[last_index]
33 |
34 | # Accessing items
35 | fruits = ['banana', 'orange', 'mango', 'lemon']
36 | last_fruit = fruits[-1]
37 | second_last = fruits[-2]
38 | print(last_fruit) # lemon
39 | print(second_last) # mango
40 |
41 | # Slicing items
42 | fruits = ['banana', 'orange', 'mango', 'lemon']
43 | all_fruits = fruits[0:4] # it returns all the fruits
44 | # this is also give the same result as the above
45 | all_fruits = fruits[0:] # if we don't set where to stop it takes all the rest
46 | orange_and_mango = fruits[1:3] # it does not include the end index
47 | orange_mango_lemon = fruits[1:]
48 |
49 | fruits = ['banana', 'orange', 'mango', 'lemon']
50 | all_fruits = fruits[-4:] # it returns all the fruits
51 | # this is also give the same result as the above
52 | orange_and_mango = fruits[-3:-1] # it does not include the end index
53 | orange_mango_lemon = fruits[-3:]
54 |
55 |
56 | fruits = ['banana', 'orange', 'mango', 'lemon']
57 | fruits[0] = 'Avocado'
58 | print(fruits) # ['avocado', 'orange', 'mango', 'lemon']
59 | fruits[1] = 'apple'
60 | print(fruits) # ['avocado', 'apple', 'mango', 'lemon']
61 | last_index = len(fruits) - 1
62 | fruits[last_index] = 'lime'
63 | print(fruits) # ['avocado', 'apple', 'mango', 'lime']
64 |
65 | # checking items
66 | fruits = ['banana', 'orange', 'mango', 'lemon']
67 | does_exist = 'banana' in fruits
68 | print(does_exist) # True
69 | does_exist = 'lime' in fruits
70 | print(does_exist) # False
71 |
72 | # Append
73 | fruits = ['banana', 'orange', 'mango', 'lemon']
74 | fruits.append('apple')
75 | print(fruits) # ['banana', 'orange', 'mango', 'lemon', 'apple']
76 | fruits.append('lime') # ['banana', 'orange', 'mango', 'lemon', 'apple', 'lime]
77 | print(fruits)
78 |
79 | # insert
80 | fruits = ['banana', 'orange', 'mango', 'lemon']
81 | fruits.insert(2, 'apple') # insert apple between orange and mango
82 | print(fruits) # ['banana', 'orange', 'apple', 'mango', 'lemon']
83 | fruits.insert(3, 'lime') # ['banana', 'orange', 'apple', 'mango', 'lime','lemon',]
84 | print(fruits)
85 |
86 | # remove
87 | fruits = ['banana', 'orange', 'mango', 'lemon']
88 | fruits.remove('banana')
89 | print(fruits) # ['orange', 'mango', 'lemon']
90 | fruits.remove('lemon')
91 | print(fruits) # ['orange', 'mango']
92 |
93 | # pop
94 | fruits = ['banana', 'orange', 'mango', 'lemon']
95 | fruits.pop()
96 | print(fruits) # ['banana', 'orange', 'mango']
97 |
98 | fruits.pop(0)
99 | print(fruits) # ['orange', 'mango']
100 |
101 | # del
102 | fruits = ['banana', 'orange', 'mango', 'lemon']
103 | del fruits[0]
104 | print(fruits) # ['orange', 'mango', 'lemon']
105 |
106 | del fruits[1]
107 | print(fruits) # ['orange', 'lemon']
108 | del fruits
109 | print(fruits) # This should give: NameError: name 'fruits' is not defined
110 |
111 | # clear
112 | fruits = ['banana', 'orange', 'mango', 'lemon']
113 | fruits.clear()
114 | print(fruits) # []
115 |
116 | # copying a lits
117 |
118 | fruits = ['banana', 'orange', 'mango', 'lemon']
119 | fruits_copy = fruits.copy()
120 | print(fruits_copy) # ['banana', 'orange', 'mango', 'lemon']
121 |
122 | # join
123 | positive_numbers = [1, 2, 3,4,5]
124 | zero = [0]
125 | negative_numbers = [-5,-4,-3,-2,-1]
126 | integers = negative_numbers + zero + positive_numbers
127 | print(integers)
128 | fruits = ['banana', 'orange', 'mango', 'lemon']
129 | vegetables = ['Tomato', 'Potato', 'Cabbage','Onion', 'Carrot']
130 | fruits_and_vegetables = fruits + vegetables
131 | print(fruits_and_vegetables )
132 |
133 | # join with extend
134 | num1 = [0, 1, 2, 3]
135 | num2= [4, 5,6]
136 | num1.extend(num2)
137 | print('Numbers:', num1)
138 | negative_numbers = [-5,-4,-3,-2,-1]
139 | positive_numbers = [1, 2, 3,4,5]
140 | zero = [0]
141 |
142 | negative_numbers.extend(zero)
143 | negative_numbers.extend(positive_numbers)
144 | print('Integers:', negative_numbers)
145 | fruits = ['banana', 'orange', 'mango', 'lemon']
146 | vegetables = ['Tomato', 'Potato', 'Cabbage','Onion', 'Carrot']
147 | fruits.extend(vegetables)
148 | print('Fruits and vegetables:', fruits )
149 |
150 | # count
151 | fruits = ['banana', 'orange', 'mango', 'lemon']
152 | print(fruits.count('orange')) # 1
153 | ages = [22, 19, 24, 25, 26, 24, 25, 24]
154 | print(ages.count(24)) # 3
155 |
156 | # index
157 | fruits = ['banana', 'orange', 'mango', 'lemon']
158 | print(fruits.index('orange')) # 1
159 | ages = [22, 19, 24, 25, 26, 24, 25, 24]
160 | print(ages.index(24))
161 | # Reverse
162 | fruits = ['banana', 'orange', 'mango', 'lemon']
163 | fruits.reverse()
164 | print(fruits)
165 | ages = [22, 19, 24, 25, 26, 24, 25, 24]
166 | ages.reverse()
167 | print(ages)
168 |
169 | # sort
170 | fruits = ['banana', 'orange', 'mango', 'lemon']
171 | fruits.sort()
172 | print(fruits)
173 | fruits.sort(reverse=True)
174 | print(fruits)
175 | ages = [22, 19, 24, 25, 26, 24, 25, 24]
176 | ages.sort()
177 | print(ages)
178 | ages.sort(reverse=True)
179 | print(ages)
--------------------------------------------------------------------------------
/06_Day_Tuples/06_tuples.md:
--------------------------------------------------------------------------------
1 |
16 |
17 | [<< Day 5](../05_Day_Lists/05_lists.md) | [Day 7 >>](../07_Day_Sets/07_sets.md)
18 |
19 | 
20 |
21 | - [Day 6:](#day-6)
22 | - [Tuples](#tuples)
23 | - [Creating a Tuple](#creating-a-tuple)
24 | - [Tuple length](#tuple-length)
25 | - [Accessing Tuple Items](#accessing-tuple-items)
26 | - [Slicing tuples](#slicing-tuples)
27 | - [Changing Tuples to Lists](#changing-tuples-to-lists)
28 | - [Checking an Item in a Tuple](#checking-an-item-in-a-tuple)
29 | - [Joining Tuples](#joining-tuples)
30 | - [Deleting Tuples](#deleting-tuples)
31 | - [💻 Exercises: Day 6](#-exercises-day-6)
32 | - [Exercises: Level 1](#exercises-level-1)
33 | - [Exercises: Level 2](#exercises-level-2)
34 |
35 | # Day 6:
36 |
37 | ## Tuples
38 |
39 | 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:
40 |
41 | - tuple(): to create an empty tuple
42 | - count(): to count the number of a specified item in a tuple
43 | - index(): to find the index of a specified item in a tuple
44 | - + operator: to join two or more tuples and to create a new tuple
45 |
46 | ### Creating a Tuple
47 |
48 | - Empty tuple: Creating an empty tuple
49 |
50 | ```py
51 | # syntax
52 | empty_tuple = ()
53 | # or using the tuple constructor
54 | empty_tuple = tuple()
55 | ```
56 |
57 | - Tuple with initial values
58 |
59 | ```py
60 | # syntax
61 | tpl = ('item1', 'item2','item3')
62 | ```
63 |
64 | ```py
65 | fruits = ('banana', 'orange', 'mango', 'lemon')
66 | ```
67 |
68 | ### Tuple length
69 |
70 | We use the _len()_ method to get the length of a tuple.
71 |
72 | ```py
73 | # syntax
74 | tpl = ('item1', 'item2', 'item3')
75 | len(tpl)
76 | ```
77 |
78 | ### Accessing Tuple Items
79 |
80 | - Positive Indexing
81 | Similar to the list data type we use positive or negative indexing to access tuple items.
82 | 
83 |
84 | ```py
85 | # Syntax
86 | tpl = ('item1', 'item2', 'item3')
87 | first_item = tpl[0]
88 | second_item = tpl[1]
89 | ```
90 |
91 | ```py
92 | fruits = ('banana', 'orange', 'mango', 'lemon')
93 | first_fruit = fruits[0]
94 | second_fruit = fruits[1]
95 | last_index =len(fruits) - 1
96 | last_fruit = fruits[las_index]
97 | ```
98 |
99 | - Negative indexing
100 | 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.
101 | 
102 |
103 | ```py
104 | # Syntax
105 | tpl = ('item1', 'item2', 'item3','item4')
106 | first_item = tpl[-4]
107 | second_item = tpl[-3]
108 | ```
109 |
110 | ```py
111 | fruits = ('banana', 'orange', 'mango', 'lemon')
112 | first_fruit = fruits[-4]
113 | second_fruit = fruits[-3]
114 | last_fruit = fruits[-1]
115 | ```
116 |
117 | ### Slicing tuples
118 |
119 | 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.
120 |
121 | - Range of Positive Indexes
122 |
123 | ```py
124 | # Syntax
125 | tpl = ('item1', 'item2', 'item3','item4')
126 | all_items = tpl[0:4] # all items
127 | all_items = tpl[0:] # all items
128 | middle_two_items = tpl[1:3] # does not include item at index 3
129 | ```
130 |
131 | ```py
132 | fruits = ('banana', 'orange', 'mango', 'lemon')
133 | all_fruits = fruits[0:4] # all items
134 | all_fruits= fruits[0:] # all items
135 | orange_mango = fruits[1:3] # doesn't include item at index 3
136 | orange_to_the_rest = fruits[1:]
137 | ```
138 |
139 | - Range of Negative Indexes
140 |
141 | ```py
142 | # Syntax
143 | tpl = ('item1', 'item2', 'item3','item4')
144 | all_items = tpl[-4:] # all items
145 | middle_two_items = tpl[-3:-1] # does not include item at index 3 (-1)
146 | ```
147 |
148 | ```py
149 | fruits = ('banana', 'orange', 'mango', 'lemon')
150 | all_fruits = fruits[-4:] # all items
151 | orange_mango = fruits[-3:-1] # doesn't include item at index 3
152 | orange_to_the_rest = fruits[-3:]
153 | ```
154 |
155 | ### Changing Tuples to Lists
156 |
157 | We can change tuples to lists and lists to tuples. Tuple is immutable if we want to modify a tuple we should change it to a list.
158 |
159 | ```py
160 | # Syntax
161 | tpl = ('item1', 'item2', 'item3','item4')
162 | lst = list(tpl)
163 | ```
164 |
165 | ```py
166 | fruits = ('banana', 'orange', 'mango', 'lemon')
167 | fruits = list(fruits)
168 | fruits[0] = 'apple'
169 | print(fruits) # ['apple', 'orange', 'mango', 'lemon']
170 | fruits = tuple(fruits)
171 | print(fruits) # ('apple', 'orange', 'mango', 'lemon')
172 | ```
173 |
174 | ### Checking an Item in a Tuple
175 |
176 | We can check if an item exists or not in a tuple using _in_, it returns a boolean.
177 |
178 | ```py
179 | # Syntax
180 | tpl = ('item1', 'item2', 'item3','item4')
181 | 'item2' in tpl # True
182 | ```
183 |
184 | ```py
185 | fruits = ('banana', 'orange', 'mango', 'lemon')
186 | print('orange' in fruits) # True
187 | print('apple' in fruits) # False
188 | fruits[0] = 'apple' # TypeError: 'tuple' object does not support item assignment
189 | ```
190 |
191 | ### Joining Tuples
192 |
193 | We can join two or more tuples using + operator
194 |
195 | ```py
196 | # syntax
197 | tpl1 = ('item1', 'item2', 'item3')
198 | tpl2 = ('item4', 'item5','item6')
199 | tpl3 = tpl1 + tpl2
200 | ```
201 |
202 | ```py
203 | fruits = ('banana', 'orange', 'mango', 'lemon')
204 | vegetables = ('Tomato', 'Potato', 'Cabbage','Onion', 'Carrot')
205 | fruits_and_vegetables = fruits + vegetables
206 | ```
207 |
208 | ### Deleting Tuples
209 |
210 | It is not possible to remove a single item in a tuple but it is possible to delete the tuple itself using _del_.
211 |
212 | ```py
213 | # syntax
214 | tpl1 = ('item1', 'item2', 'item3')
215 | del tpl1
216 |
217 | ```
218 |
219 | ```py
220 | fruits = ('banana', 'orange', 'mango', 'lemon')
221 | del fruits
222 | ```
223 |
224 | 🌕 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.
225 |
226 | ## 💻 Exercises: Day 6
227 |
228 | ### Exercises: Level 1
229 |
230 | 1. Create an empty tuple
231 | 2. Create a tuple containing names of your sisters and your brothers (imaginary siblings are fine)
232 | 3. Join brothers and sisters tuples and assign it to siblings
233 | 4. How many siblings do you have?
234 | 5. Modify the siblings tuple and add the name of your father and mother and assign it to family_members
235 |
236 | ### Exercises: Level 2
237 |
238 | 1. Unpack siblings and parents from family_members
239 | 1. Create fruits, vegetables and animal products tuples. Join the three tuples and assign it to a variable called food_stuff_tp.
240 | 1. Change the about food_stuff_tp tuple to a food_stuff_lt list
241 | 1. Slice out the middle item or items from the food_stuff_tp tuple or food_stuff_lt list.
242 | 1. Slice out the first three items and the last three items from food_staff_lt list
243 | 1. Delete the food_staff_tp tuple completely
244 | 1. Check if an item exists in tuple:
245 |
246 | - Check if 'Estonia' is a nordic country
247 | - Check if 'Iceland' is a nordic country
248 |
249 | ```py
250 | nordic_countries = ('Denmark', 'Finland','Iceland', 'Norway', 'Sweden')
251 | ```
252 |
253 |
254 | [<< Day 5](../05_Day_Lists/05_lists.md) | [Day 7 >>](../07_Day_Sets/07_sets.md)
255 |
--------------------------------------------------------------------------------
/07_Day_Sets/07_sets.md:
--------------------------------------------------------------------------------
1 |
16 |
17 | [<< Day 8](../08_Day_Dictionaries/08_dictionaries.md) | [Day 10 >>](../10_Day_Loops/10_loops.md)
18 |
19 | 
20 |
21 | - [📘 Day 9](#-day-9)
22 | - [Conditionals](#conditionals)
23 | - [If Condition](#if-condition)
24 | - [If Else](#if-else)
25 | - [If Elif Else](#if-elif-else)
26 | - [Short Hand](#short-hand)
27 | - [Nested Conditions](#nested-conditions)
28 | - [If Condition and Logical Operators](#if-condition-and-logical-operators)
29 | - [If and Or Logical Operators](#if-and-or-logical-operators)
30 | - [💻 Exercises: Day 9](#-exercises-day-9)
31 | - [Exercises: Level 1](#exercises-level-1)
32 |
33 | # 📘 Day 9
34 |
35 | ## Conditionals
36 |
37 | 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:
38 |
39 | - Conditional execution: a block of one or more statements will be executed if a certain expression is true
40 | - 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.
41 |
42 | ### If Condition
43 |
44 | 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.
45 |
46 | ```py
47 | # syntax
48 | if condition:
49 | this part of code runs for truthy conditions
50 | ```
51 |
52 | **Example: 1**
53 |
54 | ```py
55 | a = 3
56 | if a > 0:
57 | print('A is a positive number')
58 | # A is a positive number
59 | ```
60 |
61 | As you can see in the example above, 3 is greater than 0. The condition was true and the block code was executed. However, if the condition is false, we do not see the result. In order to see the result of the falsy condition, we should have another block, which is going to be _else_.
62 |
63 | ### If Else
64 |
65 | If condition is true the first block will be executed, if not the else condition will run.
66 |
67 | ```py
68 | # syntax
69 | if condition:
70 | this part of code runs for truthy conditions
71 | else:
72 | this part of code runs for false conditions
73 | ```
74 |
75 | **Example: **
76 |
77 | ```py
78 | a = 3
79 | if a < 0:
80 | print('A is a negative number')
81 | else:
82 | print('A is a positive number')
83 | ```
84 |
85 | The condition above proves false, therefore the else block was executed. How about if our condition is more than two? We could use _ elif_.
86 |
87 | ### If Elif Else
88 |
89 | In our daily life, we make decisions on daily basis. We make decisions not by checking one or two conditions but multiple conditions. As similar to life, programming is also full of conditions. We use _elif_ when we have multiple conditions.
90 |
91 | ```py
92 | # syntax
93 | if condition:
94 | code
95 | elif condition:
96 | code
97 | else:
98 | code
99 |
100 | ```
101 |
102 | **Example: **
103 |
104 | ```py
105 | a = 0
106 | if a > 0:
107 | print('A is a positive number')
108 | elif a < 0:
109 | print('A is a negative number')
110 | else:
111 | print('A is zero')
112 | ```
113 |
114 | ### Short Hand
115 |
116 | ```py
117 | # syntax
118 | code if condition else code
119 | ```
120 |
121 | **Example: **
122 |
123 | ```py
124 | a = 3
125 | print('A is positive') if a > 0 else print('A is negative') # first condition met, 'A is positive' will be printed
126 | ```
127 |
128 | ### Nested Conditions
129 |
130 | Conditions can be nested
131 |
132 | ```py
133 | # syntax
134 | if condition:
135 | code
136 | if condition:
137 | code
138 | ```
139 |
140 | **Example: **
141 |
142 | ```py
143 | a = 0
144 | if a > 0:
145 | if a % 2 == 0:
146 | print('A is a positive and even integer')
147 | else:
148 | print('A is a positive number')
149 | elif a == 0:
150 | print('A is zero')
151 | else:
152 | print('A is a negative number')
153 |
154 | ```
155 |
156 | We can avoid writing nested condition by using logical operator _and_.
157 |
158 | ### If Condition and Logical Operators
159 |
160 | ```py
161 | # syntax
162 | if condition and condition:
163 | code
164 | ```
165 |
166 | **Example: **
167 |
168 | ```py
169 | a = 0
170 | if a > 0 and a % 2 == 0:
171 | print('A is an even and positive integer')
172 | elif a > 0 and a % 2 != 0:
173 | print('A is a positive integer')
174 | elif a == 0:
175 | print('A is zero')
176 | else:
177 | print('A is negative')
178 | ```
179 |
180 | ### If and Or Logical Operators
181 |
182 | ```py
183 | # syntax
184 | if condition or condition:
185 | code
186 | ```
187 |
188 | **Example: **
189 |
190 | ```py
191 | user = 'James'
192 | access_level = 3
193 | if user == 'admin' or access_level >= 4:
194 | print('Access granted!')
195 | else:
196 | print('Access denied!')
197 | ```
198 |
199 | 🌕 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.
200 |
201 | ## 💻 Exercises: Day 9
202 |
203 | ### Exercises: Level 1
204 |
205 | 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:
206 | ```sh
207 | Enter your age: 30
208 | You are old enough to learn to drive.
209 | Output:
210 | Enter your age: 15
211 | You need 3 more years to learn to drive.
212 | ```
213 | 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:
214 | ```sh
215 | Enter your age: 30
216 | You are 5 years older than me.
217 | ```
218 | 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:
219 |
220 | ```sh
221 | Enter number one: 4
222 | Enter number two: 3
223 | 4 is greater than 3
224 | ```
225 |
226 | ### Exercises: Level 2
227 |
228 | 1. Write a code which gives grade to students according to theirs scores:
229 |
230 | ```sh
231 | 80-100, A
232 | 70-89, B
233 | 60-69, C
234 | 50-59, D
235 | 0-49, F
236 | ```
237 | 1. Check if the season is Autumn, Winter, Spring or Summer. If the user input is:
238 | September, October or November, the season is Autumn.
239 | December, January or February, the season is Winter.
240 | March, April or May, the season is Spring
241 | June, July or August, the season is Summer
242 | 2. The following list contains some fruits:
243 | ```sh
244 | fruits = ['banana', 'orange', 'mango', 'lemon']
245 | ```
246 | 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')
247 |
248 | ### Exercises: Level 3
249 |
250 | 1. Here we have a person dictionary. Feel free to modify it!
251 |
252 | ```py
253 | person={
254 | 'first_name': 'Asabeneh',
255 | 'last_name': 'Yetayeh',
256 | 'age': 250,
257 | 'country': 'Finland',
258 | 'is_marred': True,
259 | 'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
260 | 'address': {
261 | 'street': 'Space street',
262 | 'zipcode': '02210'
263 | }
264 | }
265 | ```
266 |
267 | * Check if the person dictionary has skills key, if so print out the middle skill in the skills list.
268 | * Check if the person dictionary has skills key, if so check if the person has 'Python' skill and print out the result.
269 | * 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!
270 | * If the person is married and if he lives in Finland, print the information in the following format:
271 |
272 | ```py
273 | Asabeneh Yetayeh lives in Finland. He is married.
274 | ```
275 |
276 | 🎉 CONGRATULATIONS ! 🎉
277 |
278 | [<< Day 8](../08_Day_Dictionaries/08_dictionaries.md) | [Day 10 >>](../10_Day_Loops/10_loops.md)
279 |
--------------------------------------------------------------------------------
/10_Day_Loops/10_loops.md:
--------------------------------------------------------------------------------
1 |
15 |
16 | [<< Day 9](../09_Day_Conditionals/09_conditionals.md) | [Day 11 >>](../11_Day_Functions/11_functions.md)
17 |
18 | 
19 |
20 | - [📘 Day 10](#-day-10)
21 | - [Loops](#loops)
22 | - [While Loop](#while-loop)
23 | - [Break and Continue - Part 1](#break-and-continue---part-1)
24 | - [For Loop](#for-loop)
25 | - [Break and Continue - Part 2](#break-and-continue---part-2)
26 | - [The Range Function](#the-range-function)
27 | - [Nested For Loop](#nested-for-loop)
28 | - [For Else](#for-else)
29 | - [Pass](#pass)
30 | - [💻 Exercises: Day 10](#-exercises-day-10)
31 | - [Exercises: Level 1](#exercises-level-1)
32 | - [Exercises: Level 2](#exercises-level-2)
33 | - [Exercises: Level 3](#exercises-level-3)
34 |
35 | # 📘 Day 10
36 |
37 | ## Loops
38 |
39 | 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:
40 |
41 | 1. while loop
42 | 2. for loop
43 |
44 | ### While Loop
45 |
46 | We use the reserved word _while_ to make a while loop. It is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the lines of code after the loop will be continued to be executed.
47 |
48 | ```py
49 | # syntax
50 | while condition:
51 | code goes here
52 | ```
53 |
54 | **Example:**
55 |
56 | ```py
57 | count = 0
58 | while count < 5:
59 | print(count)
60 | count = count + 1
61 | #prints from 0 to 4
62 | ```
63 |
64 | In the above while loop, the condition becomes false when count is 5. That is when the loop stops.
65 | If we are interested to run block of code once the condition is no longer true, we can use _else_.
66 |
67 | ```py
68 | # syntax
69 | while condition:
70 | code goes here
71 | else:
72 | code goes here
73 | ```
74 |
75 | **Example:**
76 |
77 | ```py
78 | count = 0
79 | while count < 5:
80 | print(count)
81 | count = count + 1
82 | else:
83 | print(count)
84 | ```
85 |
86 | 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.
87 |
88 |
89 | ### Break and Continue - Part 1
90 |
91 | - Break: We use break when we like to get out of or stop the loop.
92 |
93 | ```py
94 | # syntax
95 | while condition:
96 | code goes here
97 | if another_condition:
98 | break
99 | ```
100 |
101 | **Example:**
102 |
103 | ```py
104 | count = 0
105 | while count < 5:
106 | print(count)
107 | count = count + 1
108 | if count == 3:
109 | break
110 | ```
111 |
112 | The above while loop only prints 0, 1, 2, but when it reaches 3 it stops.
113 |
114 | - Continue: With the continue statement we can skip the current iteration, and continue with the next:
115 |
116 | ```py
117 | # syntax
118 | while condition:
119 | code goes here
120 | if another_condition:
121 | continue
122 | ```
123 |
124 | **Example:**
125 |
126 | ```py
127 | count = 0
128 | while count < 5:
129 | if count == 3:
130 | continue
131 | print(count)
132 | count = count + 1
133 | ```
134 |
135 | The above while loop only prints 0, 1, 2 and 4 (skips 3).
136 |
137 | ### For Loop
138 |
139 | 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).
140 |
141 | - For loop with list
142 |
143 | ```py
144 | # syntax
145 | for iterator in lst:
146 | code goes here
147 | ```
148 |
149 | **Example:**
150 |
151 | ```py
152 | numbers = [0, 1, 2, 3, 4, 5]
153 | for number in numbers: # number is temporary name to refer to the list's items, valid only inside this loop
154 | print(number) # the numbers will be printed line by line, from 0 to 5
155 | ```
156 |
157 | - For loop with string
158 |
159 | ```py
160 | # syntax
161 | for iterator in string:
162 | code goes here
163 | ```
164 |
165 | **Example:**
166 |
167 | ```py
168 | language = 'Python'
169 | for letter in language:
170 | print(letter)
171 |
172 |
173 | for i in range(len(language)):
174 | print(language[i])
175 | ```
176 |
177 | - For loop with tuple
178 |
179 | ```py
180 | # syntax
181 | for iterator in tpl:
182 | code goes here
183 | ```
184 |
185 | **Example:**
186 |
187 | ```py
188 | numbers = (0, 1, 2, 3, 4, 5)
189 | for number in numbers:
190 | print(number)
191 | ```
192 |
193 | - For loop with dictionary
194 | Looping through a dictionary gives you the key of the dictionary.
195 |
196 | ```py
197 | # syntax
198 | for iterator in dct:
199 | code goes here
200 | ```
201 |
202 | **Example:**
203 |
204 | ```py
205 | person = {
206 | 'first_name':'Asabeneh',
207 | 'last_name':'Yetayeh',
208 | 'age':250,
209 | 'country':'Finland',
210 | 'is_marred':True,
211 | 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
212 | 'address':{
213 | 'street':'Space street',
214 | 'zipcode':'02210'
215 | }
216 | }
217 | for key in person:
218 | print(key)
219 |
220 | for key, value in person.items():
221 | print(key, value) # this way we get both keys and values printed out
222 | ```
223 |
224 | - Loops in set
225 |
226 | ```py
227 | # syntax
228 | for iterator in st:
229 | code goes here
230 | ```
231 |
232 | **Example:**
233 |
234 | ```py
235 | it_companies = {'Facebook', 'Google', 'Microsoft', 'Apple', 'IBM', 'Oracle', 'Amazon'}
236 | for company in it_companies:
237 | print(company)
238 | ```
239 |
240 | ### Break and Continue - Part 2
241 |
242 | Short reminder:
243 | _Break_: We use break when we like to stop our loop before it is completed.
244 |
245 | ```py
246 | # syntax
247 | for iterator in sequence:
248 | code goes here
249 | if condition:
250 | break
251 | ```
252 |
253 | **Example:**
254 |
255 | ```py
256 | numbers = (0,1,2,3,4,5)
257 | for number in numbers:
258 | print(number)
259 | if number == 3:
260 | break
261 | ```
262 |
263 | In the above example, the loop stops when it reaches 3.
264 |
265 | Continue: We use continue when we like to skip some of the steps in the iteration of the loop.
266 |
267 | ```py
268 | # syntax
269 | for iterator in sequence:
270 | code goes here
271 | if condition:
272 | continue
273 | ```
274 |
275 | **Example:**
276 |
277 | ```py
278 | numbers = (0,1,2,3,4,5)
279 | for number in numbers:
280 | print(number)
281 | if number == 3:
282 | continue
283 | print('Next number should be ', number + 1) if number != 5 else print("loop's end") # for short hand conditions need both if and else statements
284 | print('outside the loop')
285 | ```
286 |
287 | 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.
288 |
289 | ### The Range Function
290 |
291 | The _range()_ function is used 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).
292 | Creating sequences using range
293 |
294 | ```py
295 | lst = list(range(11))
296 | print(lst) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
297 | st = set(range(1, 11)) # 2 arguments indicate start and end of the sequence, step set to default 1
298 | print(st) # {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
299 |
300 | lst = list(range(0,11,2))
301 | print(lst) # [0, 2, 4, 6, 8, 10]
302 | st = set(range(0,11,2))
303 | print(st) # {0, 2, 4, 6, 8, 10}
304 | ```
305 |
306 | ```py
307 | # syntax
308 | for iterator in range(start, end, step):
309 | ```
310 |
311 | **Example:**
312 |
313 | ```py
314 | for number in range(11):
315 | print(number) # prints 0 to 10, not including 11
316 | ```
317 |
318 | ### Nested For Loop
319 |
320 | We can write loops inside a loop.
321 |
322 | ```py
323 | # syntax
324 | for x in y:
325 | for t in x:
326 | print(t)
327 | ```
328 |
329 | **Example:**
330 |
331 | ```py
332 | person = {
333 | 'first_name': 'Asabeneh',
334 | 'last_name': 'Yetayeh',
335 | 'age': 250,
336 | 'country': 'Finland',
337 | 'is_marred': True,
338 | 'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
339 | 'address': {
340 | 'street': 'Space street',
341 | 'zipcode': '02210'
342 | }
343 | }
344 | for key in person:
345 | if key == 'skills':
346 | for skill in person['skills']:
347 | print(skill)
348 | ```
349 |
350 | ### For Else
351 |
352 | If we want to execute some message when the loop ends, we use else.
353 |
354 | ```py
355 | # syntax
356 | for iterator in range(start, end, step):
357 | do something
358 | else:
359 | print('The loop ended')
360 | ```
361 |
362 | **Example:**
363 |
364 | ```py
365 | for number in range(11):
366 | print(number) # prints 0 to 10, not including 11
367 | else:
368 | print('The loop stops at', number)
369 | ```
370 |
371 | ### Pass
372 |
373 | In python when statement is required (after semicolon), but we don't like to execute any code there, we can write the word _pass_ to avoid errors. Also we can use it as a placeholder, for future statements.
374 |
375 | **Example:**
376 |
377 | ```py
378 | for number in range(6):
379 | pass
380 | ```
381 |
382 | 🌕 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.
383 |
384 | ## 💻 Exercises: Day 10
385 |
386 | ### Exercises: Level 1
387 |
388 | 1. Iterate 0 to 10 using for loop, do the same using while loop.
389 | 2. Iterate 10 to 0 using for loop, do the same using while loop.
390 | 3. Write a loop that makes seven calls to print(), so we get on the output the following triangle:
391 |
392 | ```py
393 | #
394 | ##
395 | ###
396 | ####
397 | #####
398 | ######
399 | #######
400 | ```
401 |
402 | 4. Use nested loops to create the following:
403 |
404 | ```sh
405 | # # # # # # # #
406 | # # # # # # # #
407 | # # # # # # # #
408 | # # # # # # # #
409 | # # # # # # # #
410 | # # # # # # # #
411 | # # # # # # # #
412 | # # # # # # # #
413 | ```
414 |
415 | 5. Print the following pattern:
416 |
417 | ```sh
418 | 0 x 0 = 0
419 | 1 x 1 = 1
420 | 2 x 2 = 4
421 | 3 x 3 = 9
422 | 4 x 4 = 16
423 | 5 x 5 = 25
424 | 6 x 6 = 36
425 | 7 x 7 = 49
426 | 8 x 8 = 64
427 | 9 x 9 = 81
428 | 10 x 10 = 100
429 | ```
430 |
431 | 6. Iterate through the list, ['Python', 'Numpy','Pandas','Django', 'Flask'] using a for loop and print out the items.
432 | 7. Use for loop to iterate from 0 to 100 and print only even numbers
433 | 8. Use for loop to iterate from 0 to 100 and print only odd numbers
434 |
435 | ### Exercises: Level 2
436 |
437 | 1. Use for loop to iterate from 0 to 100 and print the sum of all numbers.
438 |
439 | ```sh
440 | The sum of all numbers is 5050.
441 | ```
442 |
443 | 1. Use for loop to iterate from 0 to 100 and print the sum of all evens and the sum of all odds.
444 |
445 | ```sh
446 | The sum of all evens is 2550. And the sum of all odds is 2500.
447 | ```
448 |
449 | ### Exercises: Level 3
450 |
451 | 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_.
452 | 1. This is a fruit list, ['banana', 'orange', 'mango', 'lemon'] reverse the order using loop.
453 | 2. 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.
454 | 1. What are the total number of languages in the data
455 | 2. Find the ten most spoken languages from the data
456 | 3. Find the 10 most populated countries in the world
457 |
458 | 🎉 CONGRATULATIONS ! 🎉
459 |
460 | [<< Day 9](../09_Day_Conditionals/09_conditionals.md) | [Day 11 >>](../11_Day_Functions/11_functions.md)
461 |
--------------------------------------------------------------------------------
/12_Day_Modules/12_modules.md:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 | [<< Day 11](../11_Day_Functions/11_functions.md) | [Day 13>>](../13_Day_List_comprehension/13_list_comprehension.md)
19 |
20 | 
21 |
22 | - [📘 Day 12](#-day-12)
23 | - [Modules](#modules)
24 | - [What is a Module](#what-is-a-module)
25 | - [Creating a Module](#creating-a-module)
26 | - [Importing a Module](#importing-a-module)
27 | - [Import Functions from a Module](#import-functions-from-a-module)
28 | - [Import Functions from a Module and Renaming](#import-functions-from-a-module-and-renaming)
29 | - [Import Built-in Modules](#import-built-in-modules)
30 | - [OS Module](#os-module)
31 | - [Sys Module](#sys-module)
32 | - [Statistics Module](#statistics-module)
33 | - [Math Module](#math-module)
34 | - [String Module](#string-module)
35 | - [Random Module](#random-module)
36 | - [💻 Exercises: Day 12](#-exercises-day-12)
37 | - [Exercises: Level 1](#exercises-level-1)
38 | - [Exercises: Level 2](#exercises-level-2)
39 | - [Exercises: Level 3](#exercises-level-3)
40 |
41 | # 📘 Day 12
42 |
43 | ## Modules
44 |
45 | ### What is a Module
46 |
47 | 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.
48 |
49 | ### Creating a Module
50 |
51 | 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.
52 |
53 | ```py
54 | # mymodule.py file
55 | def generate_full_name(firstname, lastname):
56 | return firstname + ' ' + lastname
57 | ```
58 |
59 | Create main.py file in your project directory and import the mymodule.py file.
60 |
61 | ### Importing a Module
62 |
63 | To import the file we use the _import_ keyword and the name of the file only.
64 |
65 | ```py
66 | # main.py file
67 | import mymodule
68 | print(mymodule.generate_full_name('Asabeneh', 'Yetayeh')) # Asabeneh Yetayeh
69 | ```
70 |
71 | ### Import Functions from a Module
72 |
73 | We can have many functions in a file and we can import all the functions differently.
74 |
75 | ```py
76 | # main.py file
77 | from mymodule import generate_full_name, sum_two_nums, person, gravity
78 | print(generate_full_name('Asabneh','Yetayeh'))
79 | print(sum_two_nums(1,9))
80 | mass = 100;
81 | weight = mass * gravity
82 | print(weight)
83 | print(person['firstname'])
84 | ```
85 |
86 | ### Import Functions from a Module and Renaming
87 |
88 | During importing we can rename the name of the module.
89 |
90 | ```py
91 | # main.py file
92 | from mymodule import generate_full_name as fullname, sum_two_nums as total, person as p, gravity as g
93 | print(fullname('Asabneh','Yetayeh'))
94 | print(total(1, 9))
95 | mass = 100;
96 | weight = mass * g
97 | print(weight)
98 | print(p)
99 | print(p['firstname'])
100 | ```
101 |
102 | ## Import Built-in Modules
103 |
104 | Like other programming languages we can also import modules by importing the file/function using the key word _import_. Let's import the common module we will use most of the time. Some of the common built-in modules: _math_, _datetime_, _os_,_sys_, _random_, _statistics_, _collections_, _json_,_re_
105 |
106 | ### OS Module
107 |
108 | Using python _os_ module it is possible to automatically perform many operating system tasks. The OS module in Python provides functions for creating, changing current working directory, and removing a directory (folder), fetching its contents, changing and identifying the current directory.
109 |
110 | ```py
111 | # import the module
112 | import os
113 | # Creating a directory
114 | os.mkdir('directory_name')
115 | # Changing the current directory
116 | os.chdir('path')
117 | # Getting current working directory
118 | os.getcwd()
119 | # Removing directory
120 | os.rmdir()
121 | ```
122 |
123 | ### Sys Module
124 |
125 | The sys module provides functions and variables used to manipulate different parts of the Python runtime environment. Function sys.argv returns a list of command line arguments passed to a Python script. The item at index 0 in this list is always the name of the script, at index 1 is the argument passed from the command line.
126 |
127 | Example of a script.py file:
128 |
129 | ```py
130 | import sys
131 | #print(sys.argv[0], argv[1],sys.argv[2]) # this line would print out: filename argument1 argument2
132 | print('Welcome {}. Enjoy {} challenge!'.format(sys.argv[1], sys.argv[2]))
133 | ```
134 |
135 | Now to check how this script works I wrote in command line:
136 |
137 | ```sh
138 | python script.py Asabeneh 30DaysOfPython
139 | ```
140 |
141 | The result:
142 |
143 | ```sh
144 | Welcome Asabeneh. Enjoy 30DayOfPython challenge!
145 | ```
146 |
147 | Some useful sys commands:
148 |
149 | ```py
150 | # to exit sys
151 | sys.exit()
152 | # To know the largest integer variable it takes
153 | sys.maxsize
154 | # To know environment path
155 | sys.path
156 | # To know the version of python you are using
157 | sys.version
158 | ```
159 |
160 | ### Statistics Module
161 |
162 | The statistics module provides functions for mathematical statistics of numeric data. The popular statistical functions which are defined in this module: _mean_, _median_, _mode_, _stdev_ etc.
163 |
164 | ```py
165 | from statistics import * # importing all the statistics modules
166 | ages = [20, 20, 4, 24, 25, 22, 26, 20, 23, 22, 26]
167 | print(mean(ages)) # ~22.9
168 | print(median(ages)) # 23
169 | print(mode(ages)) # 20
170 | print(stdev(ages)) # ~2.3
171 | ```
172 |
173 | ### Math Module
174 |
175 | Module containing many mathematical operations and constants.
176 |
177 | ```py
178 | import math
179 | print(math.pi) # 3.141592653589793, pi constant
180 | print(math.sqrt(2)) # 1.4142135623730951, square root
181 | print(math.pow(2, 3)) # 8.0, exponential function
182 | print(math.floor(9.81)) # 9, rounding to the lowest
183 | print(math.ceil(9.81)) # 10, rounding to the highest
184 | print(math.log10(100)) # 2, logarithm with 10 as base
185 | ```
186 |
187 | 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:
188 |
189 | ```py
190 | from math import pi
191 | print(pi)
192 | ```
193 |
194 | It is also possible to import multiple functions at once
195 |
196 | ```py
197 |
198 | from math import pi, sqrt, pow, floor, ceil, log10
199 | print(pi) # 3.141592653589793
200 | print(sqrt(2)) # 1.4142135623730951
201 | print(pow(2, 3)) # 8.0
202 | print(floor(9.81)) # 9
203 | print(ceil(9.81)) # 10
204 | print(math.log10(100)) # 2
205 |
206 | ```
207 |
208 | But if we want to import all the function in math module we can use \* .
209 |
210 | ```py
211 | from math import *
212 | print(pi) # 3.141592653589793, pi constant
213 | print(sqrt(2)) # 1.4142135623730951, square root
214 | print(pow(2, 3)) # 8.0, exponential
215 | print(floor(9.81)) # 9, rounding to the lowest
216 | print(ceil(9.81)) # 10, rounding to the highest
217 | print(math.log10(100)) # 2
218 | ```
219 |
220 | When we import we can also rename the name of the function.
221 |
222 | ```py
223 | from math import pi as PI
224 | print(PI) # 3.141592653589793
225 | ```
226 |
227 | ### String Module
228 |
229 | A string module is a useful module for many purposes. The example below shows some use of the string module.
230 |
231 | ```py
232 | import string
233 | print(string.ascii_letters) # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
234 | print(string.digits) # 0123456789
235 | print(string.punctuation) # !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
236 | ```
237 |
238 | ### Random Module
239 |
240 | 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_.
241 |
242 | ```py
243 | from random import random, randint
244 | print(random()) # it doesn't take any arguments; it returns a value between 0 and 0.9999
245 | print(randint(5, 20)) # it returns a random integer number between [5, 20] inclusive
246 | ```
247 |
248 | 🌕 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.
249 |
250 | ## 💻 Exercises: Day 12
251 |
252 | ### Exercises: Level 1
253 |
254 | 1. Writ a function which generates a six digit/character random_user_id.
255 | ```py
256 | print(random_user_id());
257 | '1ee33d'
258 | ```
259 | 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.
260 |
261 | ```py
262 | print(user_id_gen_by_user()) # user input: 5 5
263 | #output:
264 | #kcsy2
265 | #SMFYb
266 | #bWmeq
267 | #ZXOYh
268 | #2Rgxf
269 |
270 | print(user_id_gen_by_user()) # 16 5
271 | #1GCSgPLMaBAVQZ26
272 | #YD7eFwNQKNs7qXaT
273 | #ycArC5yrRupyG00S
274 | #UbGxOFI7UXSWAyKN
275 | #dIV0SSUTgAdKwStr
276 | ```
277 |
278 | 3. Write a function named rgb_color_gen. It will generate rgb colors (3 values ranging from 0 to 255 each).
279 |
280 | ```py
281 | print(rgb_color_gen())
282 | # rgb(125,244,255) - the output should be in this form
283 | ```
284 |
285 | ### Exercises: Level 2
286 |
287 | 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).
288 | 1. Write a function list_of_rgb_colors which returns any number of RGB colors in an array.
289 | 1. Write a function generate_colors which can generate any number of hexa or rgb colors.
290 |
291 | ```py
292 | generate_colors('hexa', 3) # ['#a3e12f','#03ed55','#eb3d2b']
293 | generate_colors('hexa', 1) # ['#b334ef']
294 | generate_colors('rgb', 3) # ['rgb(5, 55, 175','rgb(50, 105, 100','rgb(15, 26, 80']
295 | generate_colors('rgb', 1) # ['rgb(33,79, 176)']
296 | ```
297 |
298 | ### Exercises: Level 3
299 |
300 | 1. Call your function shuffle_list, it takes a list as a parameter and it returns a shuffled list
301 | 1. Write a function which returns an array of seven random numbers in a range of 0-9. All the numbers must be unique.
302 |
303 | 🎉 CONGRATULATIONS ! 🎉
304 |
305 | [<< Day 11](../11_Day_Functions/11_functions.md) | [Day 13>>](../13_Day_List_comprehension/13_list_comprehension.md)
306 |
--------------------------------------------------------------------------------
/12_Day_Modules/main.py:
--------------------------------------------------------------------------------
1 |
2 | from mymodule import generate_full_name as fullname, sum_two_nums as total, person as p, gravity as g
3 | print(fullname('Asabneh','Yetayeh'))
4 | print(total(1, 9))
5 | mass = 100;
6 | weight = mass * g
7 | print(weight)
8 | print(p)
9 | print(p['firstname'])
--------------------------------------------------------------------------------
/12_Day_Modules/mymodule.py:
--------------------------------------------------------------------------------
1 | def generate_full_name(firstname, lastname):
2 | space = ' '
3 | fullname = firstname + space + lastname
4 | return fullname
5 |
6 | def sum_two_nums (num1, num2):
7 | return num1 + num2
8 | gravity = 9.81
9 | person = {
10 | "firstname": "Asabeneh",
11 | "age": 250,
12 | "country": "Finland",
13 | "city":'Helsinki'
14 | }
15 |
16 |
17 |
--------------------------------------------------------------------------------
/13_Day_List_comprehension/13_list_comprehension.md:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 | [<< Day 12](../12_Day_Modules/12_modules.md) | [Day 14>>](../14_Day_Higher_order_functions/14_higher_order_functions.md)
19 |
20 | 
21 |
22 | - [📘 Day 13](#-day-13)
23 | - [List Comprehension](#list-comprehension)
24 | - [Lambda Function](#lambda-function)
25 | - [Creating a Lambda Function](#creating-a-lambda-function)
26 | - [Lambda Function Inside Another Function](#lambda-function-inside-another-function)
27 | - [💻 Exercises: Day 13](#-exercises-day-13)
28 |
29 | # 📘 Day 13
30 |
31 | ## List Comprehension
32 |
33 | List comprehension in Python is a compact way of creating a list from a sequence. It is a short way to create a new list. List comprehension is considerably faster than processing a list using the _for_ loop.
34 |
35 | ```py
36 | # syntax
37 | [i for i in iterable if expression]
38 | ```
39 |
40 | **Example:1**
41 |
42 | For instance if you want to change a string to a list of characters. You can use a couple of methods. Let's see some of them:
43 |
44 | ```py
45 | # One way
46 | language = 'Python'
47 | lst = list(language) # changing the string to list
48 | print(type(lst)) # list
49 | print(lst) # ['P', 'y', 't', 'h', 'o', 'n']
50 |
51 | # Second way: list comprehension
52 | lst = [i for i in language]
53 | print(type(lst)) # list
54 | print(lst) # ['P', 'y', 't', 'h', 'o', 'n']
55 |
56 | ```
57 |
58 | **Example:2**
59 |
60 | For instance if you want to generate a list of numbers
61 |
62 | ```py
63 | # Generating numbers
64 | numbers = [i for i in range(11)] # to generate numbers from 0 to 10
65 | print(numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
66 |
67 | # It is possible to do mathematical operations during iteration
68 | squares = [i * i for i in range(11)]
69 | print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
70 |
71 | # It is also possible to make a list of tuples
72 | numbers = [(i, i * i) for i in range(11)]
73 | print(numbers) # [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
74 |
75 | ```
76 |
77 | **Example:2**
78 |
79 | List comprehension can be combined with if expression
80 |
81 |
82 | ```py
83 | # Generating even numbers
84 | even_numbers = [i for i in range(21) if i % 2 == 0] # to generate even numbers list in range 0 to 21
85 | print(even_numbers) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
86 |
87 | # Generating odd numbers
88 | odd_numbers = [i for i in range(21) if i % 2 != 0] # to generate odd numbers in range 0 to 21
89 | print(odd_numbers) # [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
90 | # Filter numbers: let's filter out positive even numbers from the list below
91 | numbers = [-8, -7, -3, -1, 0, 1, 3, 4, 5, 7, 6, 8, 10]
92 | positive_even_numbers = [i for i in range(21) if i % 2 == 0 and i > 0]
93 | print(positive_even_numbers) # [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
94 |
95 | # Flattening a three dimensional array
96 | list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
97 | flattened_list = [ number for row in list_of_lists for number in row]
98 | print(flattened_list) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
99 | ```
100 |
101 | ## Lambda Function
102 |
103 | Lambda function is a small anonymous function without a name. It can take any number of arguments, but can only have one expression. Lambda function is similar to anonymous functions in JavaScript. We need it when we want to write an anonymous function inside another function.
104 |
105 | ### Creating a Lambda Function
106 |
107 | To create a lambda function we use _lambda_ keyword followed by a parameter(s), followed by an expression. See the syntax and the example below. Lambda function does not use return but it explicitly returns the expression.
108 |
109 | ```py
110 | # syntax
111 | x = lambda param1, param2, param3: param1 + param2 + param2
112 | print(x(arg1, arg2, arg3))
113 | ```
114 |
115 | **Example:**
116 |
117 | ```py
118 | # Named function
119 | def add_two_nums(a, b):
120 | return a + b
121 |
122 | print(add_two_nums(2, 3)) # 5
123 | # Lets change the above function to a lambda function
124 | add_two_nums = lambda a, b: a + b
125 | print(add_two_nums(2,3)) # 5
126 |
127 | # Self invoking lambda function
128 | (lambda a, b: a + b)(2,3) # 5 - need to encapsulate it in print() to see the result in the console
129 |
130 | square = lambda x : x ** 2
131 | print(square(3)) # 9
132 | cube = lambda x : x ** 3
133 | print(cube(3)) # 27
134 |
135 | # Multiple variables
136 | multiple_variable = lambda a, b, c: a ** 2 - 3 * b + 4 * c
137 | print(multiple_variable(5, 5, 3)) # 22
138 | ```
139 |
140 | ### Lambda Function Inside Another Function
141 |
142 | Using a lambda function inside another function.
143 |
144 | ```py
145 | def power(x):
146 | return lambda n : x ** n
147 |
148 | cube = power(2)(3) # function power now need 2 arguments to run, in separate rounded brackets
149 | print(cube) # 8
150 | two_power_of_five = power(2)(5)
151 | print(two_power_of_five) # 32
152 | ```
153 |
154 | 🌕 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.
155 |
156 | ## 💻 Exercises: Day 13
157 |
158 | 1. Filter only negative and zero in the list using list comprehension
159 | ```py
160 | numbers = [-4, -3, -2, -1, 0, 2, 4, 6]
161 | ```
162 | 2. Flatten the following list of lists of lists to a one dimensional list :
163 |
164 | ```py
165 | list_of_lists =[[[1, 2, 3]], [[4, 5, 6]], [[7, 8, 9]]]
166 |
167 | output
168 | [1, 2, 3, 4, 5, 6, 7, 8, 9]
169 | ```
170 |
171 | 3. Using list comprehension create the following list of tuples:
172 | ```py
173 | [(0, 1, 0, 0, 0, 0, 0),
174 | (1, 1, 1, 1, 1, 1, 1),
175 | (2, 1, 2, 4, 8, 16, 32),
176 | (3, 1, 3, 9, 27, 81, 243),
177 | (4, 1, 4, 16, 64, 256, 1024),
178 | (5, 1, 5, 25, 125, 625, 3125),
179 | (6, 1, 6, 36, 216, 1296, 7776),
180 | (7, 1, 7, 49, 343, 2401, 16807),
181 | (8, 1, 8, 64, 512, 4096, 32768),
182 | (9, 1, 9, 81, 729, 6561, 59049),
183 | (10, 1, 10, 100, 1000, 10000, 100000)]
184 | ```
185 | 4. Flatten the following list to a new list:
186 | ```py
187 | countries = [[('Finland', 'Helsinki')], [('Sweden', 'Stockholm')], [('Norway', 'Oslo')]]
188 | output:
189 | [['FINLAND','FIN', 'HELSINKI'], ['SWEDEN', 'SWE', 'STOCKHOLM'], ['NORWAY', 'NOR', 'OSLO']]
190 | ```
191 | 5. Change the following list to a list of dictionaries:
192 | ```py
193 | countries = [[('Finland', 'Helsinki')], [('Sweden', 'Stockholm')], [('Norway', 'Oslo')]]
194 | output:
195 | [{'country': 'FINLAND', 'city': 'HELSINKI'},
196 | {'country': 'SWEDEN', 'city': 'STOCKHOLM'},
197 | {'country': 'NORWAY', 'city': 'OSLO'}]
198 | ```
199 | 6. Change the following list of lists to a list of concatenated strings:
200 | ```py
201 | names = [[('Asabeneh', 'Yetayeh')], [('David', 'Smith')], [('Donald', 'Trump')], [('Bill', 'Gates')]]
202 | output
203 | ['Asabeneh Yetaeyeh', 'David Smith', 'Donald Trump', 'Bill Gates']
204 | ```
205 | 7. Write a lambda function which can solve a slope or y-intercept of linear functions.
206 |
207 | 🎉 CONGRATULATIONS ! 🎉
208 |
209 | [<< Day 12](../12_Day_Modules/12_modules.md) | [Day 14>>](../14_Day_Higher_order_functions/14_higher_order_functions.md)
210 |
--------------------------------------------------------------------------------
/14_Day_Higher_order_functions/14_higher_order_functions.md:
--------------------------------------------------------------------------------
1 |
2 |
30 Days Of Python: Day 14 - Higher Order Functions
15 |
16 |
17 | [<< Day 13](../13_Day_List_comprehension/13_list_comprehension.md) | [Day 15>>](../15_Day_Python_type_errors/15_python_type_errors.md)
18 |
19 | 
20 | - [📘 Day 14](#-day-14)
21 | - [Higher Order Functions](#higher-order-functions)
22 | - [Function as a Parameter](#function-as-a-parameter)
23 | - [Function as a Return Value](#function-as-a-return-value)
24 | - [Python Closures](#python-closures)
25 | - [Python Decorators](#python-decorators)
26 | - [Creating Decorators](#creating-decorators)
27 | - [Applying Multiple Decorators to a Single Function](#applying-multiple-decorators-to-a-single-function)
28 | - [Accepting Parameters in Decorator Functions](#accepting-parameters-in-decorator-functions)
29 | - [Built-in Higher Order Functions](#built-in-higher-order-functions)
30 | - [Python - Map Function](#python---map-function)
31 | - [Python - Filter Function](#python---filter-function)
32 | - [Python - Reduce Function](#python---reduce-function)
33 | - [💻 Exercises: Day 14](#-exercises-day-14)
34 | - [Exercises: Level 1](#exercises-level-1)
35 | - [Exercises: Level 2](#exercises-level-2)
36 | - [Exercises: Level 3](#exercises-level-3)
37 |
38 | # 📘 Day 14
39 |
40 | ## Higher Order Functions
41 |
42 | In Python functions are treated as first class citizens, allowing you to perform the following operations on functions:
43 |
44 | - A function can take one or more functions as parameters
45 | - A function can be returned as a result of another function
46 | - A function can be modified
47 | - A function can be assigned to a variable
48 |
49 | In this section, we will cover:
50 |
51 | 1. Handling functions as parameters
52 | 2. Returning functions as return value from another functions
53 | 3. Using Python closures and decorators
54 |
55 | ### Function as a Parameter
56 |
57 | ```py
58 | def sum_numbers(nums): # normal function
59 | return sum(nums) # a sad function abusing the built-in sum function :<
60 |
61 | def higher_order_function(f, lst): # function as a parameter
62 | summation = f(lst)
63 | return summation
64 | result = higher_order_function(sum_numbers, [1, 2, 3, 4, 5])
65 | print(result) # 15
66 | ```
67 |
68 | ### Function as a Return Value
69 |
70 | ```py
71 | def square(x): # a square function
72 | return x ** 2
73 |
74 | def cube(x): # a cube function
75 | return x ** 3
76 |
77 | def absolute(x): # an absolute value function
78 | if x >= 0:
79 | return x
80 | else:
81 | return -(x)
82 |
83 | def higher_order_function(type): # a higher order function returning a function
84 | if type == 'square':
85 | return square
86 | elif type == 'cube':
87 | return cube
88 | elif type == 'absolute':
89 | return absolute
90 |
91 | result = higher_order_function('square')
92 | print(result(3)) # 9
93 | result = higher_order_function('cube')
94 | print(result(3)) # 27
95 | result = higher_order_function('absolute')
96 | print(result(-3)) # 3
97 | ```
98 |
99 | You can see from the above example that the higher order function is returning different functions depending on the passed parameter
100 |
101 | ## Python Closures
102 |
103 | 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.
104 |
105 | **Example:**
106 |
107 | ```py
108 | def add_ten():
109 | ten = 10
110 | def add(num):
111 | return num + ten
112 | return add
113 |
114 | closure_result = add_ten()
115 | print(closure_result(5)) # 15
116 | print(closure_result(10)) # 20
117 | ```
118 |
119 | ## Python Decorators
120 |
121 | A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.
122 |
123 | ### Creating Decorators
124 |
125 | To create a decorator function, we need an outer function with an inner wrapper function.
126 |
127 | **Example:**
128 |
129 | ```py
130 | # Normal function
131 | def greeting():
132 | return 'Welcome to Python'
133 | def uppercase_decorator(function):
134 | def wrapper():
135 | func = function()
136 | make_uppercase = func.upper()
137 | return make_uppercase
138 | return wrapper
139 | g = uppercase_decorator(greeting)
140 | print(g()) # WELCOME TO PYTHON
141 |
142 | ## Let us implement the example above with a decorator
143 |
144 | '''This decorator function is a higher order function
145 | that takes a function as a parameter'''
146 | def uppercase_decorator(function):
147 | def wrapper():
148 | func = function()
149 | make_uppercase = func.upper()
150 | return make_uppercase
151 | return wrapper
152 | @uppercase_decorator
153 | def greeting():
154 | return 'Welcome to Python'
155 | print(greeting()) # WELCOME TO PYTHON
156 |
157 | ```
158 |
159 | ### Applying Multiple Decorators to a Single Function
160 |
161 | ```py
162 |
163 | '''These decorator functions are higher order functions
164 | that take functions as parameters'''
165 |
166 | # First Decorator
167 | def uppercase_decorator(function):
168 | def wrapper():
169 | func = function()
170 | make_uppercase = func.upper()
171 | return make_uppercase
172 | return wrapper
173 |
174 | # Second decorator
175 | def split_string_decorator(function):
176 | def wrapper():
177 | func = function()
178 | splitted_string = func.split()
179 | return splitted_string
180 |
181 | return wrapper
182 |
183 | @split_string_decorator
184 | @uppercase_decorator # order with decorators is important in this case - .upper() function does not work with lists
185 | def greeting():
186 | return 'Welcome to Python'
187 | print(greeting()) # WELCOME TO PYTHON
188 | ```
189 |
190 | ### Accepting Parameters in Decorator Functions
191 |
192 | Most of the time we need our functions to take parameters, so we might need to define a decorator that accepts parameters.
193 |
194 | ```py
195 | def decorator_with_parameters(function):
196 | def wrapper_accepting_parameters(para1, para2, para3):
197 | function(para1, para2, para3)
198 | print("I live in {}".format(para3))
199 | return wrapper_accepting_parameters
200 |
201 | @decorator_with_parameters
202 | def print_full_name(first_name, last_name, country):
203 | print("I am {} {}. I love to teach.".format(
204 | first_name, last_name, country))
205 |
206 | print_full_name("Asabeneh", "Yetayeh",'Finland')
207 | ```
208 |
209 | ## Built-in Higher Order Functions
210 |
211 | Some of the built-in higher order functions that we cover in this part are _map()_, _filter_, and _reduce_.
212 | Lambda function can be passed as a parameter and the best use case of lambda functions is in functions like map, filter and reduce.
213 |
214 | ### Python - Map Function
215 |
216 | The map() function is a built-in function that takes a function and iterable as parameters.
217 |
218 | ```py
219 | # syntax
220 | map(function, iterable)
221 | ```
222 |
223 | **Example:1**
224 |
225 | ```py
226 | numbers = [1, 2, 3, 4, 5] # iterable
227 | def square(x):
228 | return x ** 2
229 | numbers_squared = map(square, numbers)
230 | print(list(numbers_squared)) # [1, 4, 9, 16, 25]
231 | # Lets apply it with a lambda function
232 | numbers_squared = map(lambda x : x ** 2, numbers)
233 | print(list(numbers_squared)) # [1, 4, 9, 16, 25]
234 | ```
235 |
236 | **Example:2**
237 |
238 | ```py
239 | numbers_str = ['1', '2', '3', '4', '5'] # iterable
240 | numbers_int = map(int, numbers_str)
241 | print(list(numbers_int)) # [1, 2, 3, 4, 5]
242 | ```
243 |
244 | **Example:3**
245 |
246 | ```py
247 | names = ['Asabeneh', 'Lidiya', 'Ermias', 'Abraham'] # iterable
248 |
249 | def change_to_upper(name):
250 | return name.upper()
251 |
252 | names_upper_cased = map(change_to_upper, names)
253 | print(list(names_upper_cased)) # ['ASABENEH', 'LIDIYA', 'ERMIAS', 'ABRAHAM']
254 |
255 | # Let us apply it with a lambda function
256 | names_upper_cased = map(lambda name: name.upper(), names)
257 | print(list(names_upper_cased)) # ['ASABENEH', 'LIDIYA', 'ERMIAS', 'ABRAHAM']
258 | ```
259 |
260 | What actually map does is iterating over a list. For instance, it changes the names to upper case and returns a new list.
261 |
262 | ### Python - Filter Function
263 |
264 | The filter() function calls the specified function which returns boolean for each item of the specified iterable (list). It filters the items that satisfy the filtering criteria.
265 |
266 | ```py
267 | # syntax
268 | filter(function, iterable)
269 | ```
270 |
271 | **Example:1**
272 |
273 | ```py
274 | # Lets filter only even nubers
275 | numbers = [1, 2, 3, 4, 5] # iterable
276 |
277 | def is_even(num):
278 | if num % 2 == 0:
279 | return True
280 | return False
281 |
282 | even_numbers = filter(is_even, numbers)
283 | print(list(even_numbers)) # [2, 4]
284 | ```
285 |
286 | **Example:2**
287 |
288 | ```py
289 | numbers = [1, 2, 3, 4, 5] # iterable
290 |
291 | def is_odd(num):
292 | if num % 2 != 0:
293 | return True
294 | return False
295 |
296 | odd_numbers = filter(is_odd, numbers)
297 | print(list(odd_numbers)) # [1, 3, 5]
298 | ```
299 |
300 | ```py
301 | # Filter long name
302 | names = ['Asabeneh', 'Lidiya', 'Ermias', 'Abraham'] # iterable
303 | def is_name_long(name):
304 | if len(name) > 7:
305 | return True
306 | return False
307 |
308 | long_names = filter(is_name_long, names)
309 | print(list(long_names)) # ['Asabeneh']
310 | ```
311 |
312 | ### Python - Reduce Function
313 |
314 | 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.
315 | **Example:1**
316 |
317 | ```py
318 | numbers_str = ['1', '2', '3', '4', '5'] # iterable
319 | def add_two_nums(x, y):
320 | return int(x) + int(y)
321 |
322 | total = reduce(add_two_nums, numbers_str)
323 | print(total) # 15
324 | ```
325 |
326 | ## 💻 Exercises: Day 14
327 |
328 | ```py
329 | countries = ['Estonia', 'Finland', 'Sweden', 'Denmark', 'Norway', 'Iceland']
330 | names = ['Asabeneh', 'Lidiya', 'Ermias', 'Abraham']
331 | numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
332 | ```
333 |
334 | ### Exercises: Level 1
335 |
336 | 1. Explain the difference between map, filter, and reduce.
337 | 2. Explain the difference between higher order function, closure and decorator
338 | 3. Define a call function before map, filter or reduce, see examples.
339 | 4. Use for loop to print each country in the countries list.
340 | 5. Use for to print each name in the names list.
341 | 6. Use for to print each number in the numbers list.
342 |
343 | ### Exercises: Level 2
344 |
345 | 1. Use map to create a new list by changing each country to uppercase in the countries list
346 | 1. Use map to create a new list by changing each number to its square in the numbers list
347 | 1. Use map to change each name to uppercase in the names list
348 | 1. Use filter to filter out countries containing 'land'.
349 | 1. Use filter to filter out countries having exactly six characters.
350 | 1. Use filter to filter out countries containing six letters and more in the country list.
351 | 1. Use filter to filter out countries starting with an 'E'
352 | 1. Chain two or more list iterators (eg. arr.map(callback).filter(callback).reduce(callback))
353 | 1. Declare a function called get_string_lists which takes a list as a parameter and then returns a list containing only string items.
354 | 1. Use reduce to sum all the numbers in the numbers list.
355 | 1. Use reduce to concatenate all the countries and to produce this sentence: Estonia, Finland, Sweden, Denmark, Norway, and Iceland are north European countries
356 | 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')).
357 | 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.
358 | 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.
359 | 1. Declare a get_last_ten_countries function that returns the last ten countries in the countries list.
360 |
361 | ### Exercises: Level 3
362 |
363 | 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:
364 | - Sort countries by name, by capital, by population
365 | - Sort out the ten most spoken languages by location.
366 | - Sort out the ten most populated countries.
367 |
368 | 🎉 CONGRATULATIONS ! 🎉
369 |
370 | [<< Day 13](../13_Day_List_comprehension/13_list_comprehension.md) | [Day 15>>](../15_Day_Python_type_errors/15_python_type_errors.md)
--------------------------------------------------------------------------------
/15_Day_Python_type_errors/15_python_type_errors.md:
--------------------------------------------------------------------------------
1 |
15 |
16 |
17 | [<< Day 14](../14_Day_Higher_order_functions/14_higher_order_functions.md) | [Day 16 >>](../16_Day_Python_date_time/16_python_datetime.md)
18 |
19 | 
20 | - [📘 Day 15](#-day-15)
21 | - [Python Error Types](#python-error-types)
22 | - [SyntaxError](#syntaxerror)
23 | - [NameError](#nameerror)
24 | - [IndexError](#indexerror)
25 | - [ModuleNotFoundError](#modulenotfounderror)
26 | - [AttributeError](#attributeerror)
27 | - [KeyError](#keyerror)
28 | - [TypeError](#typeerror)
29 | - [ImportError](#importerror)
30 | - [ValueError](#valueerror)
31 | - [ZeroDivisionError](#zerodivisionerror)
32 | - [💻 Exercises: Day 15](#-exercises-day-15)
33 |
34 | # 📘 Day 15
35 |
36 | ## Python Error Types
37 |
38 | 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.
39 |
40 | 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.
41 |
42 | ### SyntaxError
43 |
44 | **Example 1: SyntaxError**
45 |
46 | ```py
47 | asabeneh@Asabeneh:~$ python
48 | Python 3.9.6 (default, Jun 28 2021, 15:26:21)
49 | [Clang 11.0.0 (clang-1100.0.33.8)] on darwin
50 | Type "help", "copyright", "credits" or "license" for more information.
51 | >>> print 'hello world'
52 | File "", line 1
53 | print 'hello world'
54 | ^
55 | SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello world')?
56 | >>>
57 | ```
58 |
59 | 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.
60 |
61 | ```py
62 | asabeneh@Asabeneh:~$ python
63 | Python 3.9.6 (default, Jun 28 2021, 15:26:21)
64 | [Clang 11.0.0 (clang-1100.0.33.8)] on darwin
65 | Type "help", "copyright", "credits" or "license" for more information.
66 | >>> print 'hello world'
67 | File "", line 1
68 | print 'hello world'
69 | ^
70 | SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello world')?
71 | >>> print('hello world')
72 | hello world
73 | >>>
74 | ```
75 |
76 | The error was a _SyntaxError_. After the fix our code was executed without a hitch. Let see more error types.
77 |
78 | ### NameError
79 |
80 | **Example 1: NameError**
81 |
82 | ```py
83 | asabeneh@Asabeneh:~$ python
84 | Python 3.9.6 (default, Jun 28 2021, 15:26:21)
85 | [Clang 11.0.0 (clang-1100.0.33.8)] on darwin
86 | Type "help", "copyright", "credits" or "license" for more information.
87 | >>> print(age)
88 | Traceback (most recent call last):
89 | File "", line 1, in
90 | NameError: name 'age' is not defined
91 | >>>
92 | ```
93 |
94 | 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.
95 |
96 | ```py
97 | asabeneh@Asabeneh:~$ python
98 | Python 3.9.6 (default, Jun 28 2021, 15:26:21)
99 | [Clang 11.0.0 (clang-1100.0.33.8)] on darwin
100 | Type "help", "copyright", "credits" or "license" for more information.
101 | >>> print(age)
102 | Traceback (most recent call last):
103 | File "", line 1, in
104 | NameError: name 'age' is not defined
105 | >>> age = 25
106 | >>> print(age)
107 | 25
108 | >>>
109 | ```
110 |
111 | The type of error was a _NameError_. We debugged the error by defining the variable name.
112 |
113 | ### IndexError
114 |
115 | **Example 1: IndexError**
116 |
117 | ```py
118 | asabeneh@Asabeneh:~$ python
119 | Python 3.9.6 (default, Jun 28 2021, 15:26:21)
120 | [Clang 11.0.0 (clang-1100.0.33.8)] on darwin
121 | Type "help", "copyright", "credits" or "license" for more information.
122 | >>> numbers = [1, 2, 3, 4, 5]
123 | >>> numbers[5]
124 | Traceback (most recent call last):
125 | File "", line 1, in
126 | IndexError: list index out of range
127 | >>>
128 | ```
129 |
130 | In the example above, Python raised an _IndexError_, because the list has only indexes from 0 to 4 , so it was out of range.
131 |
132 | ### ModuleNotFoundError
133 |
134 | **Example 1: ModuleNotFoundError**
135 |
136 | ```py
137 | asabeneh@Asabeneh:~$ python
138 | Python 3.9.6 (default, Jun 28 2021, 15:26:21)
139 | [Clang 11.0.0 (clang-1100.0.33.8)] on darwin
140 | Type "help", "copyright", "credits" or "license" for more information.
141 | >>> import maths
142 | Traceback (most recent call last):
143 | File "", line 1, in
144 | ModuleNotFoundError: No module named 'maths'
145 | >>>
146 | ```
147 |
148 | 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.
149 |
150 | ```py
151 | asabeneh@Asabeneh:~$ python
152 | Python 3.9.6 (default, Jun 28 2021, 15:26:21)
153 | [Clang 11.0.0 (clang-1100.0.33.8)] on darwin
154 | Type "help", "copyright", "credits" or "license" for more information.
155 | >>> import maths
156 | Traceback (most recent call last):
157 | File "", line 1, in
158 | ModuleNotFoundError: No module named 'maths'
159 | >>> import math
160 | >>>
161 | ```
162 |
163 | We fixed it, so let's use some of the functions from the math module.
164 |
165 | ### AttributeError
166 |
167 | **Example 1: AttributeError**
168 |
169 | ```py
170 | asabeneh@Asabeneh:~$ python
171 | Python 3.9.6 (default, Jun 28 2021, 15:26:21)
172 | [Clang 11.0.0 (clang-1100.0.33.8)] on darwin
173 | Type "help", "copyright", "credits" or "license" for more information.
174 | >>> import maths
175 | Traceback (most recent call last):
176 | File "", line 1, in
177 | ModuleNotFoundError: No module named 'maths'
178 | >>> import math
179 | >>> math.PI
180 | Traceback (most recent call last):
181 | File "", line 1, in
182 | AttributeError: module 'math' has no attribute 'PI'
183 | >>>
184 | ```
185 |
186 | 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.
187 |
188 | ```py
189 | asabeneh@Asabeneh:~$ python
190 | Python 3.9.6 (default, Jun 28 2021, 15:26:21)
191 | [Clang 11.0.0 (clang-1100.0.33.8)] on darwin
192 | Type "help", "copyright", "credits" or "license" for more information.
193 | >>> import maths
194 | Traceback (most recent call last):
195 | File "", line 1, in
196 | ModuleNotFoundError: No module named 'maths'
197 | >>> import math
198 | >>> math.PI
199 | Traceback (most recent call last):
200 | File "", line 1, in
201 | AttributeError: module 'math' has no attribute 'PI'
202 | >>> math.pi
203 | 3.141592653589793
204 | >>>
205 | ```
206 |
207 | Now, when we call pi from the math module we got the result.
208 |
209 | ### KeyError
210 |
211 | **Example 1: KeyError**
212 |
213 | ```py
214 | asabeneh@Asabeneh:~$ python
215 | Python 3.9.6 (default, Jun 28 2021, 15:26:21)
216 | [Clang 11.0.0 (clang-1100.0.33.8)] on darwin
217 | Type "help", "copyright", "credits" or "license" for more information.
218 | >>> users = {'name':'Asab', 'age':250, 'country':'Finland'}
219 | >>> users['name']
220 | 'Asab'
221 | >>> users['county']
222 | Traceback (most recent call last):
223 | File "", line 1, in
224 | KeyError: 'county'
225 | >>>
226 | ```
227 |
228 | 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!
229 |
230 | ```py
231 | asabeneh@Asabeneh:~$ python
232 | Python 3.9.6 (default, Jun 28 2021, 15:26:21)
233 | [Clang 11.0.0 (clang-1100.0.33.8)] on darwin
234 | Type "help", "copyright", "credits" or "license" for more information.
235 | >>> user = {'name':'Asab', 'age':250, 'country':'Finland'}
236 | >>> user['name']
237 | 'Asab'
238 | >>> user['county']
239 | Traceback (most recent call last):
240 | File "", line 1, in
241 | KeyError: 'county'
242 | >>> user['country']
243 | 'Finland'
244 | >>>
245 | ```
246 |
247 | We debugged the error, our code ran and we got the value.
248 |
249 | ### TypeError
250 |
251 | **Example 1: TypeError**
252 |
253 | ```py
254 | asabeneh@Asabeneh:~$ python
255 | Python 3.9.6 (default, Jun 28 2021, 15:26:21)
256 | [Clang 11.0.0 (clang-1100.0.33.8)] on darwin
257 | Type "help", "copyright", "credits" or "license" for more information.
258 | >>> 4 + '3'
259 | Traceback (most recent call last):
260 | File "", line 1, in
261 | TypeError: unsupported operand type(s) for +: 'int' and 'str'
262 | >>>
263 | ```
264 |
265 | 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.
266 |
267 | ```py
268 | asabeneh@Asabeneh:~$ python
269 | Python 3.9.6 (default, Jun 28 2021, 15:26:21)
270 | [Clang 11.0.0 (clang-1100.0.33.8)] on darwin
271 | Type "help", "copyright", "credits" or "license" for more information.
272 | >>> 4 + '3'
273 | Traceback (most recent call last):
274 | File "", line 1, in
275 | TypeError: unsupported operand type(s) for +: 'int' and 'str'
276 | >>> 4 + int('3')
277 | 7
278 | >>> 4 + float('3')
279 | 7.0
280 | >>>
281 | ```
282 |
283 | Error removed and we got the result we expected.
284 |
285 | ### ImportError
286 |
287 | **Example 1: TypeError**
288 |
289 | ```py
290 | asabeneh@Asabeneh:~$ python
291 | Python 3.9.6 (default, Jun 28 2021, 15:26:21)
292 | [Clang 11.0.0 (clang-1100.0.33.8)] on darwin
293 | Type "help", "copyright", "credits" or "license" for more information.
294 | >>> from math import power
295 | Traceback (most recent call last):
296 | File "", line 1, in
297 | ImportError: cannot import name 'power' from 'math'
298 | >>>
299 | ```
300 |
301 | There is no function called power in the math module, it goes with a different name: _pow_. Let's correct it:
302 |
303 | ```py
304 | asabeneh@Asabeneh:~$ python
305 | Python 3.9.6 (default, Jun 28 2021, 15:26:21)
306 | [Clang 11.0.0 (clang-1100.0.33.8)] on darwin
307 | Type "help", "copyright", "credits" or "license" for more information.
308 | >>> from math import power
309 | Traceback (most recent call last):
310 | File "", line 1, in
311 | ImportError: cannot import name 'power' from 'math'
312 | >>> from math import pow
313 | >>> pow(2,3)
314 | 8.0
315 | >>>
316 | ```
317 |
318 | ### ValueError
319 |
320 | ```py
321 | asabeneh@Asabeneh:~$ python
322 | Python 3.9.6 (default, Jun 28 2021, 15:26:21)
323 | [Clang 11.0.0 (clang-1100.0.33.8)] on darwin
324 | Type "help", "copyright", "credits" or "license" for more information.
325 | >>> int('12a')
326 | Traceback (most recent call last):
327 | File "", line 1, in
328 | ValueError: invalid literal for int() with base 10: '12a'
329 | >>>
330 | ```
331 |
332 | In this case we cannot change the given string to a number, because of the 'a' letter in it.
333 |
334 | ### ZeroDivisionError
335 |
336 | ```py
337 | asabeneh@Asabeneh:~$ python
338 | Python 3.9.6 (default, Jun 28 2021, 15:26:21)
339 | [Clang 11.0.0 (clang-1100.0.33.8)] on darwin
340 | Type "help", "copyright", "credits" or "license" for more information.
341 | >>> 1/0
342 | Traceback (most recent call last):
343 | File "", line 1, in
344 | ZeroDivisionError: division by zero
345 | >>>
346 | ```
347 |
348 | We cannot divide a number by zero.
349 |
350 | 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.
351 | 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.
352 |
353 | 🌕 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.
354 |
355 | ## 💻 Exercises: Day 15
356 |
357 | 1. Open you python interactive shell and try all the examples covered in this section.
358 |
359 | 🎉 CONGRATULATIONS ! 🎉
360 |
361 | [<< Day 14](../14_Day_Higher_order_functions/14_higher_order_functions.md) | [Day 16 >>](../16_Day_Python_date_time/16_python_datetime.md)
--------------------------------------------------------------------------------
/16_Day_Python_date_time/16_python_datetime.md:
--------------------------------------------------------------------------------
1 |
15 |
16 | [<< Day 16](../16_Day_Python_date_time/16_python_datetime.md) | [Day 18 >>](../18_Day_Regular_expressions/18_regular_expressions.md)
17 |
18 | 
19 | - [📘 Day 17](#-day-17)
20 | - [Exception Handling](#exception-handling)
21 | - [Packing and Unpacking Arguments in Python](#packing-and-unpacking-arguments-in-python)
22 | - [Unpacking](#unpacking)
23 | - [Unpacking Lists](#unpacking-lists)
24 | - [Unpacking Dictionaries](#unpacking-dictionaries)
25 | - [Packing](#packing)
26 | - [Packing Lists](#packing-lists)
27 | - [Packing Dictionaries](#packing-dictionaries)
28 | - [Spreading in Python](#spreading-in-python)
29 | - [Enumerate](#enumerate)
30 | - [Zip](#zip)
31 | - [Exercises: Day 17](#exercises-day-17)
32 |
33 | # 📘 Day 17
34 |
35 | ## Exception Handling
36 |
37 | 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.
38 |
39 | 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.
40 |
41 | 
42 |
43 | ```py
44 | try:
45 | code in this block if things go well
46 | except:
47 | code in this block run if things go wrong
48 | ```
49 |
50 | **Example:**
51 |
52 | ```py
53 | try:
54 | print(10 + '5')
55 | except:
56 | print('Something went wrong')
57 | ```
58 |
59 | In the example above the second operand is a string. We could change it to float or int to add it with the number to make it work. But without any changes, the second block, _except_, will be executed.
60 |
61 | **Example:**
62 |
63 | ```py
64 | try:
65 | name = input('Enter your name:')
66 | year_born = input('Year you were born:')
67 | age = 2019 - year_born
68 | print(f'You are {name}. And your age is {age}.')
69 | except:
70 | print('Something went wrong')
71 | ```
72 |
73 | ```sh
74 | Something went wrong
75 | ```
76 |
77 | 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.
78 |
79 | In the following example, it will handle the error and will also tell us the kind of error raised.
80 |
81 | ```py
82 | try:
83 | name = input('Enter your name:')
84 | year_born = input('Year you were born:')
85 | age = 2019 - year_born
86 | print(f'You are {name}. And your age is {age}.')
87 | except TypeError:
88 | print('Type error occured')
89 | except ValueError:
90 | print('Value error occured')
91 | except ZeroDivisionError:
92 | print('zero division error occured')
93 | ```
94 |
95 | ```sh
96 | Enter your name:Asabeneh
97 | Year you born:1920
98 | Type error occured
99 | ```
100 |
101 | In the code above the output is going to be _TypeError_.
102 | Now, let's add an additional block:
103 |
104 | ```py
105 | try:
106 | name = input('Enter your name:')
107 | year_born = input('Year you born:')
108 | age = 2019 - int(year_born)
109 | print('You are {name}. And your age is {age}.')
110 | except TypeError:
111 | print('Type error occur')
112 | except ValueError:
113 | print('Value error occur')
114 | except ZeroDivisionError:
115 | print('zero division error occur')
116 | else:
117 | print('I usually run with the try block')
118 | finally:
119 | print('I alway run.')
120 | ```
121 |
122 | ```sh
123 | Enter your name:Asabeneh
124 | Year you born:1920
125 | You are Asabeneh. And your age is 99.
126 | I usually run with the try block
127 | I alway run.
128 | ```
129 |
130 | It is also shorten the above code as follows:
131 | ```py
132 | try:
133 | name = input('Enter your name:')
134 | year_born = input('Year you born:')
135 | age = 2019 - int(year_born)
136 | print('You are {name}. And your age is {age}.')
137 | except Exception as e:
138 | print(e)
139 |
140 | ```
141 |
142 | ## Packing and Unpacking Arguments in Python
143 |
144 | We use two operators:
145 |
146 | - \* for tuples
147 | - \*\* for dictionaries
148 |
149 | Let us take as an example below. It takes only arguments but we have list. We can unpack the list and changes to argument.
150 |
151 | ### Unpacking
152 |
153 | #### Unpacking Lists
154 |
155 | ```py
156 | def sum_of_five_nums(a, b, c, d, e):
157 | return a + b + c + d + e
158 |
159 | lst = [1, 2, 3, 4, 5]
160 | print(sum_of_five_nums(lst)) # TypeError: sum_of_five_nums() missing 4 required positional arguments: 'b', 'c', 'd', and 'e'
161 | ```
162 |
163 | 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.
164 |
165 | ```py
166 | def sum_of_five_nums(a, b, c, d, e):
167 | return a + b + c + d + e
168 |
169 | lst = [1, 2, 3, 4, 5]
170 | print(sum_of_five_nums(*lst)) # 15
171 | ```
172 |
173 | We can also use unpacking in the range built-in function that expects a start and an end.
174 |
175 | ```py
176 | numbers = range(2, 7) # normal call with separate arguments
177 | print(list(numbers)) # [2, 3, 4, 5, 6]
178 | args = [2, 7]
179 | numbers = range(*args) # call with arguments unpacked from a list
180 | print(numbers) # [2, 3, 4, 5,6]
181 |
182 | ```
183 |
184 | A list or a tuple can also be unpacked like this:
185 |
186 | ```py
187 | countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
188 | fin, sw, nor, *rest = countries
189 | print(fin, sw, nor, rest) # Finland Sweden Norway ['Denmark', 'Iceland']
190 | numbers = [1, 2, 3, 4, 5, 6, 7]
191 | one, *middle, last = numbers
192 | print(one, middle, last) # 1 [2, 3, 4, 5, 6] 7
193 | ```
194 |
195 | #### Unpacking Dictionaries
196 |
197 | ```py
198 | def unpacking_person_info(name, country, city, age):
199 | return f'{name} lives in {country}, {city}. He is {age} year old.'
200 | dct = {'name':'Asabeneh', 'country':'Finland', 'city':'Helsinki', 'age':250}
201 | print(unpacking_person_info(**dct)) # Asabeneh lives in Finland, Helsinki. He is 250 years old.
202 | ```
203 |
204 | ### Packing
205 |
206 | Sometimes we never know how many arguments need to be passed to a python function. We can use the packing method to allow our function to take unlimited number or arbitrary number of arguments.
207 |
208 | ### Packing Lists
209 |
210 | ```py
211 | def sum_all(*args):
212 | s = 0
213 | for i in args:
214 | s += i
215 | return s
216 | print(sum_all(1, 2, 3)) # 6
217 | print(sum_all(1, 2, 3, 4, 5, 6, 7)) # 28
218 | ```
219 |
220 | #### Packing Dictionaries
221 |
222 | ```py
223 | def packing_person_info(**kwargs):
224 | # check the type of kwargs and it is a dict type
225 | # print(type(kwargs))
226 | # Printing dictionary items
227 | for key in kwargs:
228 | print("{key} = {kwargs[key]}")
229 | return kwargs
230 |
231 | print(packing_person_info(name="Asabeneh",
232 | country="Finland", city="Helsinki", age=250))
233 | ```
234 |
235 | ```sh
236 | name = Asabeneh
237 | country = Finland
238 | city = Helsinki
239 | age = 250
240 | {'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250}
241 | ```
242 |
243 | ## Spreading in Python
244 |
245 | Like in JavaScript, spreading is possible in Python. Let us check it in an example below:
246 |
247 | ```py
248 | lst_one = [1, 2, 3]
249 | lst_two = [4, 5, 6, 7]
250 | lst = [0, *list_one, *list_two]
251 | print(lst) # [0, 1, 2, 3, 4, 5, 6, 7]
252 | country_lst_one = ['Finland', 'Sweden', 'Norway']
253 | country_lst_two = ['Denmark', 'Iceland']
254 | nordic_countries = [*country_lst_one, *country_lst_two]
255 | print(nordic_countries) # ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
256 | ```
257 |
258 | ## Enumerate
259 |
260 | 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.
261 |
262 | ```py
263 | for index, item in enumerate([20, 30, 40]):
264 | print(index, item)
265 | ```
266 |
267 | ```py
268 | for index, i in enumerate(countries):
269 | print('hi')
270 | if i == 'Finland':
271 | print('The country {i} has been found at index {index}')
272 | ```
273 |
274 | ```sh
275 | The country Finland has been found at index 1.
276 | ```
277 |
278 | ## Zip
279 |
280 | Sometimes we would like to combine lists when looping through them. See the example below:
281 |
282 | ```py
283 | fruits = ['banana', 'orange', 'mango', 'lemon', 'lime']
284 | vegetables = ['Tomato', 'Potato', 'Cabbage','Onion', 'Carrot']
285 | fruits_and_veges = []
286 | for f, v in zip(fruits, vegetables):
287 | fruits_and_veges.append({'fruit':f, 'veg':v})
288 |
289 | print(fruits_and_veges)
290 | ```
291 |
292 | ```sh
293 | [{'fruit': 'banana', 'veg': 'Tomato'}, {'fruit': 'orange', 'veg': 'Potato'}, {'fruit': 'mango', 'veg': 'Cabbage'}, {'fruit': 'lemon', 'veg': 'Onion'}, {'fruit': 'lime', 'veg': 'Carrot'}]
294 | ```
295 |
296 | 🌕 You are determined. You are 17 steps a head to your way to greatness. Now do some exercises for your brain and muscles.
297 |
298 | ## Exercises: Day 17
299 |
300 | 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.
301 |
302 | 🎉 CONGRATULATIONS ! 🎉
303 |
304 | [<< Day 16](../16_Day_Python_date_time/16_python_datetime.md) | [Day 18 >>](../18_Day_Regular_expressions/18_regular_expressions.md)
--------------------------------------------------------------------------------
/20_Day_Python_package_manager/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CagriElvan/30-Days-of-Phyton/aee0d5548316ab53dbf1978640d14b3e6e3be0d1/20_Day_Python_package_manager/__init__.py
--------------------------------------------------------------------------------
/20_Day_Python_package_manager/arithmetic.py:
--------------------------------------------------------------------------------
1 | def add_numbers(*args):
2 | total = 0
3 | for num in args:
4 | total += num
5 | return total
6 |
7 |
8 | def subtract(a, b):
9 | return (a - b)
10 |
11 |
12 | def multiple(a, b):
13 | return a * b
14 |
15 |
16 | def division(a, b):
17 | return a / b
18 |
19 |
20 | def remainder(a, b):
21 | return a % b
22 |
23 |
24 | def power(a, b):
25 | return a ** b
--------------------------------------------------------------------------------
/20_Day_Python_package_manager/greet.py:
--------------------------------------------------------------------------------
1 | def greet_person(firstname, lastname):
2 | return f'{firstname} {lastname}, welcome to 30DaysOfPython Challenge!'
--------------------------------------------------------------------------------
/22_Day_Web_scraping/22_web_scraping.md:
--------------------------------------------------------------------------------
1 |
15 |
16 | [<< Day 21](../21_Day_Classes_and_objects/21_classes_and_objects.md) | [Day 23 >>](../23_Day_Virtual_environment/23_virtual_environment.md)
17 |
18 | 
19 |
20 | - [📘 Day 22](#-day-22)
21 | - [Python Web Scraping](#python-web-scraping)
22 | - [What is Web Scrapping](#what-is-web-scrapping)
23 | - [💻 Exercises: Day 22](#-exercises-day-22)
24 |
25 | # 📘 Day 22
26 |
27 | ## Python Web Scraping
28 |
29 | ### What is Web Scrapping
30 |
31 | The internet is full of huge amount of data which can be used for different purposes. To collect this data we need to know how to scrape data from a website.
32 |
33 | Web scraping is the process of extracting and collecting data from websites and storing it on a local machine or in a database.
34 |
35 | In this section, we will use beautifulsoup and requests package to scrape data. The package version we are using is beautifulsoup 4.
36 |
37 | To start scraping websites you need _requests_, _beautifoulSoup4_ and a _website_.
38 |
39 | ```sh
40 | pip install requests
41 | pip install beautifulsoup4
42 | ```
43 |
44 | 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.
45 | Let us import the requests and BeautifulSoup module
46 |
47 | ```py
48 | import requests
49 | from bs4 import BeautifulSoup
50 | ```
51 |
52 | Let us declare url variable for the website which we are going to scrape.
53 |
54 | ```py
55 |
56 | import requests
57 | from bs4 import BeautifulSoup
58 | url = 'https://archive.ics.uci.edu/ml/datasets.php'
59 |
60 | # Lets use the requests get method to fetch the data from url
61 |
62 | response = requests.get(url)
63 | # lets check the status
64 | status = response.status_code
65 | print(status) # 200 means the fetching was successful
66 | ```
67 |
68 | ```sh
69 | 200
70 | ```
71 |
72 | Using beautifulSoup to parse content from the page
73 |
74 | ```py
75 | import requests
76 | from bs4 import BeautifulSoup
77 | url = 'https://archive.ics.uci.edu/ml/datasets.php'
78 |
79 | response = requests.get(url)
80 | content = response.content # we get all the content from the website
81 | soup = BeautifulSoup(content, 'html.parser') # beautiful soup will give a chance to parse
82 | print(soup.title) # UCI Machine Learning Repository: Data Sets
83 | print(soup.title.get_text()) # UCI Machine Learning Repository: Data Sets
84 | print(soup.body) # gives the whole page on the website
85 | print(response.status_code)
86 |
87 | tables = soup.find_all('table', {'cellpadding':'3'})
88 | # We are targeting the table with cellpadding attribute with the value of 3
89 | # We can select using id, class or HTML tag , for more information check the beautifulsoup doc
90 | table = tables[0] # the result is a list, we are taking out data from it
91 | for td in table.find('tr').find_all('td'):
92 | print(td.text)
93 | ```
94 |
95 | 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.
96 | For reference check the [beautifulsoup documentation](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#quick-start)
97 |
98 | 🌕 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.
99 |
100 | ## 💻 Exercises: Day 22
101 |
102 | 1. Scrape the following website and store the data as json file(url = 'http://www.bu.edu/president/boston-university-facts-stats/').
103 | 1. Extract the table in this url (https://archive.ics.uci.edu/ml/datasets.php) and change it to a json file
104 | 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.
105 |
106 | 🎉 CONGRATULATIONS ! 🎉
107 |
108 | [<< Day 21](../21_Day_Web_scraping/21_class_and_object.md) | [Day 23 >>](../23_Day_Virtual_environment/23_virtual_environment.md)
109 |
--------------------------------------------------------------------------------
/22_Day_Web_scraping/scrapped_data.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "category": "Community",
4 | "Student Body": "34,589",
5 | "Living Alumni": "398,195",
6 | "Total Employees": "10,517",
7 | "Faculty": "4,171",
8 | "Nondegree Students": "2,008",
9 | "Graduate & Professional Students": "15,645",
10 | "Undergraduate Students": "16,936"
11 | },
12 | {
13 | "category": "Campus",
14 | "Classrooms": "834",
15 | "Buildings": "370",
16 | "Laboratories": "1,681",
17 | "Libraries": "21",
18 | "Campus Area (acres)": "169"
19 | },
20 | {
21 | "category": "Academics",
22 | "Study Abroad Programs": "70+",
23 | "Average Class Size": "27",
24 | "Faculty": "4,171",
25 | "Student/Faculty Ratio": "10:1",
26 | "Schools and Colleges": "17",
27 | "Programs of Study": "300+"
28 | },
29 | {
30 | "category": "Grant & Contract Awards",
31 | "Research Awards": "$574.1M",
32 | "BMC Clinical Research Grants": "$88.0M"
33 | },
34 | {
35 | "category": "Undergraduate Financial Aid & Scholarships",
36 | "Average Total Need-Based Financial Aid": "$46,252",
37 | "Average Need-Based Grant/Scholarship": "$40,969",
38 | "Grants & Scholarships (need-based)": "$275.6M",
39 | "Grants & Scholarships (non-need-based)": "$28.7M"
40 | },
41 | {
42 | "category": "Student Life",
43 | "Community Service Hours": "1.6M+",
44 | "Alternative Service Breaks Participants": "300+",
45 | "BU on Social": "new accounts daily",
46 | "Cultural & Religious Organizations": "60+",
47 | "Community Service & Justice Organizations": "80+",
48 | "Academic & Professional Organizations": "120+",
49 | "Art & Performance Organizations": "60+",
50 | "Student Organizations": "450+",
51 | "First-Year Student Outreach Project Volunteers": "800+"
52 | },
53 | {
54 | "category": "Research",
55 | "Faculty Publications": "6,000+",
56 | "Student UROP Participants": "450+",
57 | "Centers & Institutes": "130+"
58 | },
59 | {
60 | "category": "International Community",
61 | "Global Initiatives": "300+",
62 | "Cultural Student Groups": "40+",
63 | "Alumni Countries": "180+",
64 | "International Students": "11,000+"
65 | },
66 | {
67 | "category": "Athletics",
68 | "Intramural Sports & Tournaments": "15+",
69 | "Club and Intramural Sports Participants": "7,000+",
70 | "Club Sports Teams": "50",
71 | "Varsity Sports": "24"
72 | }
73 | ]
--------------------------------------------------------------------------------
/23_Day_Virtual_environment/23_virtual_environment.md:
--------------------------------------------------------------------------------
1 |
15 |
16 | [<< Day 22](../22_Day_Web_scraping/22_web_scraping.md) | [Day 24 >>](../24_Day_Statistics/24_statistics.md)
17 |
18 | 
19 |
20 | - [📘 Day 23](#-day-23)
21 | - [Setting up Virtual Environments](#setting-up-virtual-environments)
22 | - [💻 Exercises: Day 23](#-exercises-day-23)
23 |
24 | # 📘 Day 23
25 |
26 | ## Setting up Virtual Environments
27 |
28 | 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
29 |
30 | ```sh
31 | asabeneh@Asabeneh:~$ pip install virtualenv
32 | ```
33 |
34 | Inside the 30DaysOfPython folder create a flask_project folder.
35 |
36 | After installing the virtualenv package go to your project folder and create a virtual env by writing:
37 |
38 | For Mac/Linux:
39 | ```sh
40 | asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project\$ virtualenv venv
41 |
42 | ```
43 |
44 | For Windows:
45 | ```sh
46 | C:\Users\User\Documents\30DaysOfPython\flask_project>python -m venv venv
47 | ```
48 |
49 | 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.
50 |
51 | ```sh
52 | asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ ls
53 | venv/
54 | ```
55 |
56 | Let us activate the virtual environment by writing the following command at our project folder.
57 |
58 | For Mac/Linux:
59 | ```sh
60 | asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ source venv/bin/activate
61 | ```
62 | Activation of the virtual environment in Windows may very on Windows Power shell and git bash.
63 |
64 | For Windows Power Shell:
65 | ```sh
66 | C:\Users\User\Documents\30DaysOfPython\flask_project> venv\Scripts\activate
67 | ```
68 |
69 | For Windows Git bash:
70 | ```sh
71 | C:\Users\User\Documents\30DaysOfPython\flask_project> venv\Scripts\. activate
72 | ```
73 |
74 | After you write the activation command, your project directory will start with venv. See the example below.
75 |
76 | ```sh
77 | (venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$
78 | ```
79 |
80 | Now, lets check the available packages in this project by writing pip freeze. You will not see any packages.
81 |
82 | We are going to do a small flask project so let us install flask package to this project.
83 |
84 | ```sh
85 | (venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ pip install Flask
86 | ```
87 |
88 | Now, let us write pip freeze to see a list of installed packages in the project:
89 |
90 | ```sh
91 | (venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ pip freeze
92 | Click==7.0
93 | Flask==1.1.1
94 | itsdangerous==1.1.0
95 | Jinja2==2.10.3
96 | MarkupSafe==1.1.1
97 | Werkzeug==0.16.0
98 | ```
99 |
100 | When you finish you should dactivate active project using _deactivate_.
101 |
102 | ```sh
103 | (venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython$ deactivate
104 | ```
105 |
106 | The necessary modules to work with flask are installed. Now, your project directory is ready for a flask project. You should include the venv to your .gitignore file not to push it to github.
107 |
108 | ## 💻 Exercises: Day 23
109 |
110 | 1. Create a project directory with a virtual environment based on the example given above.
111 |
112 | 🎉 CONGRATULATIONS ! 🎉
113 |
114 | [<< Day 22](../22_Day_Web_scraping/22_web_scraping.md) | [Day 24 >>](../24_Day_Statistics/24_statistics.md)
115 |
--------------------------------------------------------------------------------
/28_Day_API/28_API.md:
--------------------------------------------------------------------------------
1 |
16 |
17 |
18 | [<< Day 27](../27_Day_Python_with_mongodb/27_python_with_mongodb.md) | [Day 29 >>](../29_Day_Building_API/29_building_API.md)
19 |
20 | 
21 |
22 | - [📘 Day 28](#-day-28)
23 | - [Application Programming Interface(API)](#application-programming-interfaceapi)
24 | - [API](#api)
25 | - [Building API](#building-api)
26 | - [HTTP(Hypertext Transfer Protocol)](#httphypertext-transfer-protocol)
27 | - [Structure of HTTP](#structure-of-http)
28 | - [Initial Request Line(Status Line)](#initial-request-linestatus-line)
29 | - [Initial Response Line(Status Line)](#initial-response-linestatus-line)
30 | - [Header Fields](#header-fields)
31 | - [The message body](#the-message-body)
32 | - [Request Methods](#request-methods)
33 | - [💻 Exercises: Day 28](#-exercises-day-28)
34 |
35 | # 📘 Day 28
36 |
37 | # Application Programming Interface(API)
38 |
39 | ## API
40 |
41 | API stands for Application Programming Interface. The kind of API we will cover in this section is going to be Web APIs.
42 | Web APIs are the defined interfaces through which interactions happen between an enterprise and applications that use its assets, which also is a Service Level Agreement (SLA) to specify the functional provider and expose the service path or URL for its API users.
43 |
44 | In the context of web development, an API is defined as a set of specifications, such as Hypertext Transfer Protocol (HTTP) request messages, along with a definition of the structure of response messages, usually in an XML or a JavaScript Object Notation (JSON) format.
45 |
46 | Web API has been moving away from Simple Object Access Protocol (SOAP) based web services and service-oriented architecture (SOA) towards more direct representational state transfer (REST) style web resources.
47 |
48 | Social media services, web APIs have allowed web communities to share content and data between communities and different platforms.
49 |
50 | Using API, content that is created in one place dynamically can be posted and updated to multiple locations on the web.
51 |
52 | For example, Twitter's REST API allows developers to access core Twitter data and the Search API provides methods for developers to interact with Twitter Search and trends data.
53 |
54 | Many applications provide API end points. Some examples of API such as the countries [API](https://restcountries.eu/rest/v2/all), [cat's breed API](https://api.thecatapi.com/v1/breeds).
55 |
56 | In this section, we will cover a RESTful API that uses HTTP request methods to GET, PUT, POST and DELETE data.
57 |
58 | ## Building API
59 |
60 | RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. In the previous sections, we have learned about python, flask and mongoDB. We will use the knowledge we acquire to develop a RESTful API using Python flask and mongoDB database. Every application which has CRUD(Create, Read, Update, Delete) operation has an API to create data, to get data, to update data or to delete data from a database.
61 |
62 | To build an API, it is good to understand HTTP protocol and HTTP request and response cycle.
63 |
64 | ## HTTP(Hypertext Transfer Protocol)
65 |
66 | HTTP is an established communication protocol between a client and a server. A client in this case is a browser and server is the place where you access data. HTTP is a network protocol used to deliver resources which could be files on the World Wide Web, whether they are HTML files, image files, query results, scripts, or other file types.
67 |
68 | A browser is an HTTP client because it sends requests to an HTTP server (Web server), which then sends responses back to the client.
69 |
70 | ## Structure of HTTP
71 |
72 | HTTP uses client-server model. An HTTP client opens a connection and sends a request message to an HTTP server and the HTTP server returns response message which is the requested resources. When the request response cycle completes the server closes the connection.
73 |
74 | 
75 |
76 | The format of the request and response messages are similar. Both kinds of messages have
77 |
78 | - an initial line,
79 | - zero or more header lines,
80 | - a blank line (i.e. a CRLF by itself), and
81 | - an optional message body (e.g. a file, or query data, or query output).
82 |
83 | Let us an example of request and response messages by navigating this site:https://thirtydaysofpython-v1-final.herokuapp.com/. This site has been deployed on Heroku free dyno and in some months may not work because of high request. Support this work to make the server run all the time.
84 |
85 | 
86 |
87 | ## Initial Request Line(Status Line)
88 |
89 | The initial request line is different from the response.
90 | A request line has three parts, separated by spaces:
91 |
92 | - method name(GET, POST, HEAD)
93 | - path of the requested resource,
94 | - the version of HTTP being used. eg GET / HTTP/1.1
95 |
96 | GET is the most common HTTP that helps to get or read resource and POST is a common request method to create resource.
97 |
98 | ### Initial Response Line(Status Line)
99 |
100 | The initial response line, called the status line, also has three parts separated by spaces:
101 |
102 | - HTTP version
103 | - Response status code that gives the result of the request, and a reason which describes the status code. Example of status lines are:
104 | HTTP/1.0 200 OK
105 | or
106 | HTTP/1.0 404 Not Found
107 | Notes:
108 |
109 | The most common status codes are:
110 | 200 OK: The request succeeded, and the resulting resource (e.g. file or script output) is returned in the message body.
111 | 500 Server Error
112 | A complete list of HTTP status code can be found [here](https://httpstatuses.com/). It can be also found [here](https://httpstatusdogs.com/).
113 |
114 | ### Header Fields
115 |
116 | As you have seen in the above screenshot, header lines provide information about the request or response, or about the object sent in the message body.
117 |
118 | ```sh
119 | GET / HTTP/1.1
120 | Host: thirtydaysofpython-v1-final.herokuapp.com
121 | Connection: keep-alive
122 | Pragma: no-cache
123 | Cache-Control: no-cache
124 | Upgrade-Insecure-Requests: 1
125 | User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36
126 | Sec-Fetch-User: ?1
127 | Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
128 | Sec-Fetch-Site: same-origin
129 | Sec-Fetch-Mode: navigate
130 | Referer: https://thirtydaysofpython-v1-final.herokuapp.com/post
131 | Accept-Encoding: gzip, deflate, br
132 | Accept-Language: en-GB,en;q=0.9,fi-FI;q=0.8,fi;q=0.7,en-CA;q=0.6,en-US;q=0.5,fr;q=0.4
133 | ```
134 |
135 | ### The message body
136 |
137 | An HTTP message may have a body of data sent after the header lines. In a response, this is where the requested resource is returned to the client (the most common use of the message body), or perhaps explanatory text if there's an error. In a request, this is where user-entered data or uploaded files are sent to the server.
138 |
139 | If an HTTP message includes a body, there are usually header lines in the message that describe the body. In particular,
140 |
141 | The Content-Type: header gives the MIME-type of the data in the body(text/html, application/json, text/plain, text/css, image/gif).
142 | The Content-Length: header gives the number of bytes in the body.
143 |
144 | ### Request Methods
145 |
146 | The GET, POST, PUT and DELETE are the HTTP request methods which we are going to implement an API or a CRUD operation application.
147 |
148 | 1. GET: GET method is used to retrieve and get information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data.
149 |
150 | 2. POST: POST request is used to create data and send data to the server, for example, creating a new post, file upload, etc. using HTML forms.
151 |
152 | 3. PUT: Replaces all current representations of the target resource with the uploaded content and we use it modify or update data.
153 |
154 | 4. DELETE: Removes data
155 |
156 | ## 💻 Exercises: Day 28
157 |
158 | 1. Read about API and HTTP
159 |
160 | 🎉 CONGRATULATIONS ! 🎉
161 |
162 | [<< Day 27](../27_Day_Python_with_mongodb/27_python_with_mongodb.md) | [Day 29 >>](../29_Day_Building_API/29_building_API.md)
163 |
--------------------------------------------------------------------------------
/30-Days-of-Phyton/README.md:
--------------------------------------------------------------------------------
1 | # 30-Days-of-Phyton
2 | How to learn Phyton in 30 Days
3 |
--------------------------------------------------------------------------------
/30_Day_Conclusions/30_conclusions.md:
--------------------------------------------------------------------------------
1 |
18 |
19 | [<< Day 29](../29_Day_Building_API/29_building_API.md)
20 | 
21 |
22 | - [Day 30](#day-30)
23 | - [Conclusions](#conclusions)
24 |
25 | # Day 30
26 |
27 |
28 | ## Conclusions
29 |
30 | In the process of preparing this material I have learned quite a lot and you have inspired me to do more. Congratulations for making it to this level. If you have done all the exercise and the projects, now you are capable to go to a data analysis, data science, machine learning or web development paths. [Support the author for more educational materials](https://www.paypal.com/paypalme/asabeneh).
31 |
32 | ## Testimony
33 | Now it is time to express your thoughts about the Author and 30DaysOfPyhton. You can leave your testimonial on this [link](https://testimonify.herokuapp.com/)
34 |
35 | GIVE FEEDBACK:
36 | http://thirtydayofpython-api.herokuapp.com/feedback
37 |
38 | 🎉 CONGRATULATIONS ! 🎉
39 |
40 | [<< Day 29](../29_Day_Building_API/29_building_API.md)
41 |
--------------------------------------------------------------------------------
/50 Days of Phython .pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CagriElvan/30-Days-of-Phyton/aee0d5548316ab53dbf1978640d14b3e6e3be0d1/50 Days of Phython .pdf
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 30-Days-of-Phyton
2 | How to learn Phyton in 30 Days
3 |
--------------------------------------------------------------------------------
/data/countries.py:
--------------------------------------------------------------------------------
1 | countries = [
2 | 'Afghanistan',
3 | 'Albania',
4 | 'Algeria',
5 | 'Andorra',
6 | 'Angola',
7 | 'Antigua and Barbuda',
8 | 'Argentina',
9 | 'Armenia',
10 | 'Australia',
11 | 'Austria',
12 | 'Azerbaijan',
13 | 'Bahamas',
14 | 'Bahrain',
15 | 'Bangladesh',
16 | 'Barbados',
17 | 'Belarus',
18 | 'Belgium',
19 | 'Belize',
20 | 'Benin',
21 | 'Bhutan',
22 | 'Bolivia',
23 | 'Bosnia and Herzegovina',
24 | 'Botswana',
25 | 'Brazil',
26 | 'Brunei',
27 | 'Bulgaria',
28 | 'Burkina Faso',
29 | 'Burundi',
30 | 'Cambodia',
31 | 'Cameroon',
32 | 'Canada',
33 | 'Cape Verde',
34 | 'Central African Republic',
35 | 'Chad',
36 | 'Chile',
37 | 'China',
38 | 'Colombi',
39 | 'Comoros',
40 | 'Congo (Brazzaville)',
41 | 'Congo',
42 | 'Costa Rica',
43 | "Cote d'Ivoire",
44 | 'Croatia',
45 | 'Cuba',
46 | 'Cyprus',
47 | 'Czech Republic',
48 | 'Denmark',
49 | 'Djibouti',
50 | 'Dominica',
51 | 'Dominican Republic',
52 | 'East Timor (Timor Timur)',
53 | 'Ecuador',
54 | 'Egypt',
55 | 'El Salvador',
56 | 'Equatorial Guinea',
57 | 'Eritrea',
58 | 'Estonia',
59 | 'Ethiopia',
60 | 'Fiji',
61 | 'Finland',
62 | 'France',
63 | 'Gabon',
64 | 'Gambia, The',
65 | 'Georgia',
66 | 'Germany',
67 | 'Ghana',
68 | 'Greece',
69 | 'Grenada',
70 | 'Guatemala',
71 | 'Guinea',
72 | 'Guinea-Bissau',
73 | 'Guyana',
74 | 'Haiti',
75 | 'Honduras',
76 | 'Hungary',
77 | 'Iceland',
78 | 'India',
79 | 'Indonesia',
80 | 'Iran',
81 | 'Iraq',
82 | 'Ireland',
83 | 'Israel',
84 | 'Italy',
85 | 'Jamaica',
86 | 'Japan',
87 | 'Jordan',
88 | 'Kazakhstan',
89 | 'Kenya',
90 | 'Kiribati',
91 | 'Korea, North',
92 | 'Korea, South',
93 | 'Kuwait',
94 | 'Kyrgyzstan',
95 | 'Laos',
96 | 'Latvia',
97 | 'Lebanon',
98 | 'Lesotho',
99 | 'Liberia',
100 | 'Libya',
101 | 'Liechtenstein',
102 | 'Lithuania',
103 | 'Luxembourg',
104 | 'Macedonia',
105 | 'Madagascar',
106 | 'Malawi',
107 | 'Malaysia',
108 | 'Maldives',
109 | 'Mali',
110 | 'Malta',
111 | 'Marshall Islands',
112 | 'Mauritania',
113 | 'Mauritius',
114 | 'Mexico',
115 | 'Micronesia',
116 | 'Moldova',
117 | 'Monaco',
118 | 'Mongolia',
119 | 'Morocco',
120 | 'Mozambique',
121 | 'Myanmar',
122 | 'Namibia',
123 | 'Nauru',
124 | 'Nepal',
125 | 'Netherlands',
126 | 'New Zealand',
127 | 'Nicaragua',
128 | 'Niger',
129 | 'Nigeria',
130 | 'Norway',
131 | 'Oman',
132 | 'Pakistan',
133 | 'Palau',
134 | 'Panama',
135 | 'Papua New Guinea',
136 | 'Paraguay',
137 | 'Peru',
138 | 'Philippines',
139 | 'Poland',
140 | 'Portugal',
141 | 'Qatar',
142 | 'Romania',
143 | 'Russia',
144 | 'Rwanda',
145 | 'Saint Kitts and Nevis',
146 | 'Saint Lucia',
147 | 'Saint Vincent',
148 | 'Samoa',
149 | 'San Marino',
150 | 'Sao Tome and Principe',
151 | 'Saudi Arabia',
152 | 'Senegal',
153 | 'Serbia and Montenegro',
154 | 'Seychelles',
155 | 'Sierra Leone',
156 | 'Singapore',
157 | 'Slovakia',
158 | 'Slovenia',
159 | 'Solomon Islands',
160 | 'Somalia',
161 | 'South Africa',
162 | 'Spain',
163 | 'Sri Lanka',
164 | 'Sudan',
165 | 'Suriname',
166 | 'Swaziland',
167 | 'Sweden',
168 | 'Switzerland',
169 | 'Syria',
170 | 'Taiwan',
171 | 'Tajikistan',
172 | 'Tanzania',
173 | 'Thailand',
174 | 'Togo',
175 | 'Tonga',
176 | 'Trinidad and Tobago',
177 | 'Tunisia',
178 | 'Turkey',
179 | 'Turkmenistan',
180 | 'Tuvalu',
181 | 'Uganda',
182 | 'Ukraine',
183 | 'United Arab Emirates',
184 | 'United Kingdom',
185 | 'United States',
186 | 'Uruguay',
187 | 'Uzbekistan',
188 | 'Vanuatu',
189 | 'Vatican City',
190 | 'Venezuela',
191 | 'Vietnam',
192 | 'Yemen',
193 | 'Zambia',
194 | 'Zimbabwe',
195 | ];
--------------------------------------------------------------------------------
/data/donald_speech.txt:
--------------------------------------------------------------------------------
1 | Chief Justice Roberts, President Carter, President Clinton,President Bush, fellow Americans and people of the world – thank you.
2 | We the citizens of America have now joined a great national effort to rebuild our county and restore its promise for all our people.
3 | Together we will determine the course of America for many, many years to come.
4 | Together we will face challenges. We will confront hardships. But we will get the job done.
5 | Every four years we gather on these steps to carry out the orderly and peaceful transfer of power.
6 | And we are grateful to President Obama and First Lady Michelle Obama for their gracious aid throughout this transition. They have been magnificent, thank you.
7 | Today’s ceremony, however, has very special meaning because today we are not merely transferring power from one administration to another – but transferring it from Washington DC and giving it back to you the people.
8 | For too long a small group in our nation’s capital has reaped the rewards of government while the people have borne the cost.
9 | Washington flourished but the people did not share in its wealth. Politicians prospered but the jobs left and the factories closed.The establishment protected itself but not the citizens of our country.
10 | Their victories have not been your victories. Their triumphs have not been your triumphs. While they have celebrated there has been little to celebrate for struggling families all across our land.
11 | That all changes starting right here and right now because this moment is your moment. It belongs to you. It belongs to everyone gathered here today and everyone watching all across America today.
12 | This is your day.This is your celebration.And this – the United States of America – is your country.What truly matters is not what party controls our government but that this government is controlled by the people.
13 | Today, January 20 2017, will be remembered as the day the people became the rulers of this nation again.The forgotten men and women of our country will be forgotten no longer. Everyone is listening to you now.
14 | You came by the tens of millions to become part of a historic movement – the likes of which the world has never seen before.
15 | At the centre of this movement is a crucial conviction – that a nation exists to serve its citizens.Americans want great schools for their children, safe neighbourhoods for their families and good jobs for themselves.
16 | These are just and reasonable demands.Mothers and children trapped in poverty in our inner cities, rusted out factories scattered like tombstones across the landscape of our nation.
17 | An education system flushed with cash, but which leaves our young and beautiful students deprived of all knowledge. And the crime and the gangs and the drugs which deprive people of so much unrealised potential.
18 | We are one nation, and their pain is our pain, their dreams are our dreams, we share one nation, one home and one glorious destiny.
19 | Today I take an oath of allegiance to all Americans. For many decades, we’ve enriched foreign industry at the expense of American industry, subsidised the armies of other countries, while allowing the sad depletion of our own military.
20 | We've defended other nations’ borders while refusing to defend our own.And spent trillions and trillions of dollars overseas while America’s infrastructure has fallen into disrepair and decay.
21 | We have made other countries rich while the wealth, strength and confidence of our country has dissipated over the horizon.
22 | One by one, shutters have closed on our factories without even a thought about the millions and millions of those who have been left behind.
23 | But that is the past and now we are looking only to the future.
24 | We assembled here today are issuing a new decree to be heard in every city, in every foreign capital, in every hall of power – from this day on a new vision will govern our land – from this day onwards it is only going to be America first – America first!
25 | Every decision on trade, on taxes, on immigration, on foreign affairs will be made to benefit American workers and American families.
26 | Protection will lead to great prosperity and strength. I will fight for you with every bone in my body and I will never ever let you down.
27 | America will start winning again. America will start winning like never before.
28 | We will bring back our jobs, we will bring back our borders, we will bring back our wealth, we will bring back our dreams.
29 | We will bring new roads and high roads and bridges and tunnels and railways all across our wonderful nation.
30 | We will get our people off welfare and back to work – rebuilding our country with American hands and American labour.
31 | We will follow two simple rules – buy American and hire American.
32 | We see good will with the nations of the world but we do so with the understanding that it is the right of all nations to put their nations first.
33 | We will shine for everyone to follow.We will reinforce old alliances and form new ones, and untie the world against radical Islamic terrorism which we will eradicate from the face of the earth.
34 | At the bed rock of our politics will be an allegiance to the United States.And we will discover new allegiance to each other. There is no room for prejudice.
35 | The bible tells us how good and pleasant it is when god’s people live together in unity.When America is united, America is totally unstoppable
36 | There is no fear, we are protected and will always be protected by the great men and women of our military and most importantly we will be protected by god.
37 | Finally, we must think big and dream even bigger. As Americans, we know we live as a nation only when it is striving.
38 | We will no longer accept politicians who are always complaining but never doing anything about it.The time for empty talk is over, now arrives the hour of action.
39 | Do not allow anyone to tell you it cannot be done. No challenge can match the heart and fight and spirit of America. We will not fail, our country will thrive and prosper again.
40 | We stand at the birth of a new millennium, ready to unlock the mysteries of space, to free the earth from the miseries of disease, to harvest the energies, industries and technologies of tomorrow.
41 | A new national pride will stir ourselves, lift our sights and heal our divisions. It’s time to remember that old wisdom our soldiers will never forget, that whether we are black or brown or white, we all bleed the same red blood of patriots.
42 | We all enjoy the same glorious freedoms and we all salute the same great American flag and whether a child is born in the urban sprawl of Detroit or the windswept plains of Nebraska, they look at the same night sky, and dream the same dreams, and they are infused with the breath by the same almighty creator.
43 | So to all Americans in every city near and far, small and large, from mountain to mountain, from ocean to ocean – hear these words – you will never be ignored again.
44 | Your voice, your hopes and dreams will define your American destiny.Your courage, goodness and love will forever guide us along the way.
45 | Together we will make America strong again, we will make America wealthy again, we will make America safe again and yes – together we will make America great again.
46 | Thank you.
47 | God bless you.
48 | And god bless America.
49 |
--------------------------------------------------------------------------------
/data/fortune1000_final.csv:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CagriElvan/30-Days-of-Phyton/aee0d5548316ab53dbf1978640d14b3e6e3be0d1/data/fortune1000_final.csv
--------------------------------------------------------------------------------
/mymodule.py:
--------------------------------------------------------------------------------
1 | def generate_full_name(firstname, lastname):
2 | space = ' '
3 | fullname = firstname + space + lastname
4 | return fullname
5 |
6 | def sum_two_nums (num1, num2):
7 | return num1 + num2
8 | gravity = 9.81
9 | person = {
10 | "firstname": "Asabeneh",
11 | "age": 250,
12 | "country": "Finland",
13 | "city":'Helsinki'
14 | }
15 |
16 |
17 |
--------------------------------------------------------------------------------
/old_files/readme22-24.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | 🧳 [Part 1: Day 1 - 3](https://github.com/Asabeneh/30-Days-Of-Python)
4 | 🧳 [Part 2: Day 4 - 6](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/readme4-6.md)
5 | 🧳 [Part 3: Day 7 - 9](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/readme7-9.md)
6 | 🧳 [Part 4: Day 10 - 12](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/readme10-12.md)
7 | 🧳 [Part 5: Day 13 - 15](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/readme13-15.md)
8 | 🧳 [Part 6: Day 16 - 18](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/readme16-18.md)
9 | 🧳 [Part 7: Day 19 - 21](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/readme19-21.md)
10 | 🧳 [Part 8: Day 22 - 24](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/readme22-24.md)
11 | 🧳 [Part 9: Day 25 - 27](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/readme25-27.md)
12 | 🧳 [Part 10: Day 28 - 30](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/readme28-30.md)
13 |
14 | ---
15 | - [📘 Day 22](#%f0%9f%93%98-day-22)
16 | - [Python Web Scraping](#python-web-scraping)
17 | - [What is web scrapping](#what-is-web-scrapping)
18 | - [💻 Exercises: Day 22](#%f0%9f%92%bb-exercises-day-22)
19 | - [📘 Day 23](#%f0%9f%93%98-day-23)
20 | - [Setting up Virtual Environments](#setting-up-virtual-environments)
21 | - [💻 Exercises: Day 23](#%f0%9f%92%bb-exercises-day-23)
22 | - [📘 Day 24](#%f0%9f%93%98-day-24)
23 | - [Python for Statistical Analysis](#python-for-statistical-analysis)
24 | - [Statistics](#statistics)
25 | - [Data](#data)
26 | - [Statistics Module](#statistics-module)
27 | - [NumPy](#numpy)
28 |
29 | GIVE FEEDBACK: http://thirtydayofpython-api.herokuapp.com/feedback
30 | # 📘 Day 22
31 |
32 | ## Python Web Scraping
33 |
34 | ### What is web scrapping
35 |
36 | The internet is full huge amount of data which can be used for different uses. To collect this data we need to know how scrape data on a website.
37 |
38 | Web scraping is the process of extracting and collecting data from websites and storing the data into a local machine or into a database.
39 |
40 | In this section, we will use beautifulsoup and requests package to scape data. The beautifulsoup package we are using beautifulsoup 4.
41 |
42 | To start scraping a website you need _requests_, _beautifoulSoup4_ and _website_ to be scrapped.
43 |
44 | ```sh
45 | pip install requests
46 | pip installl install beautifulsoup4
47 | ```
48 |
49 | To scrape a data on a website it needs basic understanding of HTML tags and css selectors. We target content from a website using HTML tag, class or an id.
50 | Let's import the requests and BeautifulSoup module
51 |
52 | ```py
53 | import requests
54 | from bs4 import BeautifulSoup
55 | ```
56 |
57 | Let's declare url variable for the website which we are going to scrape.
58 |
59 | ```py
60 |
61 | import requests
62 | from bs4 import BeautifulSoup
63 | url = 'http://mlr.cs.umass.edu/ml/datasets.html'
64 |
65 | # Lets use the requests get method to fetch the data from url
66 |
67 | response = requests.get(url)
68 | # lets check the status
69 | status = response.status_code
70 | print(status) # 200 means the fetching was successful
71 | ```
72 |
73 | ```sh
74 | 200
75 | ```
76 |
77 | Using beautifulSoup to parse content from the page
78 |
79 | ```py
80 | import requests
81 | from bs4 import BeautifulSoup
82 | url = 'http://mlr.cs.umass.edu/ml/datasets.html'
83 |
84 | response = requests.get(url)
85 | content = response.content # we get all the content from the website
86 | soup = BeautifulSoup(content, 'html.parser') # beautiful soup will give a chance to parse
87 | print(soup.title) # UCI Machine Learning Repository: Data Sets
88 | print(soup.title.get_text()) # UCI Machine Learning Repository: Data Sets
89 | print(soup.body) # gives the whole page on the website
90 | # print(soup.body)
91 | print(response.status_code)
92 |
93 | tables = soup.find_all('table', {'cellpadding':'3'})
94 | # We are targeting the table with cellpadding attribute and the attribute value
95 | # We can select using id, class or HTML tag , for more information check the beautifulsoup doc
96 | table = tables[0] # the result is list, we are taking out from the list
97 | for td in table.find('tr').find_all('td'):
98 | print(td.text)
99 | ```
100 |
101 | If you run the above code, you can see that the extraction is half done. You can continue doing it because it is part of exercise 1.
102 | For reference check the beautiful [soup documentation](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#quick-start)
103 |
104 | ## 💻 Exercises: Day 22
105 |
106 | 1. Extract the table in this url (http://mlr.cs.umass.edu/ml/datasets.html) and change it to a json file
107 | 2. Scrape the presidents table and store the data as json(https://en.wikipedia.org/wiki/List_of_presidents_of_the_United_States)
108 |
109 | # 📘 Day 23
110 |
111 | ## Setting up Virtual Environments
112 |
113 | 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
114 |
115 | ```sh
116 | asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ pip install virtualenv
117 | ```
118 |
119 | After installing the virtualenv package go to your project folder and create a virtual env by writing:
120 | ``sh
121 | asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project\$ virtualenv venv
122 |
123 | ````
124 | The venv name could another name too but I prefer to call it venv. Let's check if the the venv is create by using ls command.
125 | ```sh
126 | asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ ls
127 | venv/
128 | ````
129 |
130 | Let's activate the virtual environment by writing the following command at our project folder.
131 |
132 | ```sh
133 | asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ source venv/bin/activate
134 |
135 | ```
136 |
137 | After you write the activation command, your project directory will start with venv. See the example below.
138 |
139 | ```sh
140 | (venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$
141 | ```
142 |
143 | Now, lets check the available package in this project by writing pip freeze. You will not see any package.
144 |
145 | We are going to do a small flask project so let's install flask to this project.
146 |
147 | ```sh
148 | (venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ pip install Flask
149 | ```
150 |
151 | Now, let's write pip freeze to see the install packages in the project
152 |
153 | ```sh
154 | (venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython/flask_project$ pip freeze
155 | Click==7.0
156 | Flask==1.1.1
157 | itsdangerous==1.1.0
158 | Jinja2==2.10.3
159 | MarkupSafe==1.1.1
160 | Werkzeug==0.16.0
161 | ```
162 |
163 | When you finish you should dactivate active project using _deactivate_.
164 |
165 | ```sh
166 | (venv) asabeneh@Asabeneh:~/Desktop/30DaysOfPython$ deactivate
167 | ```
168 |
169 | The necessary modules to work on flask are installed. Now, you project directory is ready for flask project. You should include the venv to your .gitignore file not to push it to github.
170 |
171 | ## 💻 Exercises: Day 23
172 | 1. Create a project directory with a virtual environment based on the example give above.
173 |
174 | # 📘 Day 24
175 | ## Python for Statistical Analysis
176 | ## Statistics
177 |
178 | Statistics is the discipline that studies the _collection_, _organization_, _displaying_, _analysis_, _interpretation_ and _presentation_ of data.
179 | 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.
180 | After completing this challenge, you may go to 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 decision based on data, *data tells as they say*.
181 |
182 | ## Data
183 |
184 | 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 into context, it doesn't give any sense to a human or computer. To make sense from data we need to work on the data using different tools.
185 |
186 | 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 and unstructure data.
187 |
188 | Data can be found as small or big data format. Most of the data types we will get have been covered in the file handling section.
189 |
190 | ## Statistics Module
191 |
192 | The python _statistics_ module provides functions for calculating mathematical statistics of numeric 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.
193 |
194 | # NumPy
195 |
196 | 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.
197 |
198 | Numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with arrays.
199 |
200 | 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 and you don't have install packages if you installed anaconda.
201 |
202 | [continue](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/numpy.md)
203 |
204 |
205 | [<< Part 7 ](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/readme19-21.md) | [Part 9 >>](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/readme25-27.md)
206 |
207 | ---
208 |
--------------------------------------------------------------------------------
/python_for_web/Procfile:
--------------------------------------------------------------------------------
1 | web: python app.py
--------------------------------------------------------------------------------
/python_for_web/app.py:
--------------------------------------------------------------------------------
1 | # let's import the flask
2 | from flask import Flask, render_template, request, redirect, url_for
3 | import os # importing operating system module
4 |
5 | app = Flask(__name__)
6 | # to stop caching static file
7 | app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
8 |
9 |
10 |
11 | @app.route('/') # this decorator create the home route
12 | def home ():
13 | techs = ['HTML', 'CSS', 'Flask', 'Python']
14 | name = '30 Days Of Python Programming'
15 | return render_template('home.html', techs=techs, name = name, title = 'Home')
16 |
17 | @app.route('/about')
18 | def about():
19 | name = '30 Days Of Python Programming'
20 | return render_template('about.html', name = name, title = 'About Us')
21 |
22 | @app.route('/result')
23 | def result():
24 | return render_template('result.html')
25 |
26 | @app.route('/post', methods= ['GET','POST'])
27 | def post():
28 | name = 'Text Analyzer'
29 | if request.method == 'GET':
30 | return render_template('post.html', name = name, title = name)
31 | if request.method =='POST':
32 | content = request.form['content']
33 | return redirect(url_for('result'))
34 |
35 | if __name__ == '__main__':
36 | # for deployment
37 | # to make it work for both production and development
38 | port = int(os.environ.get("PORT", 5000))
39 | app.run(debug=True, host='0.0.0.0', port=port)
--------------------------------------------------------------------------------
/python_for_web/requirements.txt:
--------------------------------------------------------------------------------
1 | Click==7.0
2 | Flask==1.1.1
3 | itsdangerous==1.1.0
4 | Jinja2==2.10.3
5 | MarkupSafe==1.1.1
6 | Werkzeug==0.16.0
7 |
--------------------------------------------------------------------------------
/python_for_web/static/css/main.css:
--------------------------------------------------------------------------------
1 | /* === GENERAL === */
2 |
3 | * {
4 | margin: 0;
5 | padding: 0;
6 | box-sizing: border-box;
7 | }
8 |
9 | /* === css variables === */
10 | :root {
11 | --header-bg-color: #4a7799;
12 | --textarea-bg-color: rgb(250, 246, 246);
13 | --body-bg-color: rgb(210, 214, 210);
14 | --nav-link-color: #bbb;
15 | }
16 |
17 | /* === body style === */
18 | body {
19 | background: var(--body-bg-color);
20 | margin: auto;
21 | line-height: 1.75;
22 | font-weight: 900;
23 | word-spacing: 1.5px;
24 | font-family: 'Lato',sans-serif;
25 | font-weight: 300;
26 | }
27 |
28 | /* === header style === */
29 | header {
30 | background: var(--header-bg-color);
31 | }
32 | /* === title and subtitle style === */
33 | h1,
34 | h2 {
35 | margin: 20px;
36 | font-weight: 300;
37 | font-family: Nunito;
38 | }
39 |
40 | /* === header menu style === */
41 |
42 | .menu-container {
43 | width: 90%;
44 | display: flex;
45 | justify-content: space-around;
46 | align-items: center;
47 | color: rgb(221, 215, 215);
48 | padding: 25px;
49 | }
50 |
51 | .nav-lists {
52 | display: flex;
53 | }
54 |
55 | .nav-list {
56 | list-style: none;
57 | margin: 0 5px;
58 | }
59 |
60 | .nav-link {
61 | text-decoration: none;
62 | font-size: 22px;
63 | padding: 0 5px;
64 | color: var(--nav-link-color);
65 | font-weight: 400;
66 | }
67 |
68 | .brand-name {
69 | font-size: 28px;
70 | font-weight: bolder;
71 | }
72 | /* === paragraph text style === */
73 | p {
74 | font-size: 22px;
75 | font-weight: 300;
76 | }
77 |
78 | /* === main style === */
79 | main {
80 | width: 90%;
81 | margin: auto;
82 | }
83 |
84 | /* === container div inside main style === */
85 |
86 | .container {
87 | background: rgb(210, 214, 210);
88 | padding: 20px;
89 | margin: auto;
90 | }
91 |
92 | .tech-lists {
93 | margin: 10px auto;
94 | text-align: left;
95 | font-size: 20px;
96 | }
97 | .tech {
98 | list-style: none;
99 | }
100 | /* === button style === */
101 | .btn {
102 | width: 150px;
103 | height: 50px;
104 | background: var(--header-bg-color);
105 | color: var(--nav-link-color);
106 | font-size: 20px;
107 | margin: 5px;
108 | border: 1px solid var(--header-bg-color);
109 | font-family: Lato;
110 | cursor: pointer;
111 | }
112 |
113 | .btn:focus {
114 | outline: 2px solid #2a70a5;
115 | cursor: pointer;
116 | }
117 | /* === textarea style === */
118 | textarea {
119 | width: 65%;
120 | margin: auto;
121 | padding: 10px 15px;
122 | outline: 2px solid rgba(207, 203, 203, 0.25);
123 | border: none;
124 | font-size: 18px;
125 | font-family: Lato;
126 | font-weight: 300;
127 | }
128 |
129 | textarea:focus {
130 | border: none;
131 | outline: 2px solid rgba(74, 119, 153, 0.45);
132 | background: var(--textarea-bg-color);
133 | font-size: 18px;
134 | caret-color: var(--header-bg-color);
135 | font-family: Lato;
136 | font-weight: 300;
137 |
138 | }
139 |
140 | /* === responsiveness === */
141 | @media (max-width:600px) {
142 |
143 | .menu-container {
144 | flex-direction: column;
145 | justify-content: space-between;
146 | }
147 | h1{
148 | font-size: 22px;
149 | }
150 |
151 | .nav-lists {
152 | flex-direction: column;
153 | }
154 |
155 | textarea {
156 | width: 100%;
157 | }
158 |
159 | }
--------------------------------------------------------------------------------
/python_for_web/templates/about.html:
--------------------------------------------------------------------------------
1 | {% extends 'layout.html' %}
2 | {% block content %}
3 |
4 |
About {{name}}
5 |
This is a 30 days of python programming challenge. If you have been coding this far, you are awesome.
6 | Congratulations
7 | for the job well done!
This application clean texts and analyse the number of word, characters and most frequent words in the text.
6 | Check it out by click text analyzer at the menu.
7 | You need the following technologies to build this web application: