diff --git a/02_Day_Variables_builtin_functions/02_variables_builtin_functions.ipynb b/02_Day_Variables_builtin_functions/02_variables_builtin_functions.ipynb new file mode 100644 index 000000000..15d7e5613 --- /dev/null +++ b/02_Day_Variables_builtin_functions/02_variables_builtin_functions.ipynb @@ -0,0 +1,325 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "81e9f2fd", + "metadata": {}, + "source": [ + "
\n", + "

30 Days Of Python: Day 2 - Variables, Builtin Functions

\n", + " \n", + " \n", + " \n", + " \n", + " \"Twitter\n", + " \n", + "\n", + "Author:\n", + "Asabeneh Yetayeh
\n", + " Second Edition: July, 2021\n", + "
\n", + "\n", + "
\n", + "\n", + "[<< Day 1](../readme.md) | [Day 3 >>](../03_Day_Operators/03_operators.md)\n", + "\n", + "![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png)\n", + "\n", + "- [📘 Day 2](#-day-2)\n", + " - [Built in functions](#built-in-functions)\n", + " - [Variables](#variables)\n", + " - [Declaring Multiple Variable in a Line](#declaring-multiple-variable-in-a-line)\n", + " - [Data Types](#data-types)\n", + " - [Checking Data types and Casting](#checking-data-types-and-casting)\n", + " - [Numbers](#numbers)\n", + " - [💻 Exercises - Day 2](#-exercises---day-2)\n", + " - [Exercises: Level 1](#exercises-level-1)\n", + " - [Exercises: Level 2](#exercises-level-2)\n", + "\n", + "# 📘 Day 2\n", + "\n", + "## Built in functions\n", + "\n", + "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).\n", + "\n", + "![Built-in Functions](../images/builtin-functions.png)\n", + "\n", + "Let us open the Python shell and start using some of the most common built-in functions.\n", + "\n", + "![Built-in functions](../images/builtin-functions_practice.png)\n", + "\n", + "Let us practice more by using different built-in functions\n", + "\n", + "![Help and Dir Built in Functions](../images/help_and_dir_builtin.png)\n", + "\n", + "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.\n", + "\n", + "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.\n", + "\n", + "![Min Max Sum](../images/builtin-functional-final.png)\n", + "\n", + "## Variables\n", + "\n", + "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.\n", + "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.\n", + "\n", + "Python Variable Name Rules\n", + "\n", + "- A variable name must start with a letter or the underscore character\n", + "- A variable name cannot start with a number\n", + "- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and \\_ )\n", + "- Variable names are case-sensitive (firstname, Firstname, FirstName and FIRSTNAME) are different variables)\n", + "\n", + "Here are some example of valid variable names:\n", + "\n", + "```shell\n", + "firstname\n", + "lastname\n", + "age\n", + "country\n", + "city\n", + "first_name\n", + "last_name\n", + "capital_city\n", + "_if # if we want to use reserved word as a variable\n", + "year_2021\n", + "year2021\n", + "current_year_2021\n", + "birth_year\n", + "num1\n", + "num2\n", + "```\n", + "\n", + "Invalid variables names\n", + "\n", + "```shell\n", + "first-name\n", + "first@name\n", + "first$name\n", + "num-1\n", + "1num\n", + "```\n", + "\n", + "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.\n", + "\n", + "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.\n", + "\n", + "_Example:_\n", + "\n", + "```py\n", + "# Variables in Python\n", + "first_name = 'Asabeneh'\n", + "last_name = 'Yetayeh'\n", + "country = 'Finland'\n", + "city = 'Helsinki'\n", + "age = 250\n", + "is_married = True\n", + "skills = ['HTML', 'CSS', 'JS', 'React', 'Python']\n", + "person_info = {\n", + " 'firstname':'Asabeneh',\n", + " 'lastname':'Yetayeh',\n", + " 'country':'Finland',\n", + " 'city':'Helsinki'\n", + " }\n", + "```\n", + "\n", + "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.\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "print('Hello, World!') # The text Hello, World! is an argument\n", + "print('Hello',',', 'World','!') # it can take multiple arguments, four arguments have been passed\n", + "print(len('Hello, World!')) # it takes only one argument\n", + "```\n", + "\n", + "Let us print and also find the length of the variables declared at the top:\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "# Printing the values stored in the variables\n", + "\n", + "print('First name:', first_name)\n", + "print('First name length:', len(first_name))\n", + "print('Last name: ', last_name)\n", + "print('Last name length: ', len(last_name))\n", + "print('Country: ', country)\n", + "print('City: ', city)\n", + "print('Age: ', age)\n", + "print('Married: ', is_married)\n", + "print('Skills: ', skills)\n", + "print('Person information: ', person_info)\n", + "```\n", + "\n", + "### Declaring Multiple Variable in a Line\n", + "\n", + "Multiple variables can also be declared in one line:\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "first_name, last_name, country, age, is_married = 'Asabeneh', 'Yetayeh', 'Helsink', 250, True\n", + "\n", + "print(first_name, last_name, country, age, is_married)\n", + "print('First name:', first_name)\n", + "print('Last name: ', last_name)\n", + "print('Country: ', country)\n", + "print('Age: ', age)\n", + "print('Married: ', is_married)\n", + "```\n", + "\n", + "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.\n", + "**Example:**\n", + "\n", + "```py\n", + "first_name = input('What is your name: ')\n", + "age = input('How old are you? ')\n", + "\n", + "print(first_name)\n", + "print(age)\n", + "```\n", + "\n", + "## Data Types\n", + "\n", + "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.\n", + "\n", + "## Checking Data types and Casting\n", + "\n", + "- Check Data types: To check the data type of certain data/variable we use the _type_\n", + " **Examples:**\n", + "\n", + "```py\n", + "# Different python data types\n", + "# Let's declare variables with various data types\n", + "\n", + "first_name = 'Asabeneh' # str\n", + "last_name = 'Yetayeh' # str\n", + "country = 'Finland' # str\n", + "city= 'Helsinki' # str\n", + "age = 250 # int, it is not my real age, don't worry about it\n", + "\n", + "# Printing out types\n", + "print(type('Asabeneh')) # str\n", + "print(type(first_name)) # str\n", + "print(type(10)) # int\n", + "print(type(3.14)) # float\n", + "print(type(1 + 1j)) # complex\n", + "print(type(True)) # bool\n", + "print(type([1, 2, 3, 4])) # list\n", + "print(type({'name':'Asabeneh'})) # dict\n", + "print(type((1,2))) # tuple\n", + "print(type(zip([1,2],[3,4]))) # zip\n", + "```\n", + "\n", + "- Casting: Converting one data type to another data type. We use _int()_, _float()_, _str()_, _list_, _set_\n", + " 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.\n", + "\n", + " **Examples:**\n", + "\n", + "```py\n", + "# int to float\n", + "num_int = 10\n", + "print('num_int',num_int) # 10\n", + "num_float = float(num_int)\n", + "print('num_float:', num_float) # 10.0\n", + "\n", + "# float to int\n", + "gravity = 9.81\n", + "print(int(gravity)) # 9\n", + "\n", + "# int to str\n", + "num_int = 10\n", + "print(num_int) # 10\n", + "num_str = str(num_int)\n", + "print(num_str) # '10'\n", + "\n", + "# str to int or float\n", + "num_str = '10.6'\n", + "num_float = float(num_str)\n", + "print('num_float', float(num_str)) # 10.6\n", + "num_int = int(num_float)\n", + "print('num_int', int(num_int)) # 10\n", + "\n", + "# str to list\n", + "first_name = 'Asabeneh'\n", + "print(first_name) # 'Asabeneh'\n", + "first_name_to_list = list(first_name)\n", + "print(first_name_to_list) # ['A', 's', 'a', 'b', 'e', 'n', 'e', 'h']\n", + "```\n", + "\n", + "## Numbers\n", + "\n", + "Number data types in Python:\n", + "\n", + "1. Integers: Integer(negative, zero and positive) numbers\n", + " Example:\n", + " ... -3, -2, -1, 0, 1, 2, 3 ...\n", + "\n", + "2. Floating Point Numbers(Decimal numbers)\n", + " Example:\n", + " ... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ...\n", + "\n", + "3. Complex Numbers\n", + " Example:\n", + " 1 + j, 2 + 4j, 1 - 1j\n", + "\n", + "🌕 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.\n", + "\n", + "## 💻 Exercises - Day 2\n", + "\n", + "### Exercises: Level 1\n", + "\n", + "1. Inside 30DaysOfPython create a folder called day_2. Inside this folder create a file named variables.py\n", + "2. Write a python comment saying 'Day 2: 30 Days of python programming'\n", + "3. Declare a first name variable and assign a value to it\n", + "4. Declare a last name variable and assign a value to it\n", + "5. Declare a full name variable and assign a value to it\n", + "6. Declare a country variable and assign a value to it\n", + "7. Declare a city variable and assign a value to it\n", + "8. Declare an age variable and assign a value to it\n", + "9. Declare a year variable and assign a value to it\n", + "10. Declare a variable is_married and assign a value to it\n", + "11. Declare a variable is_true and assign a value to it\n", + "12. Declare a variable is_light_on and assign a value to it\n", + "13. Declare multiple variable on one line\n", + "\n", + "### Exercises: Level 2\n", + "\n", + "1. Check the data type of all your variables using type() built-in function\n", + "1. Using the _len()_ built-in function, find the length of your first name\n", + "1. Compare the length of your first name and your last name\n", + "1. Declare 5 as num_one and 4 as num_two\n", + "1. Add num_one and num_two and assign the value to a variable total\n", + "1. Subtract num_two from num_one and assign the value to a variable diff\n", + "1. Multiply num_two and num_one and assign the value to a variable product\n", + "1. Divide num_one by num_two and assign the value to a variable division\n", + "1. Use modulus division to find num_two divided by num_one and assign the value to a variable remainder\n", + "1. Calculate num_one to the power of num_two and assign the value to a variable exp\n", + "1. Find floor division of num_one by num_two and assign the value to a variable floor_division\n", + "1. The radius of a circle is 30 meters.\n", + " 1. Calculate the area of a circle and assign the value to a variable name of _area_of_circle_\n", + " 2. Calculate the circumference of a circle and assign the value to a variable name of _circum_of_circle_\n", + " 3. Take radius as user input and calculate the area.\n", + "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\n", + "1. Run help('keywords') in Python shell or in your file to check for the Python reserved words or keywords\n", + "\n", + "🎉 CONGRATULATIONS ! 🎉\n", + "\n", + "[<< Day 1](../readme.md) | [Day 3 >>](../03_Day_Operators/03_operators.md)" + ] + } + ], + "metadata": { + "jupytext": { + "cell_metadata_filter": "-all", + "main_language": "python", + "notebook_metadata_filter": "-all" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/03_Day_Operators/03_operators.ipynb b/03_Day_Operators/03_operators.ipynb new file mode 100644 index 000000000..7aa77964a --- /dev/null +++ b/03_Day_Operators/03_operators.ipynb @@ -0,0 +1,352 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "f12fa3dc", + "metadata": {}, + "source": [ + "
\n", + "

30 Tage Python: Tag 3 - Operatoren

\n", + " \n", + " \n", + " \n", + " \n", + " \"Twitter\n", + " \n", + "\n", + "Autor:\n", + "Asabeneh Yetayeh
\n", + " Zweite Auflage: Juli 2021\n", + "
\n", + "
\n", + "\n", + "[<< Tag 2](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) | [Tag 4 >>](../04_Day_Strings/04_strings.md)\n", + "\n", + "![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png)\n", + "\n", + "- [📘 Tag 3](#-tag-3)\n", + " - [Boolean](#boolean)\n", + " - [Operatoren](#operatoren)\n", + " - [Zuweisungsoperatoren](#zuweisungsoperatoren)\n", + " - [Arithmetische Operatoren](#arithmetische-operatoren)\n", + " - [Vergleichsoperatoren](#vergleichsoperatoren)\n", + " - [Logische Operatoren](#logische-operatoren)\n", + " - [💻 Übungen - Tag 3](#-übungen---tag-3)\n", + "\n", + "# 📘 Tag 3\n", + "\n", + "## Boolean\n", + "\n", + "Ein Boolean-Datentyp repräsentiert einen von zwei Werten: _True_ oder _False_. Die Verwendung dieser Datentypen wird klar, sobald wir den Vergleichsoperator verwenden. Der erste Buchstabe **T** für True und **F** für False muss groß geschrieben werden, anders als in JavaScript.\n", + "**Beispiel: Boolean-Werte**\n", + "\n", + "```py\n", + "print(True)\n", + "print(False)\n", + "```\n", + "\n", + "## Operatoren\n", + "\n", + "Die Programmiersprache Python unterstützt mehrere Arten von Operatoren. In diesem Abschnitt konzentrieren wir uns auf einige davon.\n", + "\n", + "### Zuweisungsoperatoren\n", + "\n", + "Zuweisungsoperatoren werden verwendet, um Variablen Werte zuzuweisen. Nehmen wir = als Beispiel. Das Gleichheitszeichen in der Mathematik zeigt, dass zwei Werte gleich sind, aber in Python bedeutet es, dass wir einen Wert in einer bestimmten Variable speichern, und wir nennen es Zuweisung oder das Zuweisen eines Wertes an eine Variable. Die folgende Tabelle zeigt die verschiedenen Arten von Python-Zuweisungsoperatoren, übernommen von [w3school](https://www.w3schools.com/python/python_operators.asp).\n", + "\n", + "![Zuweisungsoperatoren](../images/assignment_operators.png)\n", + "\n", + "### Arithmetische Operatoren:\n", + "\n", + "- Addition(+): a + b\n", + "- Subtraktion(-): a - b\n", + "- Multiplikation(*): a * b\n", + "- Division(/): a / b\n", + "- Modulus(%): a % b\n", + "- Ganzzahldivision(//): a // b\n", + "- Potenzierung(**): a ** b\n", + "\n", + "![Arithmetische Operatoren](../images/arithmetic_operators.png)\n", + "\n", + "**Beispiel: Ganzzahlen**\n", + "\n", + "```py\n", + "# Arithmetische Operationen in Python\n", + "# Ganzzahlen\n", + "\n", + "print('Addition: ', 1 + 2) # 3\n", + "print('Subtraktion: ', 2 - 1) # 1\n", + "print('Multiplikation: ', 2 * 3) # 6\n", + "print ('Division: ', 4 / 2) # 2.0 Division in Python ergibt eine Gleitkommazahl\n", + "print('Division: ', 6 / 2) # 3.0 \n", + "print('Division: ', 7 / 2) # 3.5\n", + "print('Division ohne Rest: ', 7 // 2) # 3, ergibt keine Gleitkommazahl oder keinen Rest\n", + "print ('Division ohne Rest: ',7 // 3) # 2\n", + "print('Modulus: ', 3 % 2) # 1, Gibt den Rest zurück\n", + "print('Potenzierung: ', 2 ** 3) # 8 es bedeutet 2 * 2 * 2\n", + "```\n", + "\n", + "**Beispiel: Gleitkommazahlen**\n", + "\n", + "```py\n", + "# Gleitkommazahlen\n", + "print('Gleitkommazahl, PI', 3.14)\n", + "print('Gleitkommazahl, Schwerkraft', 9.81)\n", + "```\n", + "\n", + "**Beispiel: Komplexe Zahlen**\n", + "\n", + "```py\n", + "# Komplexe Zahlen\n", + "print('Komplexe Zahl: ', 1 + 1j)\n", + "print('Multiplikation komplexer Zahlen: ',(1 + 1j) * (1 - 1j))\n", + "```\n", + "\n", + "Lassen Sie uns eine Variable deklarieren und einen Zahlendatentyp zuweisen. Ich werde eine einzelne Zeichenvariable verwenden, aber denken Sie daran, sich nicht daran zu gewöhnen, solche Arten von Variablen zu deklarieren. Variablennamen sollten immer aussagekräftig sein.\n", + "\n", + "**Beispiel:**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1d5f450f", + "metadata": {}, + "outputs": [], + "source": [ + "# Variablen zuerst oben deklarieren\n", + "\n", + "a = 3 # a ist ein Variablenname und 3 ist ein ganzzahliger Datentyp\n", + "b = 2 # b ist ein Variablenname und 2 ist ein ganzzahliger Datentyp\n", + "\n", + "# Arithmetische Operationen und Zuweisung des Ergebnisses an eine Variable\n", + "total = a + b\n", + "diff = a - b\n", + "product = a * b\n", + "division = a / b\n", + "remainder = a % b\n", + "floor_division = a // b\n", + "exponential = a ** b\n", + "\n", + "# Ich hätte sum statt total verwenden sollen, aber sum ist eine eingebaute Funktion - versuchen Sie, das Überschreiben eingebauter Funktionen zu vermeiden\n", + "print(total) # Wenn Sie Ihren print nicht mit einem String beschriften, wissen Sie nie, woher das Ergebnis kommt\n", + "print('a + b = ', total)\n", + "print('a - b = ', diff)\n", + "print('a * b = ', product)\n", + "print('a / b = ', division)\n", + "print('a % b = ', remainder)\n", + "print('a // b = ', floor_division)\n", + "print('a ** b = ', exponential)" + ] + }, + { + "cell_type": "markdown", + "id": "72cff7e9", + "metadata": {}, + "source": [ + "**Beispiel:**\n", + "\n", + "```py\n", + "print('== Addition, Subtraktion, Multiplikation, Division, Modulus ==')\n", + "\n", + "# Werte deklarieren und zusammen organisieren\n", + "num_one = 3\n", + "num_two = 4\n", + "\n", + "# Arithmetische Operationen\n", + "total = num_one + num_two\n", + "diff = num_two - num_one\n", + "product = num_one * num_two\n", + "div = num_two / num_one\n", + "remainder = num_two % num_one\n", + "\n", + "# Werte mit Beschriftung ausgeben\n", + "print('Summe: ', total)\n", + "print('Differenz: ', diff)\n", + "print('Produkt: ', product)\n", + "print('Division: ', div)\n", + "print('Rest: ', remainder)\n", + "```\n", + "\n", + "Lassen Sie uns anfangen, die Punkte zu verbinden und das, was wir bereits wissen, zu nutzen, um zu berechnen (Fläche, Volumen, Dichte, Gewicht, Umfang, Entfernung, Kraft).\n", + "\n", + "**Beispiel:**\n", + "\n", + "```py\n", + "# Berechnung der Fläche eines Kreises\n", + "radius = 10 # Radius eines Kreises\n", + "area_of_circle = 3.14 * radius ** 2 # zwei * Zeichen bedeuten Exponent oder Potenz\n", + "print('Fläche eines Kreises:', area_of_circle)\n", + "\n", + "# Berechnung der Fläche eines Rechtecks\n", + "length = 10\n", + "width = 20\n", + "area_of_rectangle = length * width\n", + "print('Fläche eines Rechtecks:', area_of_rectangle)\n", + "\n", + "# Berechnung des Gewichts eines Objekts\n", + "mass = 75\n", + "gravity = 9.81\n", + "weight = mass * gravity\n", + "print(weight, 'N') # Einheit zum Gewicht hinzufügen\n", + "\n", + "# Berechnung der Dichte einer Flüssigkeit\n", + "mass = 75 # in Kg\n", + "volume = 0.075 # in Kubikmeter\n", + "density = mass / volume # 1000 Kg/m^3\n", + "\n", + "```\n", + "\n", + "### Vergleichsoperatoren\n", + "\n", + "In der Programmierung vergleichen wir Werte, wir verwenden Vergleichsoperatoren, um zwei Werte zu vergleichen. Wir prüfen, ob ein Wert größer oder kleiner oder gleich einem anderen Wert ist. Die folgende Tabelle zeigt Python-Vergleichsoperatoren, die von [w3school](https://www.w3schools.com/python/python_operators.asp) übernommen wurden.\n", + "\n", + "![Vergleichsoperatoren](../images/comparison_operators.png)\n", + "**Beispiel: Vergleichsoperatoren**\n", + "\n", + "```py\n", + "print(3 > 2) # True, weil 3 größer als 2 ist\n", + "print(3 >= 2) # True, weil 3 größer als 2 ist\n", + "print(3 < 2) # False, weil 3 größer als 2 ist\n", + "print(2 < 3) # True, weil 2 kleiner als 3 ist\n", + "print(2 <= 3) # True, weil 2 kleiner als 3 ist\n", + "print(3 == 2) # False, weil 3 nicht gleich 2 ist\n", + "print(3 != 2) # True, weil 3 nicht gleich 2 ist\n", + "print(len('mango') == len('avocado')) # False\n", + "print(len('mango') != len('avocado')) # True\n", + "print(len('mango') < len('avocado')) # True\n", + "print(len('milk') != len('meat')) # False\n", + "print(len('milk') == len('meat')) # True\n", + "print(len('tomato') == len('potato')) # True\n", + "print(len('python') > len('dragon')) # False\n", + "\n", + "\n", + "# Der Vergleich von etwas ergibt entweder True oder False\n", + "\n", + "print('True == True: ', True == True)\n", + "print('True == False: ', True == False)\n", + "print('False == False:', False == False)\n", + "```\n", + "\n", + "Zusätzlich zu den oben genannten Vergleichsoperatoren verwendet Python:\n", + "\n", + "- _is_: Gibt True zurück, wenn beide Variablen dasselbe Objekt sind (x is y)\n", + "- _is not_: Gibt True zurück, wenn beide Variablen nicht dasselbe Objekt sind (x is not y)\n", + "- _in_: Gibt True zurück, wenn die abgefragte Liste ein bestimmtes Element enthält (x in y)\n", + "- _not in_: Gibt True zurück, wenn die abgefragte Liste ein bestimmtes Element nicht enthält (x in y)\n", + "\n", + "```py\n", + "print('1 is 1', 1 is 1) # True - weil die Datenwerte gleich sind\n", + "print('1 is not 2', 1 is not 2) # True - weil 1 nicht 2 ist\n", + "print('A in Asabeneh', 'A' in 'Asabeneh') # True - A wurde im String gefunden\n", + "print('B in Asabeneh', 'B' in 'Asabeneh') # False - es gibt kein großes B\n", + "print('coding' in 'coding for all') # True - weil 'coding for all' das Wort 'coding' enthält\n", + "print('a in an:', 'a' in 'an') # True\n", + "print('4 is 2 ** 2:', 4 is 2 ** 2) # True\n", + "```\n", + "\n", + "### Logische Operatoren\n", + "\n", + "Im Gegensatz zu anderen Programmiersprachen verwendet Python die Schlüsselwörter _and_, _or_ und _not_ für logische Operatoren. Logische Operatoren werden verwendet, um bedingte Anweisungen zu kombinieren:\n", + "\n", + "![Logische Operatoren](../images/logical_operators.png)\n", + "\n", + "```py\n", + "print(3 > 2 and 4 > 3) # True - weil beide Aussagen wahr sind\n", + "print(3 > 2 and 4 < 3) # False - weil die zweite Aussage falsch ist\n", + "print(3 < 2 and 4 < 3) # False - weil beide Aussagen falsch sind\n", + "print('True and True: ', True and True)\n", + "print(3 > 2 or 4 > 3) # True - weil beide Aussagen wahr sind\n", + "print(3 > 2 or 4 < 3) # True - weil eine der Aussagen wahr ist\n", + "print(3 < 2 or 4 < 3) # False - weil beide Aussagen falsch sind\n", + "print('True or False:', True or False)\n", + "print(not 3 > 2) # False - weil 3 > 2 wahr ist, dann ergibt not True False\n", + "print(not True) # False - Negation, der not-Operator verwandelt True in False\n", + "print(not False) # True\n", + "print(not not True) # True\n", + "print(not not False) # False\n", + "\n", + "```\n", + "\n", + "🌕 Sie haben grenzenlose Energie. Sie haben gerade die Herausforderungen von Tag 3 abgeschlossen und sind drei Schritte weiter auf Ihrem Weg zur Größe. Jetzt machen Sie einige Übungen für Ihr Gehirn und Ihre Muskeln.\n", + "\n", + "## 💻 Übungen - Tag 3\n", + "\n", + "1. Deklarieren Sie Ihr Alter als Ganzzahlvariable\n", + "2. Deklarieren Sie Ihre Größe als Gleitkommavariable\n", + "3. Deklarieren Sie eine Variable, die eine komplexe Zahl speichert\n", + "4. Schreiben Sie ein Skript, das den Benutzer auffordert, die Basis und Höhe des Dreiecks einzugeben, und berechnen Sie die Fläche dieses Dreiecks (Fläche = 0,5 x b x h).\n", + "\n", + "```py\n", + " Basis eingeben: 20\n", + " Höhe eingeben: 10\n", + " Die Fläche des Dreiecks beträgt 100\n", + "```\n", + "\n", + "5. Schreiben Sie ein Skript, das den Benutzer auffordert, die Seite a, Seite b und Seite c des Dreiecks einzugeben. Berechnen Sie den Umfang des Dreiecks (Umfang = a + b + c).\n", + "\n", + "```py\n", + "Seite a eingeben: 5\n", + "Seite b eingeben: 4\n", + "Seite c eingeben: 3\n", + "Der Umfang des Dreiecks beträgt 12\n", + "```\n", + "\n", + "6. Erhalten Sie Länge und Breite eines Rechtecks mit Eingabeaufforderung. Berechnen Sie seine Fläche (Fläche = Länge x Breite) und Umfang (Umfang = 2 x (Länge + Breite))\n", + "7. Erhalten Sie den Radius eines Kreises mit Eingabeaufforderung. Berechnen Sie die Fläche (Fläche = pi x r x r) und den Umfang (c = 2 x pi x r), wobei pi = 3,14.\n", + "8. Berechnen Sie die Steigung, den x-Achsenabschnitt und den y-Achsenabschnitt von y = 2x - 2\n", + "9. Die Steigung ist (m = y2-y1/x2-x1). Finden Sie die Steigung und die [euklidische Entfernung](https://de.wikipedia.org/wiki/Euklidischer_Abstand) zwischen Punkt (2, 2) und Punkt (6,10)\n", + "10. Vergleichen Sie die Steigungen in Aufgabe 8 und 9.\n", + "11. Berechnen Sie den Wert von y (y = x^2 + 6x + 9). Versuchen Sie, verschiedene x-Werte zu verwenden und herauszufinden, bei welchem x-Wert y gleich 0 sein wird.\n", + "12. Finden Sie die Länge von 'python' und 'dragon' und machen Sie eine falsche Vergleichsaussage.\n", + "13. Verwenden Sie den _and_-Operator, um zu prüfen, ob 'on' sowohl in 'python' als auch in 'dragon' gefunden wird\n", + "14. _Ich hoffe, dieser Kurs ist nicht voll von Fachjargon_. Verwenden Sie den _in_-Operator, um zu prüfen, ob _jargon_ im Satz ist.\n", + "15. Es gibt kein 'on' sowohl in dragon als auch in python\n", + "16. Finden Sie die Länge des Textes _python_ und konvertieren Sie den Wert in Float und konvertieren Sie ihn in String\n", + "17. Gerade Zahlen sind durch 2 teilbar und der Rest ist Null. Wie prüfen Sie mit Python, ob eine Zahl gerade ist oder nicht?\n", + "18. Prüfen Sie, ob die Ganzzahldivision von 7 durch 3 gleich dem int-konvertierten Wert von 2,7 ist.\n", + "19. Prüfen Sie, ob der Typ von '10' gleich dem Typ von 10 ist\n", + "20. Prüfen Sie, ob int('9.8') gleich 10 ist\n", + "21. Schreiben Sie ein Skript, das den Benutzer auffordert, Stunden und Stundensatz einzugeben. Berechnen Sie die Bezahlung der Person?\n", + "\n", + "```py\n", + "Stunden eingeben: 40\n", + "Stundensatz eingeben: 28\n", + "Ihr Wochenverdienst beträgt 1120\n", + "```\n", + "\n", + "22. Schreiben Sie ein Skript, das den Benutzer auffordert, die Anzahl der Jahre einzugeben. Berechnen Sie die Anzahl der Sekunden, die eine Person leben kann. Nehmen Sie an, eine Person kann hundert Jahre leben\n", + "\n", + "```py\n", + "Anzahl der Jahre eingeben, die Sie gelebt haben: 100\n", + "Sie haben 3153600000 Sekunden gelebt.\n", + "```\n", + "\n", + "23. Schreiben Sie ein Python-Skript, das die folgende Tabelle anzeigt\n", + "\n", + "```py\n", + "1 1 1 1 1\n", + "2 1 2 4 8\n", + "3 1 3 9 27\n", + "4 1 4 16 64\n", + "5 1 5 25 125\n", + "```\n", + "\n", + "🎉 HERZLICHEN GLÜCKWUNSCH! 🎉\n", + "\n", + "[<< Tag 2](../02_Day_Variables_builtin_functions/02_variables_builtin_functions.md) | [Tag 4 >>](../04_Day_Strings/04_strings.md)" + ] + } + ], + "metadata": { + "jupytext": { + "cell_metadata_filter": "-all", + "main_language": "python", + "notebook_metadata_filter": "-all" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/04_Day_Strings/04_strings.ipynb b/04_Day_Strings/04_strings.ipynb new file mode 100644 index 000000000..454872b4b --- /dev/null +++ b/04_Day_Strings/04_strings.ipynb @@ -0,0 +1,651 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "628426ab", + "metadata": {}, + "source": [ + "
\n", + "

30 Days Of Python: Day 4 - Strings

\n", + " \n", + " \n", + " \n", + " \n", + " \"Twitter\n", + " \n", + "\n", + "Author:\n", + "Asabeneh Yetayeh
\n", + " Second Edition: July, 2021\n", + "
\n", + "\n", + "
\n", + "\n", + "[<< Day 3](../03_Day_Operators/03_operators.md) | [Day 5 >>](../05_Day_Lists/05_lists.md)\n", + "\n", + "![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png)\n", + "\n", + "- [Day 4](#day-4)\n", + " - [Strings](#strings)\n", + " - [Creating a String](#creating-a-string)\n", + " - [String Concatenation](#string-concatenation)\n", + " - [Escape Sequences in Strings](#escape-sequences-in-strings)\n", + " - [String formatting](#string-formatting)\n", + " - [Old Style String Formatting (% Operator)](#old-style-string-formatting--operator)\n", + " - [New Style String Formatting (str.format)](#new-style-string-formatting-strformat)\n", + " - [String Interpolation / f-Strings (Python 3.6+)](#string-interpolation--f-strings-python-36)\n", + " - [Python Strings as Sequences of Characters](#python-strings-as-sequences-of-characters)\n", + " - [Unpacking Characters](#unpacking-characters)\n", + " - [Accessing Characters in Strings by Index](#accessing-characters-in-strings-by-index)\n", + " - [Slicing Python Strings](#slicing-python-strings)\n", + " - [Reversing a String](#reversing-a-string)\n", + " - [Skipping Characters While Slicing](#skipping-characters-while-slicing)\n", + " - [String Methods](#string-methods)\n", + " - [💻 Exercises - Day 4](#-exercises---day-4)\n", + "\n", + "# Day 4\n", + "\n", + "## Strings\n", + "\n", + "Text is a string data type. Any data type written as text is a string. Any data under single, double or triple quote are strings. There are different string methods and built-in functions to deal with string data types. To check the length of a string use the len() method.\n", + "\n", + "### Creating a String\n", + "\n", + "```py\n", + "letter = 'P' # A string could be a single character or a bunch of texts\n", + "print(letter) # P\n", + "print(len(letter)) # 1\n", + "greeting = 'Hello, World!' # String could be made using a single or double quote,\"Hello, World!\"\n", + "print(greeting) # Hello, World!\n", + "print(len(greeting)) # 13\n", + "sentence = \"I hope you are enjoying 30 days of Python Challenge\"\n", + "print(sentence)\n", + "```\n", + "\n", + "Multiline string is created by using triple single (''') or triple double quotes (\"\"\"). See the example below.\n", + "\n", + "```py\n", + "multiline_string = '''I am a teacher and enjoy teaching.\n", + "I didn't find anything as rewarding as empowering people.\n", + "That is why I created 30 days of python.'''\n", + "print(multiline_string)\n", + "\n", + "# Another way of doing the same thing\n", + "multiline_string = \"\"\"I am a teacher and enjoy teaching.\n", + "I didn't find anything as rewarding as empowering people.\n", + "That is why I created 30 days of python.\"\"\"\n", + "print(multiline_string)\n", + "```\n", + "\n", + "### String Concatenation\n", + "\n", + "We can connect strings together. Merging or connecting strings is called concatenation. See the example below:\n", + "\n", + "```py\n", + "first_name = 'Asabeneh'\n", + "last_name = 'Yetayeh'\n", + "space = ' '\n", + "full_name = first_name + space + last_name\n", + "print(full_name) # Asabeneh Yetayeh\n", + "# Checking the length of a string using len() built-in function\n", + "print(len(first_name)) # 8\n", + "print(len(last_name)) # 7\n", + "print(len(first_name) > len(last_name)) # True\n", + "print(len(full_name)) # 16\n", + "```\n", + "\n", + "### Escape Sequences in Strings\n", + "\n", + "In Python and other programming languages \\ followed by a character is an escape sequence. Let us see the most common escape characters:\n", + "\n", + "- \\n: new line\n", + "- \\t: Tab means(8 spaces)\n", + "- \\\\\\\\: Back slash\n", + "- \\\\': Single quote (')\n", + "- \\\\\": Double quote (\")\n", + "\n", + "Now, let us see the use of the above escape sequences with examples.\n", + "\n", + "```py\n", + "print('I hope everyone is enjoying the Python Challenge.\\nAre you ?') # line break\n", + "print('Days\\tTopics\\tExercises') # adding tab space or 4 spaces \n", + "print('Day 1\\t5\\t5')\n", + "print('Day 2\\t6\\t20')\n", + "print('Day 3\\t5\\t23')\n", + "print('Day 4\\t1\\t35')\n", + "print('This is a backslash symbol (\\\\)') # To write a backslash\n", + "print('In every programming language it starts with \\\"Hello, World!\\\"') # to write a double quote inside a single quote\n", + "\n", + "# output\n", + "I hope every one is enjoying the Python Challenge.\n", + "Are you ?\n", + "Days\tTopics\tExercises\n", + "Day 1\t5\t 5\n", + "Day 2\t6\t 20\n", + "Day 3\t5\t 23\n", + "Day 4\t1\t 35\n", + "This is a backslash symbol (\\)\n", + "In every programming language it starts with \"Hello, World!\"\n", + "```\n", + "\n", + "### String formatting\n", + "\n", + "#### Old Style String Formatting (% Operator)\n", + "\n", + "In Python there are many ways of formatting strings. In this section, we will cover some of them.\n", + "The \"%\" operator is used to format a set of variables enclosed in a \"tuple\" (a fixed size list), together with a format string, which contains normal text together with \"argument specifiers\", special symbols like \"%s\", \"%d\", \"%f\", \"%.number of digitsf\".\n", + "\n", + "- %s - String (or any object with a string representation, like numbers)\n", + "- %d - Integers\n", + "- %f - Floating point numbers\n", + "- \"%.number of digitsf\" - Floating point numbers with fixed precision\n", + "\n", + "```py\n", + "# Strings only\n", + "first_name = 'Asabeneh'\n", + "last_name = 'Yetayeh'\n", + "language = 'Python'\n", + "formated_string = 'I am %s %s. I teach %s' %(first_name, last_name, language)\n", + "print(formated_string)\n", + "\n", + "# Strings and numbers\n", + "radius = 10\n", + "pi = 3.14\n", + "area = pi * radius ** 2\n", + "formated_string = 'The area of circle with a radius %d is %.2f.' %(radius, area) # 2 refers the 2 significant digits after the point\n", + "\n", + "python_libraries = ['Django', 'Flask', 'NumPy', 'Matplotlib','Pandas']\n", + "formated_string = 'The following are python libraries:%s' % (python_libraries)\n", + "print(formated_string) # \"The following are python libraries:['Django', 'Flask', 'NumPy', 'Matplotlib','Pandas']\"\n", + "```\n", + "\n", + "#### New Style String Formatting (str.format)\n", + "\n", + "This formatting is introduced in Python version 3.\n", + "\n", + "```py\n", + "\n", + "first_name = 'Asabeneh'\n", + "last_name = 'Yetayeh'\n", + "language = 'Python'\n", + "formated_string = 'I am {} {}. I teach {}'.format(first_name, last_name, language)\n", + "print(formated_string)\n", + "a = 4\n", + "b = 3\n", + "\n", + "print('{} + {} = {}'.format(a, b, a + b))\n", + "print('{} - {} = {}'.format(a, b, a - b))\n", + "print('{} * {} = {}'.format(a, b, a * b))\n", + "print('{} / {} = {:.2f}'.format(a, b, a / b)) # limits it to two digits after decimal\n", + "print('{} % {} = {}'.format(a, b, a % b))\n", + "print('{} // {} = {}'.format(a, b, a // b))\n", + "print('{} ** {} = {}'.format(a, b, a ** b))\n", + "\n", + "# output\n", + "4 + 3 = 7\n", + "4 - 3 = 1\n", + "4 * 3 = 12\n", + "4 / 3 = 1.33\n", + "4 % 3 = 1\n", + "4 // 3 = 1\n", + "4 ** 3 = 64\n", + "\n", + "# Strings and numbers\n", + "radius = 10\n", + "pi = 3.14\n", + "area = pi * radius ** 2\n", + "formated_string = 'The area of a circle with a radius {} is {:.2f}.'.format(radius, area) # 2 digits after decimal\n", + "print(formated_string)\n", + "\n", + "```\n", + "\n", + "#### String Interpolation / f-Strings (Python 3.6+)\n", + "\n", + "Another new string formatting is string interpolation, f-strings. Strings start with f and we can inject the data in their corresponding positions.\n", + "\n", + "```py\n", + "a = 4\n", + "b = 3\n", + "print(f'{a} + {b} = {a +b}')\n", + "print(f'{a} - {b} = {a - b}')\n", + "print(f'{a} * {b} = {a * b}')\n", + "print(f'{a} / {b} = {a / b:.2f}')\n", + "print(f'{a} % {b} = {a % b}')\n", + "print(f'{a} // {b} = {a // b}')\n", + "print(f'{a} ** {b} = {a ** b}')\n", + "```\n", + "\n", + "### Python Strings as Sequences of Characters\n", + "\n", + "Python strings are sequences of characters, and share their basic methods of access with other Python ordered sequences of objects – lists and tuples. The simplest way of extracting single characters from strings (and individual members from any sequence) is to unpack them into corresponding variables.\n", + "\n", + "#### Unpacking Characters\n", + "\n", + "```\n", + "language = 'Python'\n", + "a,b,c,d,e,f = language # unpacking sequence characters into variables\n", + "print(a) # P\n", + "print(b) # y\n", + "print(c) # t\n", + "print(d) # h\n", + "print(e) # o\n", + "print(f) # n\n", + "```\n", + "\n", + "#### Accessing Characters in Strings by Index\n", + "\n", + "In programming counting starts from zero. Therefore the first letter of a string is at zero index and the last letter of a string is the length of a string minus one.\n", + "\n", + "![String index](../images/string_index.png)\n", + "\n", + "```py\n", + "language = 'Python'\n", + "first_letter = language[0]\n", + "print(first_letter) # P\n", + "second_letter = language[1]\n", + "print(second_letter) # y\n", + "last_index = len(language) - 1\n", + "last_letter = language[last_index]\n", + "print(last_letter) # n\n", + "```\n", + "\n", + "If we want to start from right end we can use negative indexing. -1 is the last index.\n", + "\n", + "```py\n", + "language = 'Python'\n", + "last_letter = language[-1]\n", + "print(last_letter) # n\n", + "second_last = language[-2]\n", + "print(second_last) # o\n", + "```\n", + "\n", + "#### Slicing Python Strings\n", + "\n", + "In python we can slice strings into substrings.\n", + "\n", + "```py\n", + "language = 'Python'\n", + "first_three = language[0:3] # starts at zero index and up to 3 but not include 3\n", + "print(first_three) #Pyt\n", + "last_three = language[3:6]\n", + "print(last_three) # hon\n", + "# Another way\n", + "last_three = language[-3:]\n", + "print(last_three) # hon\n", + "last_three = language[3:]\n", + "print(last_three) # hon\n", + "```\n", + "\n", + "#### Reversing a String\n", + "\n", + "We can easily reverse strings in python.\n", + "\n", + "```py\n", + "greeting = 'Hello, World!'\n", + "print(greeting[::-1]) # !dlroW ,olleH\n", + "```\n", + "\n", + "#### Skipping Characters While Slicing\n", + "\n", + "It is possible to skip characters while slicing by passing step argument to slice method.\n", + "\n", + "```py\n", + "language = 'Python'\n", + "pto = language[0:6:2] #\n", + "print(pto) # Pto\n", + "```\n", + "\n", + "### String Methods\n", + "\n", + "There are many string methods which allow us to format strings. See some of the string methods in the following example:\n", + "\n", + "- capitalize(): Converts the first character of the string to capital letter\n", + "\n", + "```py\n", + "challenge = 'thirty days of python'\n", + "print(challenge.capitalize()) # 'Thirty days of python'\n", + "```\n", + "\n", + "- count(): returns occurrences of substring in string, count(substring, start=.., end=..). The start is a starting indexing for counting and end is the last index to count.\n", + "\n", + "```py\n", + "challenge = 'thirty days of python'\n", + "print(challenge.count('y')) # 3\n", + "print(challenge.count('y', 7, 14)) # 1, \n", + "print(challenge.count('th')) # 2`\n", + "```\n", + "\n", + "- endswith(): Checks if a string ends with a specified ending\n", + "\n", + "```py\n", + "challenge = 'thirty days of python'\n", + "print(challenge.endswith('on')) # True\n", + "print(challenge.endswith('tion')) # False\n", + "```\n", + "\n", + "- expandtabs(): Replaces tab character with spaces, default tab size is 8. It takes tab size argument\n", + "\n", + "```py\n", + "challenge = 'thirty\\tdays\\tof\\tpython'\n", + "print(challenge.expandtabs()) # 'thirty days of python'\n", + "print(challenge.expandtabs(10)) # 'thirty days of python'\n", + "```\n", + "\n", + "- find(): Returns the index of the first occurrence of a substring, if not found returns -1\n", + "\n", + "```py\n", + "challenge = 'thirty days of python'\n", + "print(challenge.find('y')) # 5\n", + "print(challenge.find('th')) # 0\n", + "```\n", + "\n", + "- rfind(): Returns the index of the last occurrence of a substring, if not found returns -1\n", + "\n", + "```py\n", + "challenge = 'thirty days of python'\n", + "print(challenge.rfind('y')) # 16\n", + "print(challenge.rfind('th')) # 17\n", + "```\n", + "\n", + "- format(): formats string into a nicer output \n", + " More about string formatting check this [link](https://www.programiz.com/python-programming/methods/string/format)\n", + "\n", + "```py\n", + "first_name = 'Asabeneh'\n", + "last_name = 'Yetayeh'\n", + "age = 250\n", + "job = 'teacher'\n", + "country = 'Finland'\n", + "sentence = 'I am {} {}. I am a {}. I am {} years old. I live in {}.'.format(first_name, last_name, age, job, country)\n", + "print(sentence) # I am Asabeneh Yetayeh. I am 250 years old. I am a teacher. I live in Finland.\n", + "\n", + "radius = 10\n", + "pi = 3.14\n", + "area = pi * radius ** 2\n", + "result = 'The area of a circle with radius {} is {}'.format(str(radius), str(area))\n", + "print(result) # The area of a circle with radius 10 is 314\n", + "```\n", + "\n", + "- index(): Returns the lowest index of a substring, additional arguments indicate starting and ending index (default 0 and string length - 1). If the substring is not found it raises a valueError. \n", + "\n", + "```py\n", + "challenge = 'thirty days of python'\n", + "sub_string = 'da'\n", + "print(challenge.index(sub_string)) # 7\n", + "print(challenge.index(sub_string, 9)) # error\n", + "```\n", + "\n", + "- rindex(): Returns the highest index of a substring, additional arguments indicate starting and ending index (default 0 and string length - 1)\n", + "\n", + "```py\n", + "challenge = 'thirty days of python'\n", + "sub_string = 'da'\n", + "print(challenge.rindex(sub_string)) # 7\n", + "print(challenge.rindex(sub_string, 9)) # error\n", + "print(challenge.rindex('on', 8)) # 19\n", + "```\n", + "\n", + "- isalnum(): Checks alphanumeric character\n", + "\n", + "```py\n", + "challenge = 'ThirtyDaysPython'\n", + "print(challenge.isalnum()) # True\n", + "\n", + "challenge = '30DaysPython'\n", + "print(challenge.isalnum()) # True\n", + "\n", + "challenge = 'thirty days of python'\n", + "print(challenge.isalnum()) # False, space is not an alphanumeric character\n", + "\n", + "challenge = 'thirty days of python 2019'\n", + "print(challenge.isalnum()) # False\n", + "```\n", + "\n", + "- isalpha(): Checks if all string elements are alphabet characters (a-z and A-Z)\n", + "\n", + "```py\n", + "challenge = 'thirty days of python'\n", + "print(challenge.isalpha()) # False, space is once again excluded\n", + "challenge = 'ThirtyDaysPython'\n", + "print(challenge.isalpha()) # True\n", + "num = '123'\n", + "print(num.isalpha()) # False\n", + "```\n", + "\n", + "- isdecimal(): Checks if all characters in a string are decimal (0-9)\n", + "\n", + "```py\n", + "challenge = 'thirty days of python'\n", + "print(challenge.isdecimal()) # False\n", + "challenge = '123'\n", + "print(challenge.isdecimal()) # True\n", + "challenge = '\\u00B2'\n", + "print(challenge.isdigit()) # False\n", + "challenge = '12 3'\n", + "print(challenge.isdecimal()) # False, space not allowed\n", + "```\n", + "\n", + "- isdigit(): Checks if all characters in a string are numbers (0-9 and some other unicode characters for numbers)\n", + "\n", + "```py\n", + "challenge = 'Thirty'\n", + "print(challenge.isdigit()) # False\n", + "challenge = '30'\n", + "print(challenge.isdigit()) # True\n", + "challenge = '\\u00B2'\n", + "print(challenge.isdigit()) # True\n", + "```\n", + "\n", + "- isnumeric(): Checks if all characters in a string are numbers or number related (just like isdigit(), just accepts more symbols, like ½)\n", + "\n", + "```py\n", + "num = '10'\n", + "print(num.isnumeric()) # True\n", + "num = '\\u00BD' # ½\n", + "print(num.isnumeric()) # True\n", + "num = '10.5'\n", + "print(num.isnumeric()) # False\n", + "```\n", + "\n", + "- isidentifier(): Checks for a valid identifier - it checks if a string is a valid variable name\n", + "\n", + "```py\n", + "challenge = '30DaysOfPython'\n", + "print(challenge.isidentifier()) # False, because it starts with a number\n", + "challenge = 'thirty_days_of_python'\n", + "print(challenge.isidentifier()) # True\n", + "```\n", + "\n", + "- islower(): Checks if all alphabet characters in the string are lowercase\n", + "\n", + "```py\n", + "challenge = 'thirty days of python'\n", + "print(challenge.islower()) # True\n", + "challenge = 'Thirty days of python'\n", + "print(challenge.islower()) # False\n", + "```\n", + "\n", + "- isupper(): Checks if all alphabet characters in the string are uppercase\n", + "\n", + "```py\n", + "challenge = 'thirty days of python'\n", + "print(challenge.isupper()) # False\n", + "challenge = 'THIRTY DAYS OF PYTHON'\n", + "print(challenge.isupper()) # True\n", + "```\n", + "\n", + "- join(): Returns a concatenated string\n", + "\n", + "```py\n", + "web_tech = ['HTML', 'CSS', 'JavaScript', 'React']\n", + "result = ' '.join(web_tech)\n", + "print(result) # 'HTML CSS JavaScript React'\n", + "```\n", + "\n", + "```py\n", + "web_tech = ['HTML', 'CSS', 'JavaScript', 'React']\n", + "result = '# '.join(web_tech)\n", + "print(result) # 'HTML# CSS# JavaScript# React'\n", + "```\n", + "\n", + "- strip(): Removes all given characters starting from the beginning and end of the string\n", + "\n", + "```py\n", + "challenge = 'thirty days of pythoonnn'\n", + "print(challenge.strip('noth')) # 'irty days of py'\n", + "```\n", + "\n", + "- replace(): Replaces substring with a given string\n", + "\n", + "```py\n", + "challenge = 'thirty days of python'\n", + "print(challenge.replace('python', 'coding')) # 'thirty days of coding'\n", + "```\n", + "\n", + "- split(): Splits the string, using given string or space as a separator\n", + "\n", + "```py\n", + "challenge = 'thirty days of python'\n", + "print(challenge.split()) # ['thirty', 'days', 'of', 'python']\n", + "challenge = 'thirty, days, of, python'\n", + "print(challenge.split(', ')) # ['thirty', 'days', 'of', 'python']\n", + "```\n", + "\n", + "- title(): Returns a title cased string\n", + "\n", + "```py\n", + "challenge = 'thirty days of python'\n", + "print(challenge.title()) # Thirty Days Of Python\n", + "```\n", + "\n", + "- swapcase(): Converts all uppercase characters to lowercase and all lowercase characters to uppercase characters\n", + "\n", + "```py\n", + "challenge = 'thirty days of python'\n", + "print(challenge.swapcase()) # THIRTY DAYS OF PYTHON\n", + "challenge = 'Thirty Days Of Python'\n", + "print(challenge.swapcase()) # tHIRTY dAYS oF pYTHON\n", + "```\n", + "\n", + "- startswith(): Checks if String Starts with the Specified String\n", + "\n", + "```py\n", + "challenge = 'thirty days of python'\n", + "print(challenge.startswith('thirty')) # True\n", + "\n", + "challenge = '30 days of python'\n", + "print(challenge.startswith('thirty')) # False\n", + "```\n", + "\n", + "🌕 You are an extraordinary person and you have a remarkable potential. You have just completed day 4 challenges and you are four steps a head in to your way to greatness. Now do some exercises for your brain and muscles.\n", + "\n", + "## 💻 Exercises - Day 4\n", + "\n", + "1. Concatenate the string 'Thirty', 'Days', 'Of', 'Python' to a single string, 'Thirty Days Of Python'.\n", + "2. Concatenate the string 'Coding', 'For' , 'All' to a single string, 'Coding For All'.\n", + "3. Declare a variable named company and assign it to an initial value \"Coding For All\".\n", + "4. Print the variable company using _print()_.\n", + "5. Print the length of the company string using _len()_ method and _print()_.\n", + "6. Change all the characters to uppercase letters using _upper()_ method.\n", + "7. Change all the characters to lowercase letters using _lower()_ method.\n", + "8. Use capitalize(), title(), swapcase() methods to format the value of the string _Coding For All_.\n", + "9. Cut(slice) out the first word of _Coding For All_ string.\n", + "10. Check if _Coding For All_ string contains a word Coding using the method index, find or other methods.\n", + "11. Replace the word coding in the string 'Coding For All' to Python.\n", + "12. Change Python for Everyone to Python for All using the replace method or other methods.\n", + "13. Split the string 'Coding For All' using space as the separator (split()) .\n", + "14. \"Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon\" split the string at the comma.\n", + "15. What is the character at index 0 in the string _Coding For All_.\n", + "16. What is the last index of the string _Coding For All_.\n", + "17. What character is at index 10 in \"Coding For All\" string.\n", + "18. Create an acronym or an abbreviation for the name 'Python For Everyone'.\n", + "19. Create an acronym or an abbreviation for the name 'Coding For All'.\n", + "20. Use index to determine the position of the first occurrence of C in Coding For All.\n", + "21. Use index to determine the position of the first occurrence of F in Coding For All.\n", + "22. Use rfind to determine the position of the last occurrence of l in Coding For All People.\n", + "23. Use index or find to find the position of the first occurrence of the word 'because' in the following sentence: 'You cannot end a sentence with because because because is a conjunction'\n", + "24. Use rindex to find the position of the last occurrence of the word because in the following sentence: 'You cannot end a sentence with because because because is a conjunction'\n", + "25. Slice out the phrase 'because because because' in the following sentence: 'You cannot end a sentence with because because because is a conjunction'\n", + "26. Find the position of the first occurrence of the word 'because' in the following sentence: 'You cannot end a sentence with because because because is a conjunction'\n", + "27. Slice out the phrase 'because because because' in the following sentence: 'You cannot end a sentence with because because because is a conjunction'\n", + "28. Does '\\'Coding For All' start with a substring _Coding_?\n", + "29. Does 'Coding For All' end with a substring _coding_?\n", + "30. '   Coding For All      '  , remove the left and right trailing spaces in the given string.\n", + "31. Which one of the following variables return True when we use the method isidentifier():\n", + " - 30DaysOfPython\n", + " - thirty_days_of_python\n", + "32. The following list contains the names of some of python libraries: ['Django', 'Flask', 'Bottle', 'Pyramid', 'Falcon']. Join the list with a hash with space string.\n", + "33. Use the new line escape sequence to separate the following sentences.\n", + " ```py\n", + " I am enjoying this challenge.\n", + " I just wonder what is next.\n", + " ```\n", + "34. Use a tab escape sequence to write the following lines.\n", + " ```py\n", + " Name Age Country City\n", + " Asabeneh 250 Finland Helsinki\n", + " ```\n", + "35. Use the string formatting method to display the following:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "60ed3780", + "metadata": {}, + "outputs": [], + "source": [ + "radius = 10\n", + "area = 3.14 * radius ** 2\n", + "The area of a circle with radius 10 is 314 meters square." + ] + }, + { + "cell_type": "markdown", + "id": "b66b5ea4", + "metadata": {}, + "source": [ + "36. Make the following using string formatting methods:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ff7a17dd", + "metadata": {}, + "outputs": [], + "source": [ + "8 + 6 = 14\n", + "8 - 6 = 2\n", + "8 * 6 = 48\n", + "8 / 6 = 1.33\n", + "8 % 6 = 2\n", + "8 // 6 = 1\n", + "8 ** 6 = 262144" + ] + }, + { + "cell_type": "markdown", + "id": "9ce35fd2", + "metadata": {}, + "source": [ + "🎉 CONGRATULATIONS ! 🎉\n", + "\n", + "[<< Day 3](../03_Day_Operators/03_operators.md) | [Day 5 >>](../05_Day_Lists/05_lists.md)\n", + "\n" + ] + } + ], + "metadata": { + "jupytext": { + "cell_metadata_filter": "-all", + "custom_cell_magics": "kql", + "main_language": "sh" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/04_Day_Strings/04_strings.md b/04_Day_Strings/04_strings.md index 3bf09ed2a..d526cc9cb 100644 --- a/04_Day_Strings/04_strings.md +++ b/04_Day_Strings/04_strings.md @@ -1,3 +1,16 @@ +--- +jupyter: + jupytext: + cell_metadata_filter: -all + custom_cell_magics: kql + main_language: sh + text_representation: + extension: .md + format_name: markdown + format_version: '1.3' + jupytext_version: 1.11.2 +--- +

30 Days Of Python: Day 4 - Strings

diff --git a/05_Day_Lists/005_lists.ipynb b/05_Day_Lists/005_lists.ipynb new file mode 100644 index 000000000..021bdb1fc --- /dev/null +++ b/05_Day_Lists/005_lists.ipynb @@ -0,0 +1,635 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "216aa310", + "metadata": {}, + "source": [ + "
\n", + "

30 Days Of Python: Day 5 - Lists

\n", + "
\n", + " \n", + " \n", + " \n", + " \"Twitter\n", + " \n", + "\n", + "Author:\n", + "Asabeneh Yetayeh
\n", + " Second Edition: July - 2021\n", + "
\n", + "\n", + "
\n", + "\n", + "[<< Day 4](../04_Day_Strings/04_strings.md) | [Day 6 >>](../06_Day_Tuples/06_tuples.md)\n", + "\n", + "![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png)\n", + "\n", + "- [Day 5](#day-5)\n", + " - [Lists](#lists)\n", + " - [How to Create a List](#how-to-create-a-list)\n", + " - [Accessing List Items Using Positive Indexing](#accessing-list-items-using-positive-indexing)\n", + " - [Accessing List Items Using Negative Indexing](#accessing-list-items-using-negative-indexing)\n", + " - [Unpacking List Items](#unpacking-list-items)\n", + " - [Slicing Items from a List](#slicing-items-from-a-list)\n", + " - [Modifying Lists](#modifying-lists)\n", + " - [Checking Items in a List](#checking-items-in-a-list)\n", + " - [Adding Items to a List](#adding-items-to-a-list)\n", + " - [Inserting Items into a List](#inserting-items-into-a-list)\n", + " - [Removing Items from a List](#removing-items-from-a-list)\n", + " - [Removing Items Using Pop](#removing-items-using-pop)\n", + " - [Removing Items Using Del](#removing-items-using-del)\n", + " - [Clearing List Items](#clearing-list-items)\n", + " - [Copying a List](#copying-a-list)\n", + " - [Joining Lists](#joining-lists)\n", + " - [Counting Items in a List](#counting-items-in-a-list)\n", + " - [Finding Index of an Item](#finding-index-of-an-item)\n", + " - [Reversing a List](#reversing-a-list)\n", + " - [Sorting List Items](#sorting-list-items)\n", + " - [💻 Exercises: Day 5](#-exercises-day-5)\n", + " - [Exercises: Level 1](#exercises-level-1)\n", + " - [Exercises: Level 2](#exercises-level-2)\n", + "\n", + "# Day 5\n", + "\n", + "## Lists\n", + "\n", + "There are four collection data types in Python :\n", + "\n", + "- List: is a collection which is ordered and changeable(modifiable). Allows duplicate members.\n", + "- Tuple: is a collection which is ordered and unchangeable or unmodifiable(immutable). Allows duplicate members.\n", + "- Set: is a collection which is unordered, un-indexed and unmodifiable, but we can add new items to the set. Duplicate members are not allowed.\n", + "- Dictionary: is a collection which is unordered, changeable(modifiable) and indexed. No duplicate members.\n", + "\n", + "A list is collection of different data types which is ordered and modifiable(mutable). A list can be empty or it may have different data type items.\n", + "\n", + "### How to Create a List\n", + "\n", + "In Python we can create lists in two ways:\n", + "\n", + "- Using list built-in function\n", + "\n", + "```py\n", + "# syntax\n", + "lst = list()\n", + "```\n", + "\n", + "```py\n", + "empty_list = list() # this is an empty list, no item in the list\n", + "print(len(empty_list)) # 0\n", + "```\n", + "\n", + "- Using square brackets, []\n", + "\n", + "```py\n", + "# syntax\n", + "lst = []\n", + "```\n", + "\n", + "```py\n", + "empty_list = [] # this is an empty list, no item in the list\n", + "print(len(empty_list)) # 0\n", + "```\n", + "\n", + "Lists with initial values. We use _len()_ to find the length of a list.\n", + "\n", + "```py\n", + "fruits = ['banana', 'orange', 'mango', 'lemon'] # list of fruits\n", + "vegetables = ['Tomato', 'Potato', 'Cabbage','Onion', 'Carrot'] # list of vegetables\n", + "animal_products = ['milk', 'meat', 'butter', 'yoghurt'] # list of animal products\n", + "web_techs = ['HTML', 'CSS', 'JS', 'React','Redux', 'Node', 'MongDB'] # list of web technologies\n", + "countries = ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway']\n", + "\n", + "# Print the lists and its length\n", + "print('Fruits:', fruits)\n", + "print('Number of fruits:', len(fruits))\n", + "print('Vegetables:', vegetables)\n", + "print('Number of vegetables:', len(vegetables))\n", + "print('Animal products:',animal_products)\n", + "print('Number of animal products:', len(animal_products))\n", + "print('Web technologies:', web_techs)\n", + "print('Number of web technologies:', len(web_techs))\n", + "print('Countries:', countries)\n", + "print('Number of countries:', len(countries))\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "46939484", + "metadata": {}, + "outputs": [], + "source": [ + "output\n", + "Fruits: ['banana', 'orange', 'mango', 'lemon']\n", + "Number of fruits: 4\n", + "Vegetables: ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']\n", + "Number of vegetables: 5\n", + "Animal products: ['milk', 'meat', 'butter', 'yoghurt']\n", + "Number of animal products: 4\n", + "Web technologies: ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB']\n", + "Number of web technologies: 7\n", + "Countries: ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway']\n", + "Number of countries: 5" + ] + }, + { + "cell_type": "markdown", + "id": "83733ec6", + "metadata": {}, + "source": [ + "- Lists can have items of different data types\n", + "\n", + "```py\n", + " lst = ['Asabeneh', 250, True, {'country':'Finland', 'city':'Helsinki'}] # list containing different data types\n", + "```\n", + "\n", + "### Accessing List Items Using Positive Indexing\n", + "\n", + "We access each item in a list using their index. A list index starts from 0. The picture below shows clearly where the index starts\n", + "![List index](../images/list_index.png)\n", + "\n", + "```py\n", + "fruits = ['banana', 'orange', 'mango', 'lemon']\n", + "first_fruit = fruits[0] # we are accessing the first item using its index\n", + "print(first_fruit) # banana\n", + "second_fruit = fruits[1]\n", + "print(second_fruit) # orange\n", + "last_fruit = fruits[3]\n", + "print(last_fruit) # lemon\n", + "# Last index\n", + "last_index = len(fruits) - 1\n", + "last_fruit = fruits[last_index]\n", + "```\n", + "\n", + "### Accessing List Items Using Negative Indexing\n", + "\n", + "Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item.\n", + "\n", + "![List negative indexing](../images/list_negative_indexing.png)\n", + "\n", + "```py\n", + "fruits = ['banana', 'orange', 'mango', 'lemon']\n", + "first_fruit = fruits[-4]\n", + "last_fruit = fruits[-1]\n", + "second_last = fruits[-2]\n", + "print(first_fruit) # banana\n", + "print(last_fruit) # lemon\n", + "print(second_last) # mango\n", + "```\n", + "\n", + "### Unpacking List Items\n", + "\n", + "```py\n", + "lst = ['item1','item2','item3', 'item4', 'item5']\n", + "first_item, second_item, third_item, *rest = lst\n", + "print(first_item) # item1\n", + "print(second_item) # item2\n", + "print(third_item) # item3\n", + "print(rest) # ['item4', 'item5']\n", + "\n", + "```\n", + "\n", + "```py\n", + "# First Example\n", + "fruits = ['banana', 'orange', 'mango', 'lemon','lime','apple']\n", + "first_fruit, second_fruit, third_fruit, *rest = fruits \n", + "print(first_fruit) # banana\n", + "print(second_fruit) # orange\n", + "print(third_fruit) # mango\n", + "print(rest) # ['lemon','lime','apple']\n", + "# Second Example about unpacking list\n", + "first, second, third,*rest, tenth = [1,2,3,4,5,6,7,8,9,10]\n", + "print(first) # 1\n", + "print(second) # 2\n", + "print(third) # 3\n", + "print(rest) # [4,5,6,7,8,9]\n", + "print(tenth) # 10\n", + "# Third Example about unpacking list\n", + "countries = ['Germany', 'France','Belgium','Sweden','Denmark','Finland','Norway','Iceland','Estonia']\n", + "gr, fr, bg, sw, *scandic, es = countries\n", + "print(gr)\n", + "print(fr)\n", + "print(bg)\n", + "print(sw)\n", + "print(scandic)\n", + "print(es)\n", + "```\n", + "\n", + "### Slicing Items from a List\n", + "\n", + "- Positive Indexing: We can specify a range of positive indexes by specifying the start, end and step, the return value will be a new list. (default values for start = 0, end = len(lst) - 1 (last item), step = 1)\n", + "\n", + "```py\n", + "fruits = ['banana', 'orange', 'mango', 'lemon']\n", + "all_fruits = fruits[0:4] # it returns all the fruits\n", + "# this will also give the same result as the one above\n", + "all_fruits = fruits[0:] # if we don't set where to stop it takes all the rest\n", + "orange_and_mango = fruits[1:3] # it does not include the first index\n", + "orange_mango_lemon = fruits[1:]\n", + "orange_and_lemon = fruits[::2] # here we used a 3rd argument, step. It will take every 2cnd item - ['banana', 'mango']\n", + "```\n", + "\n", + "- Negative Indexing: We can specify a range of negative indexes by specifying the start, end and step, the return value will be a new list.\n", + "\n", + "```py\n", + "fruits = ['banana', 'orange', 'mango', 'lemon']\n", + "all_fruits = fruits[-4:] # it returns all the fruits\n", + "orange_and_mango = fruits[-3:-1] # it does not include the last index,['orange', 'mango']\n", + "orange_mango_lemon = fruits[-3:] # this will give starting from -3 to the end,['orange', 'mango', 'lemon']\n", + "reverse_fruits = fruits[::-1] # a negative step will take the list in reverse order,['lemon', 'mango', 'orange', 'banana']\n", + "```\n", + "\n", + "### Modifying Lists\n", + "\n", + "List is a mutable or modifiable ordered collection of items. Lets modify the fruit list.\n", + "\n", + "```py\n", + "fruits = ['banana', 'orange', 'mango', 'lemon']\n", + "fruits[0] = 'avocado'\n", + "print(fruits) # ['avocado', 'orange', 'mango', 'lemon']\n", + "fruits[1] = 'apple'\n", + "print(fruits) # ['avocado', 'apple', 'mango', 'lemon']\n", + "last_index = len(fruits) - 1\n", + "fruits[last_index] = 'lime'\n", + "print(fruits) # ['avocado', 'apple', 'mango', 'lime']\n", + "```\n", + "\n", + "### Checking Items in a List\n", + "\n", + "Checking an item if it is a member of a list using *in* operator. See the example below.\n", + "\n", + "```py\n", + "fruits = ['banana', 'orange', 'mango', 'lemon']\n", + "does_exist = 'banana' in fruits\n", + "print(does_exist) # True\n", + "does_exist = 'lime' in fruits\n", + "print(does_exist) # False\n", + "```\n", + "\n", + "### Adding Items to a List\n", + "\n", + "To add item to the end of an existing list we use the method *append()*.\n", + "\n", + "```py\n", + "# syntax\n", + "lst = list()\n", + "lst.append(item)\n", + "```\n", + "\n", + "```py\n", + "fruits = ['banana', 'orange', 'mango', 'lemon']\n", + "fruits.append('apple')\n", + "print(fruits) # ['banana', 'orange', 'mango', 'lemon', 'apple']\n", + "fruits.append('lime') # ['banana', 'orange', 'mango', 'lemon', 'apple', 'lime']\n", + "print(fruits)\n", + "```\n", + "\n", + "### Inserting Items into a List\n", + "\n", + "We can use *insert()* method to insert a single item at a specified index in a list. Note that other items are shifted to the right. The *insert()* methods takes two arguments:index and an item to insert.\n", + "\n", + "```py\n", + "# syntax\n", + "lst = ['item1', 'item2']\n", + "lst.insert(index, item)\n", + "```\n", + "\n", + "```py\n", + "fruits = ['banana', 'orange', 'mango', 'lemon']\n", + "fruits.insert(2, 'apple') # insert apple between orange and mango\n", + "print(fruits) # ['banana', 'orange', 'apple', 'mango', 'lemon']\n", + "fruits.insert(3, 'lime') # ['banana', 'orange', 'apple', 'lime', 'mango', 'lemon']\n", + "print(fruits)\n", + "```\n", + "\n", + "### Removing Items from a List\n", + "\n", + "The remove method removes a specified item from a list\n", + "\n", + "```py\n", + "# syntax\n", + "lst = ['item1', 'item2']\n", + "lst.remove(item)\n", + "```\n", + "\n", + "```py\n", + "fruits = ['banana', 'orange', 'mango', 'lemon', 'banana']\n", + "fruits.remove('banana')\n", + "print(fruits) # ['orange', 'mango', 'lemon', 'banana'] - this method removes the first occurrence of the item in the list\n", + "fruits.remove('lemon')\n", + "print(fruits) # ['orange', 'mango', 'banana']\n", + "```\n", + "\n", + "### Removing Items Using Pop\n", + "\n", + "The *pop()* method removes the specified index, (or the last item if index is not specified):\n", + "\n", + "```py\n", + "# syntax\n", + "lst = ['item1', 'item2']\n", + "lst.pop() # last item\n", + "lst.pop(index)\n", + "```\n", + "\n", + "```py\n", + "fruits = ['banana', 'orange', 'mango', 'lemon']\n", + "fruits.pop()\n", + "print(fruits) # ['banana', 'orange', 'mango']\n", + "\n", + "fruits.pop(0)\n", + "print(fruits) # ['orange', 'mango']\n", + "```\n", + "\n", + "### Removing Items Using Del\n", + "\n", + "The *del* keyword removes the specified index and it can also be used to delete items within index range. It can also delete the list completely\n", + "\n", + "```py\n", + "# syntax\n", + "lst = ['item1', 'item2']\n", + "del lst[index] # only a single item\n", + "del lst # to delete the list completely\n", + "```\n", + "\n", + "```py\n", + "fruits = ['banana', 'orange', 'mango', 'lemon', 'kiwi', 'lime']\n", + "del fruits[0]\n", + "print(fruits) # ['orange', 'mango', 'lemon', 'kiwi', 'lime']\n", + "del fruits[1]\n", + "print(fruits) # ['orange', 'lemon', 'kiwi', 'lime']\n", + "del fruits[1:3] # this deletes items between given indexes, so it does not delete the item with index 3!\n", + "print(fruits) # ['orange', 'lime']\n", + "del fruits\n", + "print(fruits) # This should give: NameError: name 'fruits' is not defined\n", + "```\n", + "\n", + "### Clearing List Items\n", + "\n", + "The *clear()* method empties the list:\n", + "\n", + "```py\n", + "# syntax\n", + "lst = ['item1', 'item2']\n", + "lst.clear()\n", + "```\n", + "\n", + "```py\n", + "fruits = ['banana', 'orange', 'mango', 'lemon']\n", + "fruits.clear()\n", + "print(fruits) # []\n", + "```\n", + "\n", + "### Copying a List\n", + "\n", + "It is possible to copy a list by reassigning it to a new variable in the following way: list2 = list1. Now, list2 is a reference of list1, any changes we make in list2 will also modify the original, list1. But there are lots of case in which we do not like to modify the original instead we like to have a different copy. One of way of avoiding the problem above is using _copy()_.\n", + "\n", + "```py\n", + "# syntax\n", + "lst = ['item1', 'item2']\n", + "lst_copy = lst.copy()\n", + "```\n", + "\n", + "```py\n", + "fruits = ['banana', 'orange', 'mango', 'lemon']\n", + "fruits_copy = fruits.copy()\n", + "print(fruits_copy) # ['banana', 'orange', 'mango', 'lemon']\n", + "```\n", + "\n", + "### Joining Lists\n", + "\n", + "There are several ways to join, or concatenate, two or more lists in Python.\n", + "\n", + "- Plus Operator (+)\n", + "\n", + "```py\n", + "# syntax\n", + "list3 = list1 + list2\n", + "```\n", + "\n", + "```py\n", + "positive_numbers = [1, 2, 3, 4, 5]\n", + "zero = [0]\n", + "negative_numbers = [-5,-4,-3,-2,-1]\n", + "integers = negative_numbers + zero + positive_numbers\n", + "print(integers) # [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]\n", + "fruits = ['banana', 'orange', 'mango', 'lemon']\n", + "vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']\n", + "fruits_and_vegetables = fruits + vegetables\n", + "print(fruits_and_vegetables ) # ['banana', 'orange', 'mango', 'lemon', 'Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']\n", + "```\n", + "\n", + "- Joining using extend() method\n", + " The *extend()* method allows to append list in a list. See the example below.\n", + "\n", + "```py\n", + "# syntax\n", + "list1 = ['item1', 'item2']\n", + "list2 = ['item3', 'item4', 'item5']\n", + "list1.extend(list2)\n", + "```\n", + "\n", + "```py\n", + "num1 = [0, 1, 2, 3]\n", + "num2= [4, 5, 6]\n", + "num1.extend(num2)\n", + "print('Numbers:', num1) # Numbers: [0, 1, 2, 3, 4, 5, 6]\n", + "negative_numbers = [-5,-4,-3,-2,-1]\n", + "positive_numbers = [1, 2, 3,4,5]\n", + "zero = [0]\n", + "\n", + "negative_numbers.extend(zero)\n", + "negative_numbers.extend(positive_numbers)\n", + "print('Integers:', negative_numbers) # Integers: [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]\n", + "fruits = ['banana', 'orange', 'mango', 'lemon']\n", + "vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']\n", + "fruits.extend(vegetables)\n", + "print('Fruits and vegetables:', fruits ) # Fruits and vegetables: ['banana', 'orange', 'mango', 'lemon', 'Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']\n", + "```\n", + "\n", + "### Counting Items in a List\n", + "\n", + "The *count()* method returns the number of times an item appears in a list:\n", + "\n", + "```py\n", + "# syntax\n", + "lst = ['item1', 'item2']\n", + "lst.count(item)\n", + "```\n", + "\n", + "```py\n", + "fruits = ['banana', 'orange', 'mango', 'lemon']\n", + "print(fruits.count('orange')) # 1\n", + "ages = [22, 19, 24, 25, 26, 24, 25, 24]\n", + "print(ages.count(24)) # 3\n", + "```\n", + "\n", + "### Finding Index of an Item\n", + "\n", + "The *index()* method returns the index of an item in the list:\n", + "\n", + "```py\n", + "# syntax\n", + "lst = ['item1', 'item2']\n", + "lst.index(item)\n", + "```\n", + "\n", + "```py\n", + "fruits = ['banana', 'orange', 'mango', 'lemon']\n", + "print(fruits.index('orange')) # 1\n", + "ages = [22, 19, 24, 25, 26, 24, 25, 24]\n", + "print(ages.index(24)) # 2, the first occurrence\n", + "```\n", + "\n", + "### Reversing a List\n", + "\n", + "The *reverse()* method reverses the order of a list.\n", + "\n", + "```py\n", + "# syntax\n", + "lst = ['item1', 'item2']\n", + "lst.reverse()\n", + "\n", + "```\n", + "\n", + "```py\n", + "fruits = ['banana', 'orange', 'mango', 'lemon']\n", + "fruits.reverse()\n", + "print(fruits) # ['lemon', 'mango', 'orange', 'banana']\n", + "ages = [22, 19, 24, 25, 26, 24, 25, 24]\n", + "ages.reverse()\n", + "print(ages) # [24, 25, 24, 26, 25, 24, 19, 22]\n", + "```\n", + "\n", + "### Sorting List Items\n", + "\n", + "To sort lists we can use _sort()_ method or _sorted()_ built-in functions. The _sort()_ method reorders the list items in ascending order and modifies the original list. If an argument of _sort()_ method reverse is equal to true, it will arrange the list in descending order.\n", + "\n", + "- sort(): this method modifies the original list\n", + "\n", + " ```py\n", + " # syntax\n", + " lst = ['item1', 'item2']\n", + " lst.sort() # ascending\n", + " lst.sort(reverse=True) # descending\n", + " ```\n", + "\n", + " **Example:**\n", + "\n", + " ```py\n", + " fruits = ['banana', 'orange', 'mango', 'lemon']\n", + " fruits.sort()\n", + " print(fruits) # sorted in alphabetical order, ['banana', 'lemon', 'mango', 'orange']\n", + " fruits.sort(reverse=True)\n", + " print(fruits) # ['orange', 'mango', 'lemon', 'banana']\n", + " ages = [22, 19, 24, 25, 26, 24, 25, 24]\n", + " ages.sort()\n", + " print(ages) # [19, 22, 24, 24, 24, 25, 25, 26]\n", + " \n", + " ages.sort(reverse=True)\n", + " print(ages) # [26, 25, 25, 24, 24, 24, 22, 19]\n", + " ```\n", + "\n", + " sorted(): returns the ordered list without modifying the original list\n", + " **Example:**\n", + "\n", + " ```py\n", + " fruits = ['banana', 'orange', 'mango', 'lemon']\n", + " print(sorted(fruits)) # ['banana', 'lemon', 'mango', 'orange']\n", + " # Reverse order\n", + " fruits = ['banana', 'orange', 'mango', 'lemon']\n", + " fruits = sorted(fruits,reverse=True)\n", + " print(fruits) # ['orange', 'mango', 'lemon', 'banana']\n", + " ```\n", + "\n", + "🌕 You are diligent and you have already achieved quite a lot. You have just completed day 5 challenges and you are 5 steps a head in to your way to greatness. Now do some exercises for your brain and muscles.\n", + "\n", + "## 💻 Exercises: Day 5\n", + "\n", + "### Exercises: Level 1\n", + "\n", + "1. Declare an empty list\n", + "2. Declare a list with more than 5 items\n", + "3. Find the length of your list\n", + "4. Get the first item, the middle item and the last item of the list\n", + "5. Declare a list called mixed_data_types, put your(name, age, height, marital status, address)\n", + "6. Declare a list variable named it_companies and assign initial values Facebook, Google, Microsoft, Apple, IBM, Oracle and Amazon.\n", + "7. Print the list using _print()_\n", + "8. Print the number of companies in the list\n", + "9. Print the first, middle and last company\n", + "10. Print the list after modifying one of the companies\n", + "11. Add an IT company to it_companies\n", + "12. Insert an IT company in the middle of the companies list\n", + "13. Change one of the it_companies names to uppercase (IBM excluded!)\n", + "14. Join the it_companies with a string '#;  '\n", + "15. Check if a certain company exists in the it_companies list.\n", + "16. Sort the list using sort() method\n", + "17. Reverse the list in descending order using reverse() method\n", + "18. Slice out the first 3 companies from the list\n", + "19. Slice out the last 3 companies from the list\n", + "20. Slice out the middle IT company or companies from the list\n", + "21. Remove the first IT company from the list\n", + "22. Remove the middle IT company or companies from the list\n", + "23. Remove the last IT company from the list\n", + "24. Remove all IT companies from the list\n", + "25. Destroy the IT companies list\n", + "26. Join the following lists:\n", + "\n", + " ```py\n", + " front_end = ['HTML', 'CSS', 'JS', 'React', 'Redux']\n", + " back_end = ['Node','Express', 'MongoDB']\n", + " ```\n", + "\n", + "27. After joining the lists in question 26. Copy the joined list and assign it to a variable full_stack, then insert Python and SQL after Redux.\n", + "\n", + "### Exercises: Level 2\n", + "\n", + "1. The following is a list of 10 students ages:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "96128a41", + "metadata": {}, + "outputs": [], + "source": [ + "ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24]" + ] + }, + { + "cell_type": "markdown", + "id": "1e11f8e0", + "metadata": {}, + "source": [ + "- Sort the list and find the min and max age\n", + "- Add the min age and the max age again to the list\n", + "- Find the median age (one middle item or two middle items divided by two)\n", + "- Find the average age (sum of all items divided by their number )\n", + "- Find the range of the ages (max minus min)\n", + "- Compare the value of (min - average) and (max - average), use _abs()_ method\n", + "\n", + "1. Find the middle country(ies) in the [countries list](https://github.com/Asabeneh/30-Days-Of-Python/tree/master/data/countries.py)\n", + "1. Divide the countries list into two equal lists if it is even if not one more country for the first half.\n", + "1. ['China', 'Russia', 'USA', 'Finland', 'Sweden', 'Norway', 'Denmark']. Unpack the first three countries and the rest as scandic countries.\n", + "\n", + "🎉 CONGRATULATIONS ! 🎉\n", + "\n", + "[<< Day 4](../04_Day_Strings/04_strings.md) | [Day 6 >>](../06_Day_Tuples/06_tuples.md)" + ] + } + ], + "metadata": { + "jupytext": { + "cell_metadata_filter": "-all", + "main_language": "sh", + "notebook_metadata_filter": "-all" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/07_Day_Sets/007_sets.ipynb b/07_Day_Sets/007_sets.ipynb new file mode 100644 index 000000000..b0d43d4b4 --- /dev/null +++ b/07_Day_Sets/007_sets.ipynb @@ -0,0 +1,452 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "2fcdb8ff", + "metadata": {}, + "source": [ + "
\n", + "

30 Days Of Python: Day 7 - Sets

\n", + " \n", + " \n", + " \n", + " \n", + " \"Twitter\n", + " \n", + "\n", + "Author:\n", + "Asabeneh Yetayeh
\n", + " Second Edition: July, 2021\n", + "
\n", + "\n", + "
\n", + "\n", + "[<< Day 6](../06_Day_Tuples/06_tuples.md) | [Day 8 >>](../08_Day_Dictionaries/08_dictionaries.md)\n", + "\n", + "![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png)\n", + "\n", + "- [📘 Day 7](#-day-7)\n", + " - [Sets](#sets)\n", + " - [Creating a Set](#creating-a-set)\n", + " - [Getting Set's Length](#getting-sets-length)\n", + " - [Accessing Items in a Set](#accessing-items-in-a-set)\n", + " - [Checking an Item](#checking-an-item)\n", + " - [Adding Items to a Set](#adding-items-to-a-set)\n", + " - [Removing Items from a Set](#removing-items-from-a-set)\n", + " - [Clearing Items in a Set](#clearing-items-in-a-set)\n", + " - [Deleting a Set](#deleting-a-set)\n", + " - [Converting List to Set](#converting-list-to-set)\n", + " - [Joining Sets](#joining-sets)\n", + " - [Finding Intersection Items](#finding-intersection-items)\n", + " - [Checking Subset and Super Set](#checking-subset-and-super-set)\n", + " - [Checking the Difference Between Two Sets](#checking-the-difference-between-two-sets)\n", + " - [Finding Symmetric Difference Between Two Sets](#finding-symmetric-difference-between-two-sets)\n", + " - [Joining Sets](#joining-sets-1)\n", + " - [💻 Exercises: Day 7](#-exercises-day-7)\n", + " - [Exercises: Level 1](#exercises-level-1)\n", + " - [Exercises: Level 2](#exercises-level-2)\n", + " - [Exercises: Level 3](#exercises-level-3)\n", + "\n", + "# 📘 Day 7\n", + "\n", + "## Sets\n", + "\n", + "Set is a collection of items. Let me take you back to your elementary or high school Mathematics lesson. The Mathematics definition of a set can be applied also in Python. Set is a collection of unordered and un-indexed distinct elements. In Python set is used to store unique items, and it is possible to find the _union_, _intersection_, _difference_, _symmetric difference_, _subset_, _super set_ and _disjoint set_ among sets.\n", + "\n", + "### Creating a Set\n", + "\n", + "We use the _set()_ built-in function.\n", + "\n", + "- Creating an empty set\n", + "\n", + "```py\n", + "# syntax\n", + "st = set()\n", + "```\n", + "\n", + "- Creating a set with initial items\n", + "\n", + "```py\n", + "# syntax\n", + "st = {'item1', 'item2', 'item3', 'item4'}\n", + "```\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "# syntax\n", + "fruits = {'banana', 'orange', 'mango', 'lemon'}\n", + "```\n", + "\n", + "### Getting Set's Length\n", + "\n", + "We use **len()** method to find the length of a set.\n", + "\n", + "```py\n", + "# syntax\n", + "st = {'item1', 'item2', 'item3', 'item4'}\n", + "len(st)\n", + "```\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "fruits = {'banana', 'orange', 'mango', 'lemon'}\n", + "len(fruits)\n", + "```\n", + "\n", + "### Accessing Items in a Set\n", + "\n", + "We use loops to access items. We will see this in loop section\n", + "\n", + "### Checking an Item\n", + "\n", + "To check if an item exist in a list we use _in_ membership operator.\n", + "\n", + "```py\n", + "# syntax\n", + "st = {'item1', 'item2', 'item3', 'item4'}\n", + "print(\"Does set st contain item3? \", 'item3' in st) # Does set st contain item3? True\n", + "```\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "fruits = {'banana', 'orange', 'mango', 'lemon'}\n", + "print('mango' in fruits ) # True\n", + "```\n", + "\n", + "### Adding Items to a Set\n", + "\n", + "Once a set is created we cannot change any items and we can also add additional items.\n", + "\n", + "- Add one item using _add()_\n", + "\n", + "```py\n", + "# syntax\n", + "st = {'item1', 'item2', 'item3', 'item4'}\n", + "st.add('item5')\n", + "```\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "fruits = {'banana', 'orange', 'mango', 'lemon'}\n", + "fruits.add('lime')\n", + "```\n", + "\n", + "- Add multiple items using _update()_\n", + " The _update()_ allows to add multiple items to a set. The _update()_ takes a list argument.\n", + "\n", + "```py\n", + "# syntax\n", + "st = {'item1', 'item2', 'item3', 'item4'}\n", + "st.update(['item5','item6','item7'])\n", + "```\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "fruits = {'banana', 'orange', 'mango', 'lemon'}\n", + "vegetables = ('tomato', 'potato', 'cabbage','onion', 'carrot')\n", + "fruits.update(vegetables)\n", + "```\n", + "\n", + "### Removing Items from a Set\n", + "\n", + "We can remove an item from a set using _remove()_ method. If the item is not found _remove()_ method will raise errors, so it is good to check if the item exist in the given set. However, _discard()_ method doesn't raise any errors.\n", + "\n", + "```py\n", + "# syntax\n", + "st = {'item1', 'item2', 'item3', 'item4'}\n", + "st.remove('item2')\n", + "```\n", + "\n", + "The pop() methods remove a random item from a list and it returns the removed item.\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "fruits = {'banana', 'orange', 'mango', 'lemon'}\n", + "fruits.pop() # removes a random item from the set\n", + "\n", + "```\n", + "\n", + "If we are interested in the removed item.\n", + "\n", + "```py\n", + "fruits = {'banana', 'orange', 'mango', 'lemon'}\n", + "removed_item = fruits.pop() \n", + "```\n", + "\n", + "### Clearing Items in a Set\n", + "\n", + "If we want to clear or empty the set we use _clear_ method.\n", + "\n", + "```py\n", + "# syntax\n", + "st = {'item1', 'item2', 'item3', 'item4'}\n", + "st.clear()\n", + "```\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "fruits = {'banana', 'orange', 'mango', 'lemon'}\n", + "fruits.clear()\n", + "print(fruits) # set()\n", + "```\n", + "\n", + "### Deleting a Set\n", + "\n", + "If we want to delete the set itself we use _del_ operator.\n", + "\n", + "```py\n", + "# syntax\n", + "st = {'item1', 'item2', 'item3', 'item4'}\n", + "del st\n", + "```\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "fruits = {'banana', 'orange', 'mango', 'lemon'}\n", + "del fruits\n", + "```\n", + "\n", + "### Converting List to Set\n", + "\n", + "We can convert list to set and set to list. Converting list to set removes duplicates and only unique items will be reserved.\n", + "\n", + "```py\n", + "# syntax\n", + "lst = ['item1', 'item2', 'item3', 'item4', 'item1']\n", + "st = set(lst) # {'item2', 'item4', 'item1', 'item3'} - the order is random, because sets in general are unordered\n", + "```\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "fruits = ['banana', 'orange', 'mango', 'lemon','orange', 'banana']\n", + "fruits = set(fruits) # {'mango', 'lemon', 'banana', 'orange'}\n", + "```\n", + "\n", + "### Joining Sets\n", + "\n", + "We can join two sets using the _union()_ or _update()_ method.\n", + "\n", + "- Union\n", + " This method returns a new set\n", + "\n", + "```py\n", + "# syntax\n", + "st1 = {'item1', 'item2', 'item3', 'item4'}\n", + "st2 = {'item5', 'item6', 'item7', 'item8'}\n", + "st3 = st1.union(st2)\n", + "```\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "fruits = {'banana', 'orange', 'mango', 'lemon'}\n", + "vegetables = {'tomato', 'potato', 'cabbage','onion', 'carrot'}\n", + "print(fruits.union(vegetables)) # {'lemon', 'carrot', 'tomato', 'banana', 'mango', 'orange', 'cabbage', 'potato', 'onion'}\n", + "```\n", + "\n", + "- Update\n", + " This method inserts a set into a given set\n", + "\n", + "```py\n", + "# syntax\n", + "st1 = {'item1', 'item2', 'item3', 'item4'}\n", + "st2 = {'item5', 'item6', 'item7', 'item8'}\n", + "st1.update(st2) # st2 contents are added to st1\n", + "```\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "fruits = {'banana', 'orange', 'mango', 'lemon'}\n", + "vegetables = {'tomato', 'potato', 'cabbage','onion', 'carrot'}\n", + "fruits.update(vegetables)\n", + "print(fruits) # {'lemon', 'carrot', 'tomato', 'banana', 'mango', 'orange', 'cabbage', 'potato', 'onion'}\n", + "```\n", + "\n", + "### Finding Intersection Items\n", + "\n", + "Intersection returns a set of items which are in both the sets. See the example\n", + "\n", + "```py\n", + "# syntax\n", + "st1 = {'item1', 'item2', 'item3', 'item4'}\n", + "st2 = {'item3', 'item2'}\n", + "st1.intersection(st2) # {'item3', 'item2'}\n", + "```\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "whole_numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n", + "even_numbers = {0, 2, 4, 6, 8, 10}\n", + "whole_numbers.intersection(even_numbers) # {0, 2, 4, 6, 8, 10}\n", + "\n", + "python = {'p', 'y', 't', 'h', 'o','n'}\n", + "dragon = {'d', 'r', 'a', 'g', 'o','n'}\n", + "python.intersection(dragon) # {'o', 'n'}\n", + "```\n", + "\n", + "### Checking Subset and Super Set\n", + "\n", + "A set can be a subset or super set of other sets:\n", + "\n", + "- Subset: _issubset()_\n", + "- Super set: _issuperset_\n", + "\n", + "```py\n", + "# syntax\n", + "st1 = {'item1', 'item2', 'item3', 'item4'}\n", + "st2 = {'item2', 'item3'}\n", + "st2.issubset(st1) # True\n", + "st1.issuperset(st2) # True\n", + "```\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "whole_numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n", + "even_numbers = {0, 2, 4, 6, 8, 10}\n", + "whole_numbers.issubset(even_numbers) # False, because it is a super set\n", + "whole_numbers.issuperset(even_numbers) # True\n", + "\n", + "python = {'p', 'y', 't', 'h', 'o','n'}\n", + "dragon = {'d', 'r', 'a', 'g', 'o','n'}\n", + "python.issubset(dragon) # False\n", + "```\n", + "\n", + "### Checking the Difference Between Two Sets\n", + "\n", + "It returns the difference between two sets.\n", + "\n", + "```py\n", + "# syntax\n", + "st1 = {'item1', 'item2', 'item3', 'item4'}\n", + "st2 = {'item2', 'item3'}\n", + "st2.difference(st1) # set()\n", + "st1.difference(st2) # {'item1', 'item4'} => st1\\st2\n", + "```\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "whole_numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n", + "even_numbers = {0, 2, 4, 6, 8, 10}\n", + "whole_numbers.difference(even_numbers) # {1, 3, 5, 7, 9}\n", + "\n", + "python = {'p', 'y', 't', 'o','n'}\n", + "dragon = {'d', 'r', 'a', 'g', 'o','n'}\n", + "python.difference(dragon) # {'p', 'y', 't'} - the result is unordered (characteristic of sets)\n", + "dragon.difference(python) # {'d', 'r', 'a', 'g'}\n", + "```\n", + "\n", + "### Finding Symmetric Difference Between Two Sets\n", + "\n", + "It returns the symmetric difference between two sets. It means that it returns a set that contains all items from both sets, except items that are present in both sets, mathematically: (A\\B) ∪ (B\\A)\n", + "\n", + "```py\n", + "# syntax\n", + "st1 = {'item1', 'item2', 'item3', 'item4'}\n", + "st2 = {'item2', 'item3'}\n", + "# it means (A\\B)∪(B\\A)\n", + "st2.symmetric_difference(st1) # {'item1', 'item4'}\n", + "```\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "whole_numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n", + "some_numbers = {1, 2, 3, 4, 5}\n", + "whole_numbers.symmetric_difference(some_numbers) # {0, 6, 7, 8, 9, 10}\n", + "\n", + "python = {'p', 'y', 't', 'h', 'o','n'}\n", + "dragon = {'d', 'r', 'a', 'g', 'o','n'}\n", + "python.symmetric_difference(dragon) # {'r', 't', 'p', 'y', 'g', 'a', 'd', 'h'}\n", + "```\n", + "\n", + "### Joining Sets\n", + "\n", + "If two sets do not have a common item or items we call them disjoint sets. We can check if two sets are joint or disjoint using _isdisjoint()_ method.\n", + "\n", + "```py\n", + "# syntax\n", + "st1 = {'item1', 'item2', 'item3', 'item4'}\n", + "st2 = {'item2', 'item3'}\n", + "st2.isdisjoint(st1) # False\n", + "```\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "even_numbers = {0, 2, 4 ,6, 8}\n", + "odd_numbers = {1, 3, 5, 7, 9}\n", + "even_numbers.isdisjoint(odd_numbers) # True, because no common item\n", + "\n", + "python = {'p', 'y', 't', 'h', 'o','n'}\n", + "dragon = {'d', 'r', 'a', 'g', 'o','n'}\n", + "python.isdisjoint(dragon) # False, there are common items {'o', 'n'}\n", + "```\n", + "\n", + "🌕 You are a rising star . You have just completed day 7 challenges and you are 7 steps ahead in to your way to greatness. Now do some exercises for your brain and muscles.\n", + "\n", + "## 💻 Exercises: Day 7\n", + "\n", + "```py\n", + "# sets\n", + "it_companies = {'Facebook', 'Google', 'Microsoft', 'Apple', 'IBM', 'Oracle', 'Amazon'}\n", + "A = {19, 22, 24, 20, 25, 26}\n", + "B = {19, 22, 20, 25, 26, 24, 28, 27}\n", + "age = [22, 19, 24, 25, 26, 24, 25, 24]\n", + "```\n", + "\n", + "### Exercises: Level 1\n", + "\n", + "1. Find the length of the set it_companies\n", + "2. Add 'Twitter' to it_companies\n", + "3. Insert multiple IT companies at once to the set it_companies\n", + "4. Remove one of the companies from the set it_companies\n", + "5. What is the difference between remove and discard\n", + "\n", + "### Exercises: Level 2\n", + "\n", + "1. Join A and B\n", + "1. Find A intersection B\n", + "1. Is A subset of B\n", + "1. Are A and B disjoint sets\n", + "1. Join A with B and B with A\n", + "1. What is the symmetric difference between A and B\n", + "1. Delete the sets completely\n", + "\n", + "### Exercises: Level 3\n", + "\n", + "1. Convert the ages to a set and compare the length of the list and the set, which one is bigger?\n", + "1. Explain the difference between the following data types: string, list, tuple and set\n", + "2. _I am a teacher and I love to inspire and teach people._ How many unique words have been used in the sentence? Use the split methods and set to get the unique words.\n", + "\n", + "🎉 CONGRATULATIONS ! 🎉\n", + "\n", + "[<< Day 6](../06_Day_Tuples/06_tuples.md) | [Day 8 >>](../08_Day_Dictionaries/08_dictionaries.md)" + ] + } + ], + "metadata": { + "jupytext": { + "cell_metadata_filter": "-all", + "main_language": "python", + "notebook_metadata_filter": "-all" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/08_Day_Dictionaries/008_dictionaries.ipynb b/08_Day_Dictionaries/008_dictionaries.ipynb new file mode 100644 index 000000000..c31d18f43 --- /dev/null +++ b/08_Day_Dictionaries/008_dictionaries.ipynb @@ -0,0 +1,365 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "ed46b100", + "metadata": {}, + "source": [ + "
\n", + "

30 Days Of Python: Day 8 - Dictionaries

\n", + " \n", + " \n", + " \n", + " \n", + " \"Twitter\n", + " \n", + "\n", + "Author:\n", + "Asabeneh Yetayeh
\n", + " Second Edition: July, 2021\n", + "
\n", + "\n", + "
\n", + "\n", + "[<< Day 7 ](../07_Day_Sets/07_sets.md) | [Day 9 >>](../09_Day_Conditionals/09_conditionals.md)\n", + "\n", + "![30DaysOfPython](../images/30DaysOfPython_banner3@2x.png)\n", + "\n", + "- [📘 Day 8](#-day-8)\n", + " - [Dictionaries](#dictionaries)\n", + " - [Creating a Dictionary](#creating-a-dictionary)\n", + " - [Dictionary Length](#dictionary-length)\n", + " - [Accessing Dictionary Items](#accessing-dictionary-items)\n", + " - [Adding Items to a Dictionary](#adding-items-to-a-dictionary)\n", + " - [Modifying Items in a Dictionary](#modifying-items-in-a-dictionary)\n", + " - [Checking Keys in a Dictionary](#checking-keys-in-a-dictionary)\n", + " - [Removing Key and Value Pairs from a Dictionary](#removing-key-and-value-pairs-from-a-dictionary)\n", + " - [Changing Dictionary to a List of Items](#changing-dictionary-to-a-list-of-items)\n", + " - [Clearing a Dictionary](#clearing-a-dictionary)\n", + " - [Deleting a Dictionary](#deleting-a-dictionary)\n", + " - [Copy a Dictionary](#copy-a-dictionary)\n", + " - [Getting Dictionary Keys as a List](#getting-dictionary-keys-as-a-list)\n", + " - [Getting Dictionary Values as a List](#getting-dictionary-values-as-a-list)\n", + " - [💻 Exercises: Day 8](#-exercises-day-8)\n", + "\n", + "# 📘 Day 8\n", + "\n", + "## Dictionaries\n", + "\n", + "A dictionary is a collection of unordered, modifiable(mutable) paired (key: value) data type.\n", + "\n", + "### Creating a Dictionary\n", + "\n", + "To create a dictionary we use curly brackets, {} or the *dict()* built-in function.\n", + "\n", + "```py\n", + "# syntax\n", + "empty_dict = {}\n", + "# Dictionary with data values\n", + "dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}\n", + "```\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "person = {\n", + " 'first_name':'Asabeneh',\n", + " 'last_name':'Yetayeh',\n", + " 'age':250,\n", + " 'country':'Finland',\n", + " 'is_marred':True,\n", + " 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],\n", + " 'address':{\n", + " 'street':'Space street',\n", + " 'zipcode':'02210'\n", + " }\n", + " }\n", + "```\n", + "\n", + "The dictionary above shows that a value could be any data types:string, boolean, list, tuple, set or a dictionary.\n", + "\n", + "### Dictionary Length\n", + "\n", + "It checks the number of 'key: value' pairs in the dictionary.\n", + "\n", + "```py\n", + "# syntax\n", + "dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}\n", + "print(len(dct)) # 4\n", + "```\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "person = {\n", + " 'first_name':'Asabeneh',\n", + " 'last_name':'Yetayeh',\n", + " 'age':250,\n", + " 'country':'Finland',\n", + " 'is_married':True,\n", + " 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],\n", + " 'address':{\n", + " 'street':'Space street',\n", + " 'zipcode':'02210'\n", + " }\n", + " }\n", + "print(len(person)) # 7\n", + "\n", + "```\n", + "\n", + "### Accessing Dictionary Items\n", + "\n", + "We can access Dictionary items by referring to its key name.\n", + "\n", + "```py\n", + "# syntax\n", + "dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}\n", + "print(dct['key1']) # value1\n", + "print(dct['key4']) # value4\n", + "```\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "person = {\n", + " 'first_name':'Asabeneh',\n", + " 'last_name':'Yetayeh',\n", + " 'age':250,\n", + " 'country':'Finland',\n", + " 'is_marred':True,\n", + " 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],\n", + " 'address':{\n", + " 'street':'Space street',\n", + " 'zipcode':'02210'\n", + " }\n", + " }\n", + "print(person['first_name']) # Asabeneh\n", + "print(person['country']) # Finland\n", + "print(person['skills']) # ['JavaScript', 'React', 'Node', 'MongoDB', 'Python']\n", + "print(person['skills'][0]) # JavaScript\n", + "print(person['address']['street']) # Space street\n", + "print(person['city']) # Error\n", + "```\n", + "\n", + "Accessing an item by key name raises an error if the key does not exist. To avoid this error first we have to check if a key exist or we can use the _get_ method. The get method returns None, which is a NoneType object data type, if the key does not exist.\n", + "```py\n", + "person = {\n", + " 'first_name':'Asabeneh',\n", + " 'last_name':'Yetayeh',\n", + " 'age':250,\n", + " 'country':'Finland',\n", + " 'is_marred':True,\n", + " 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],\n", + " 'address':{\n", + " 'street':'Space street',\n", + " 'zipcode':'02210'\n", + " }\n", + " }\n", + "print(person.get('first_name')) # Asabeneh\n", + "print(person.get('country')) # Finland\n", + "print(person.get('skills')) #['HTML','CSS','JavaScript', 'React', 'Node', 'MongoDB', 'Python']\n", + "print(person.get('city')) # None\n", + "```\n", + "\n", + "### Adding Items to a Dictionary\n", + "\n", + "We can add new key and value pairs to a dictionary\n", + "\n", + "```py\n", + "# syntax\n", + "dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}\n", + "dct['key5'] = 'value5'\n", + "```\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "person = {\n", + " 'first_name':'Asabeneh',\n", + " 'last_name':'Yetayeh',\n", + " 'age':250,\n", + " 'country':'Finland',\n", + " 'is_marred':True,\n", + " 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],\n", + " 'address':{\n", + " 'street':'Space street',\n", + " 'zipcode':'02210'\n", + " }\n", + "}\n", + "person['job_title'] = 'Instructor'\n", + "person['skills'].append('HTML')\n", + "print(person)\n", + "```\n", + "\n", + "### Modifying Items in a Dictionary\n", + "\n", + "We can modify items in a dictionary\n", + "\n", + "```py\n", + "# syntax\n", + "dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}\n", + "dct['key1'] = 'value-one'\n", + "```\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "person = {\n", + " 'first_name':'Asabeneh',\n", + " 'last_name':'Yetayeh',\n", + " 'age':250,\n", + " 'country':'Finland',\n", + " 'is_marred':True,\n", + " 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],\n", + " 'address':{\n", + " 'street':'Space street',\n", + " 'zipcode':'02210'\n", + " }\n", + " }\n", + "person['first_name'] = 'Eyob'\n", + "person['age'] = 252\n", + "```\n", + "\n", + "### Checking Keys in a Dictionary\n", + "\n", + "We use the _in_ operator to check if a key exist in a dictionary\n", + "\n", + "```py\n", + "# syntax\n", + "dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}\n", + "print('key2' in dct) # True\n", + "print('key5' in dct) # False\n", + "```\n", + "\n", + "### Removing Key and Value Pairs from a Dictionary\n", + "\n", + "- _pop(key)_: removes the item with the specified key name:\n", + "- _popitem()_: removes the last item\n", + "- _del_: removes an item with specified key name\n", + "\n", + "```py\n", + "# syntax\n", + "dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}\n", + "dct.pop('key1') # removes key1 item\n", + "dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}\n", + "dct.popitem() # removes the last item\n", + "del dct['key2'] # removes key2 item\n", + "```\n", + "\n", + "**Example:**\n", + "\n", + "```py\n", + "person = {\n", + " 'first_name':'Asabeneh',\n", + " 'last_name':'Yetayeh',\n", + " 'age':250,\n", + " 'country':'Finland',\n", + " 'is_marred':True,\n", + " 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],\n", + " 'address':{\n", + " 'street':'Space street',\n", + " 'zipcode':'02210'\n", + " }\n", + " }\n", + "person.pop('first_name') # Removes the firstname item\n", + "person.popitem() # Removes the address item\n", + "del person['is_married'] # Removes the is_married item\n", + "```\n", + "\n", + "### Changing Dictionary to a List of Items\n", + "\n", + "The _items()_ method changes dictionary to a list of tuples.\n", + "\n", + "```py\n", + "# syntax\n", + "dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}\n", + "print(dct.items()) # dict_items([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3'), ('key4', 'value4')])\n", + "```\n", + "\n", + "### Clearing a Dictionary\n", + "\n", + "If we don't want the items in a dictionary we can clear them using _clear()_ method\n", + "\n", + "```py\n", + "# syntax\n", + "dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}\n", + "print(dct.clear()) # None\n", + "```\n", + "\n", + "### Deleting a Dictionary\n", + "\n", + "If we do not use the dictionary we can delete it completely\n", + "\n", + "```py\n", + "# syntax\n", + "dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}\n", + "del dct\n", + "```\n", + "\n", + "### Copy a Dictionary\n", + "\n", + "We can copy a dictionary using a _copy()_ method. Using copy we can avoid mutation of the original dictionary.\n", + "\n", + "```py\n", + "# syntax\n", + "dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}\n", + "dct_copy = dct.copy() # {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}\n", + "```\n", + "\n", + "### Getting Dictionary Keys as a List\n", + "\n", + "The _keys()_ method gives us all the keys of a a dictionary as a list.\n", + "\n", + "```py\n", + "# syntax\n", + "dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}\n", + "keys = dct.keys()\n", + "print(keys) # dict_keys(['key1', 'key2', 'key3', 'key4'])\n", + "```\n", + "\n", + "### Getting Dictionary Values as a List\n", + "\n", + "The _values_ method gives us all the values of a a dictionary as a list.\n", + "\n", + "```py\n", + "# syntax\n", + "dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}\n", + "values = dct.values()\n", + "print(values) # dict_values(['value1', 'value2', 'value3', 'value4'])\n", + "```\n", + "\n", + "🌕 You are astonishing. Now, you are super charged with the power of dictionaries. You have just completed day 8 challenges and you are 8 steps a head in to your way to greatness. Now do some exercises for your brain and muscles.\n", + "\n", + "## 💻 Exercises: Day 8\n", + "\n", + "1. Create an empty dictionary called dog\n", + "2. Add name, color, breed, legs, age to the dog dictionary\n", + "3. Create a student dictionary and add first_name, last_name, gender, age, marital status, skills, country, city and address as keys for the dictionary\n", + "4. Get the length of the student dictionary\n", + "5. Get the value of skills and check the data type, it should be a list\n", + "6. Modify the skills values by adding one or two skills\n", + "7. Get the dictionary keys as a list\n", + "8. Get the dictionary values as a list\n", + "9. Change the dictionary to a list of tuples using _items()_ method\n", + "10. Delete one of the items in the dictionary\n", + "11. Delete one of the dictionaries\n", + "\n", + "🎉 CONGRATULATIONS ! 🎉\n", + "\n", + "[<< Day 7 ](../07_Day_Sets/07_sets.md) | [Day 9 >>](../09_Day_Conditionals/09_conditionals.md)" + ] + } + ], + "metadata": { + "jupytext": { + "cell_metadata_filter": "-all", + "main_language": "python", + "notebook_metadata_filter": "-all" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}