Skip to content

Instantly share code, notes, and snippets.

@barangerbenjamin
Created April 14, 2021 16:52
Show Gist options
  • Save barangerbenjamin/e1a1e2c25cbc8f7cde15eea3a41c4add to your computer and use it in GitHub Desktop.
Save barangerbenjamin/e1a1e2c25cbc8f7cde15eea3a41c4add to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Reboot - Python Basics\n",
"\n",
"This is a set of small independent assignments to recap the concepts of the day.\n",
"\n",
"## 1. Variables\n",
"\n",
"Create a `country` variable and assign your favorite country to it. Print it"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"country = 'Spain'"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Spain\n"
]
}
],
"source": [
"print(country)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create an `animal` variable and assign your favorite animal to it. Print it"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"animal = 'Dog'"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Dog\n"
]
}
],
"source": [
"print(animal)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create an `animal_count` variable with any positive integer in it. Print it"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"animal_count = 2"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2\n"
]
}
],
"source": [
"print(animal_count)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Print out a string using all your variables that follows this format:\n",
"`\"I just ordered 200 monkeys from Denmark\"`\n",
"\n",
"**Hint**: use interpolation"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"I just ordered 2 dogs from Spain\n"
]
}
],
"source": [
"print(f\"I just ordered {animal_count} {animal.lower() + 's' if animal_count > 1 else animal.lower()} from {country}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## 2. Data Types\n",
"Now it's time to talk about data types. The first question to ask yourself before starting any coding task, is to determine which data types you're working with.\n",
"\n",
"Run the following cells and pay attention to the variables initialized:"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Variables are now defined!\n"
]
}
],
"source": [
"pi = 3.14\n",
"food = 'pizza'\n",
"colors = ['red', 'blue', 'yellow']\n",
"print(\"Variables are now defined!\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Look at the following code. Replace the `?` with the correct data type each time (`str`, `float`, `list`). \n",
"\n",
"The cell should display `True` when you put in the right datatypes."
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"type(pi) == float \\\n",
"and type(food) == str \\\n",
"and type(colors) == list"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's try to work with other data types. This time there's no hint."
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Variables are now defined!\n"
]
}
],
"source": [
"user_profile = {'email': 'buffy@gmail.com', 'age': 19, 'password': 'hunter2', 'profession': 'Vampire Slayer' }\n",
"shapes = ('square', 'round', 'hexagonic')\n",
"age = 25\n",
"age_valid = (age < 18)\n",
"print(\"Variables are now defined!\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's repeat the excercise from before with the new variables. Once again, the cell should display `True` when you're done."
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"type(shapes) == tuple \\\n",
"and type(user_profile) == dict \\\n",
"and type(age_valid) == bool"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"\n",
"## 3. Functions\n",
"\n",
"Create a fuction `credit_card_industry` which takes one parameter (a `str` storing a credit card number like `\"4242 4242 4242 4242\"` for instance) and **return** one of the following industries:\n",
"\n",
"- Airline - 1\n",
"- Visa - 4\n",
"- Mastercard - 5\n",
"- Other\n",
"\n",
"This [article](https://www.thebalance.com/what-do-the-numbers-on-your-credit-card-mean-4588401) will prove handy if you don't know how to determine this from the number."
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [],
"source": [
"def credit_card_industry(credit_card):\n",
" # retrieve the first number of the card\n",
" first_number = int(credit_card[0])\n",
" if first_number == 1:\n",
" model = 'Airline'\n",
" elif first_number == 4:\n",
" model = 'Visa'\n",
" elif first_number == 5:\n",
" model = 'Mastercard'\n",
" else:\n",
" model = 'Other'\n",
" return model"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Call this function and **print** the result for the following card numbers:\n",
"\n",
"- `\"4539 0132 4843 4768\"`\n",
"- `\"5131 9376 6800 4058\"`\n",
"- `\"3762 8789 1971 1060\"`\n",
"- `\"1002 0494 8191 1719\"`"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Visa\n"
]
}
],
"source": [
"print(credit_card_industry(\"4539 0132 4843 4768\"))"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Mastercard\n"
]
}
],
"source": [
"print(credit_card_industry(\"5131 9376 6800 4058\"))"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Other\n"
]
}
],
"source": [
"print(credit_card_industry(\"3762 8789 1971 1060\"))"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Airline\n"
]
}
],
"source": [
"print(credit_card_industry(\"1002 0494 8191 1719\"))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## 4. Lists\n",
"\n",
"Create a `genres` variable with a list of 3 different movie genres as strings. Print the list."
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [],
"source": [
"genres = ['comedy', 'drama', 'action']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Add another genre to the list. Print the whole list."
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['comedy', 'drama', 'action', 'romance']\n"
]
}
],
"source": [
"genres.append('romance')\n",
"print(genres)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Change the name of the second genre on the list. Print the whole list"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['comedy', 'Drama', 'action', 'romance']\n"
]
}
],
"source": [
"genres[1] = 'Drama'\n",
"print(genres)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Print each genre (sorted) to the terminal following this format (use a for loop with enumerate):\n",
"\n",
"```\n",
"1 - Action\n",
"2 - Comedy\n",
"3 - Drama\n",
"4 - Thriller\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1 - Comedy\n",
"2 - Drama\n",
"3 - Action\n",
"4 - Romance\n"
]
}
],
"source": [
"for index, genre in enumerate(genres):\n",
" print(f\"{index + 1} - {genre.capitalize()}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## 5. Dictionaries\n",
"\n",
"Create a `movie` variable with a dictionary containing information about any movie. It should contain the keys `year` and `title` with appropriate values. You can get some inspiration on [IMDB](https://www.imdb.com/search/title/?count=100&groups=top_1000&sort=user_rating)"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [],
"source": [
"movie = {\n",
" 'year': 1994,\n",
" 'title': \"The Shawshank Redemption\"\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Add a `director` key to the dictonary with the appropriate value. Print the `movie` dictionary"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [],
"source": [
"movie['director'] = 'Frank Darabont'"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'year': 1994,\n",
" 'title': 'The Shawshank Redemption',\n",
" 'director': 'Frank Darabont'}"
]
},
"execution_count": 43,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"movie"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create a `movies` variable and initialize it with an empty list."
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [],
"source": [
"movies = []"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Add your `movie` to the list along with two more movies, with the same keys as the first one. Then print the entire list"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [],
"source": [
"movies.append(movie)\n",
"movies.append({'year': 1972,'title': \"The Godfather\", 'director': 'Francis Ford Coppola'})\n",
"movies.append({'year': 2008,'title': \"The Dark Knight\", 'director': 'Christopher Nolan'})"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[{'year': 1994,\n",
" 'title': 'The Shawshank Redemption',\n",
" 'director': 'Frank Darabont'},\n",
" {'year': 1972, 'title': 'The Godfather', 'director': 'Francis Ford Coppola'},\n",
" {'year': 2008, 'title': 'The Dark Knight', 'director': 'Christopher Nolan'}]"
]
},
"execution_count": 47,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"movies"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Finally, print the `movies` list line by line in the terminal in the following format (using a `for` loop):\n",
"```\n",
"Terminator by James Cameron was released in 1984\n",
"Godfather by Francis Ford Coppolla was released in 1972\n",
"The Matrix by The Wachowski Brothers was released in 1999\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The Shawshank Redemption by Frank Darabont was released in 1994\n",
"The Godfather by Francis Ford Coppola was released in 1972\n",
"The Dark Knight by Christopher Nolan was released in 2008\n"
]
}
],
"source": [
"for movie in movies:\n",
" print(f\"{movie['title']} by {movie['director']} was released in {movie['year']}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"## 6. Dictionaries + Lists\n",
"\n",
"Often when we're dealing with data, we have to find our way around a big dictionary. This can be a bit intimidating at first. But have no fear, once you get the hang of it, it's quite comfortable to navigate. When we're dealing with bigger dictionaries, it's important to take the time and read through it, knowing what kind of data types are stored and what structure it has. \n",
"\n",
"It's often a small subset of the information we're interested in looking at, so we need to know how to precisely access it. Start by running the cell below:"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"movie is defined!\n"
]
}
],
"source": [
"movie = {\n",
" 'title': { 'en': 'The Dark Knight', 'fr': 'Le Chevalier Noir' },\n",
" 'year': 2008,\n",
" 'director': 'Christopher Nolan',\n",
" 'rating': 'PG-13',\n",
" 'plot': {\n",
" 'en': 'The Batman is out for blood',\n",
" 'fr': 'Batman est de retour, plus vénère que jamais'\n",
" },\n",
" 'box office USD': {'USA': 535_234_033, 'rest_of_world': 469_700_000 },\n",
" 'actors': {\n",
" 'lead': ['Christian Bale', 'Heath Ledger'],\n",
" 'support': ['Aaron Eckhardt', 'Morgan Freeman', 'Gary Oldman', 'Maggie Gyllenhaal' ]\n",
" }\n",
"}\n",
"print(\"movie is defined!\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Try to guess the answer to the questions without writing any code. Then try the code out for yourself to test your theory.\n",
"\n",
"What does `movie['title']['fr']` return? "
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Le Chevalier Noir'"
]
},
"execution_count": 52,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"movie['title']['fr']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What does `movie['title']['es']` return?"
]
},
{
"cell_type": "code",
"execution_count": 53,
"metadata": {},
"outputs": [
{
"ename": "KeyError",
"evalue": "'es'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-53-29c18c2c258a>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mmovie\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'title'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'es'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mKeyError\u001b[0m: 'es'"
]
}
],
"source": [
"movie['title']['es']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What does `movie['actors']['support'][2]` return?"
]
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Gary Oldman'"
]
},
"execution_count": 58,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"movie['actors']['support'][2]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Optional \n",
"\n",
"Find a way to extract one list containing all the actors from the movie."
]
},
{
"cell_type": "code",
"execution_count": 59,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['Christian Bale',\n",
" 'Heath Ledger',\n",
" 'Aaron Eckhardt',\n",
" 'Morgan Freeman',\n",
" 'Gary Oldman',\n",
" 'Maggie Gyllenhaal']"
]
},
"execution_count": 59,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"movie['actors']['lead'] + movie['actors']['support']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Try to calculate the total box office of the movie from `movie`"
]
},
{
"cell_type": "code",
"execution_count": 64,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1004934033"
]
},
"execution_count": 64,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sum(movie['box office USD'].values())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Would the code above still work with the following Box Office. How would you compute the total Box Office using a `for` loop?"
]
},
{
"cell_type": "code",
"execution_count": 66,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'US': 200000000, 'EU': 85000000, 'China': 110000000}\n"
]
}
],
"source": [
"box_office = {\"US\": 200_000_000, \"EU\": 85_000_000, \"China\": 110_000_000}\n",
"print(box_office)"
]
},
{
"cell_type": "code",
"execution_count": 67,
"metadata": {},
"outputs": [],
"source": [
"total = 0\n",
"for value in box_office.values():\n",
" total = total + value\n",
" # total += value"
]
},
{
"cell_type": "code",
"execution_count": 68,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"395000000"
]
},
"execution_count": 68,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"total"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
},
"toc": {
"base_numbering": 1,
"nav_menu": {},
"number_sections": false,
"sideBar": true,
"skip_h1_title": false,
"title_cell": "Table of Contents",
"title_sidebar": "Contents",
"toc_cell": false,
"toc_position": {},
"toc_section_display": true,
"toc_window_display": false
},
"varInspector": {
"cols": {
"lenName": 16,
"lenType": 16,
"lenVar": 40
},
"kernels_config": {
"python": {
"delete_cmd_postfix": "",
"delete_cmd_prefix": "del ",
"library": "var_list.py",
"varRefreshCmd": "print(var_dic_list())"
},
"r": {
"delete_cmd_postfix": ") ",
"delete_cmd_prefix": "rm(",
"library": "var_list.r",
"varRefreshCmd": "cat(var_dic_list()) "
}
},
"types_to_exclude": [
"module",
"function",
"builtin_function_or_method",
"instance",
"_Feature"
],
"window_display": false
}
},
"nbformat": 4,
"nbformat_minor": 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment