{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Python 101 \n", "## Part II." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Install dynamic progress bar with:\n", "```bash\n", "pip install tqdm\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import random\n", "from helpers import encrypt" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "\n", "## I/O\n", "\n", "Let's have some user input:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "prompt = 'What is your name? '\n", "answer = input(prompt)\n", "print('Your name is', answer,'.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "prompt = 'What is the air-speed velocity of an unladen swallow? '\n", "answer = input(prompt)\n", "print(answer, type(answer))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(int(answer), type(int(answer)))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(float(answer), type(float(answer)))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(bool(answer), type(bool(answer)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "\n", "### About strings" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Multiline editing\n", "print('And Saint Atila raised the hand grenade up on high, saying,\\n'\n", " + '\\'Oh, Lord, bless this thy hand '\n", " 'grenade that with it thou mayest blow')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# String formatting:\n", "first_meal = 'orangutans'\n", "second_meal = 'breakfast cereals'\n", "third_meal = 'fruit bats'\n", "\n", "print('thy enemies to tiny bits, in thy mercy.\\' '\n", " 'And the Lord did grin, and\\n'\n", " 'people did feast upon the lambs, '\n", " 'and sloths, and carp, and anchovies,\\n'\n", " 'and {0}, and {1}, and {2}, and large --'.format(first_meal, second_meal, third_meal))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# F-strings\n", "grenade = 'Holy Hand Grenade of Antioch'\n", "number = 'three'\n", "\n", "print(f'And the Lord spake, saying, \"First shalt thou take out the Holy Pin. '\n", " f'Then, shalt thou count to {number}. No more. No less. '\n", " f'{number} shalt be the number thou shalt count, '\n", " f'and the number of the counting shall be {number}. '\n", " f'Four shalt thou not count, nor either count thou two, '\n", " f'excepting that thou then proceed to {number}. '\n", " f'Five is right out. Once the number {number}, being the third number, '\n", " f'be reached, then, lobbest thou thy {grenade} '\n", " f'towards thy foe, who, being naughty in My sight, shall snuff it.\"')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise: Recreate Around the World\n", "\n", "Daft Punk's Around the World is one of the most repetitive songs ever. Let's\n", "try to recreate the song's lyrics. \n", "Here is a refresher about the song: [lyrics](https://www.google.com/search?q=daft+punk+around+the+world+lyrics), [clip](https://www.youtube.com/watch?v=K0HSD_i2DvA) \n", "We already created all of the necessary building blocks for you, please use string formatting when constructing the text. Make sure to capitalize the text correctly (hint: there is a string function called `'text'.capitalize()`)!\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "around_the_world = 'around the world'\n", "lyrics = \"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Slicing" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "example_string = 'Monty Python'\n", "print(example_string)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(example_string[0])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(example_string[-1])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(example_string[6:10])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(example_string[-12:-7])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(example_string[-7:-12:-1])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(example_string[::-1])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "start = 1\n", "end = 2\n", "step = 1\n", "print(example_string[start:end:step])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(len(example_string))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print('y' in example_string)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Excercise: Decrypt the encrypted text\n", "\n", "An encryption is applied to a text. Find out a way to decrypt it using only the slicing method." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "text = 'titkositott szoveg'\n", "encrypted = encrypt(text, strength=4, level=1)\n", "print(encrypted)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(encrypted) # use a slicing method here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Conditional operators\n", "\n", "Conditional operators are used to branch the code. It consists of a condition (boolean expression) which can be evaluated as *True* or *False* Depending on the value different parts of the code will be executed.\n", "Python's conditional operator is called *if-elif-else* construct. The basic structure looks like this:\n", "```\n", "if condition_1:\n", " statement_1\n", "elif condition_2:\n", " statement_2\n", "else:\n", " statement_3\n", "```\n", "The construct must contain an *if* branch, arbitrary number of *elif* branches and optionally an *else* branch. If every other branches are evaluated to False, the else branch will be executed (if present)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "number = 15\n", "conclusion = ''\n", "\n", "if number < 0:\n", " conclusion = f'{number} is less than zero'\n", "elif number == 0:\n", " conclusion = f'{number} equals to zero'\n", "elif number < 1:\n", " conclusion = f'{number} is greater than zero but less than one'\n", "else:\n", " conclusion = f'{number} bigger than or equal to one'\n", "\n", "print(conclusion)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise: Would you like to continue?\n", "\n", "Ask the user if they would like to continue. If the user types `'yes'`, `'YES'`, `'y'` or `'Y'` print `continue`, \n", "else set the `go` variable to `False` and and print `bye`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "go = True\n", "while go:\n", " user_input = input()\n", " # insert the described if structure here\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Complex data structures" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### List\n", "\n", "Lists are what you think: they store multiple kinds of data. \n", "Typically lists are used to store multiple things of the same type, e.g. a list of applicants, a list of recipes, etc." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": false }, "outputs": [], "source": [ "pi = 3.14\n", "my_list = [1, 2, 'spam', ['eggs', 'ham'], 'spam', pi]\n", "# lists are ordered, and you can access an item using []\n", "my_list[1] = 4\n", "print(my_list)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can add or remove elements from a list too with `append` and `remove`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_list.append('new item')\n", "print(my_list)\n", "my_list.remove('spam')\n", "print(my_list)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also sort lists, and uncover previously unanswered questions, like:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# What came first?\n", "egg_or_chicken = [\"🥚\", \"🐓\"]\n", "\n", "# sort the list and return a new one:\n", "print('sorted: ', sorted(egg_or_chicken))\n", "print('original:', egg_or_chicken)\n", "\n", "# sort the list inplace\n", "egg_or_chicken.sort()\n", "print('modified:', egg_or_chicken)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercise: access the 'ham' element!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercise: add `['python', '101']` to the end of `my_list`!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Tuple\n", "Tuples are similar to lists but their contents are fixed. \n", "Typically tuples are used to store different kind of data, like (page, line) locations in a document." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_tuple = ('spam', 'eggs', 'bacon')\n", "print(my_tuple)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_tuple[1] = 4" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Set\n", "Sets work similarly to mathematical sets. Their elements are unordered and unique." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "set('arthurarthur')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "A = set(['a', 'b', 'c'])\n", "B = set(['c', 'c', 'd', 'e'])\n", "print(A)\n", "print(B)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "B[2]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercise: what are the elements that only appears in set `B`?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Dictionary\n", "Dictionaries are - as their name suggests - key-value pairs. \n", "Typical use of dictionaries is storing information of people in an organization." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_dict = {'key1': 'spam', 2: 2, 'key3': ['s', 'p', 'a', 'm', 3]}\n", "print(my_dict)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Keys must be unmutable or string." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_dict2 = {[1, 2, 3]: 'a list'}" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "person1 = {'name': 'Mario'}\n", "person2 = {'name': 'Sonic'}\n", "# so you can access information in a neat way:\n", "print(person1['name'])\n", "# we can add new key-value pairs like this:\n", "person1['company'] = 'nintendo'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercise: add the company 'sega' to person2!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercise: add the list of active years to each person!\n", "(The first game featuring Mario was Donkey Kong which released in 1981. Sonic first appeared in Sonic the Hedgehog in 1991.)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can check what keys or values does a dict have" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print('keys:', person1.keys())\n", "print('values:', person2.values())\n", "print('items:', person1.items())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercise: what do you think will happen and why?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = 2\n", "dict1 = {a: 6}\n", "a = 6\n", "print(dict1[a])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "\n", "## Let's do some...\n", "\n", "\n", "
\n", "\n", "### Cool library of the week: youtube_dl\n", "* Download a youtube video in four lines!\n", "\n", "```bash\n", "pip install \"yt-dlp[default]\"\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from yt_dlp import YoutubeDL\n", "\n", "with YoutubeDL({'verbose': True}) as ydl:\n", " ydl.download([u'https://www.youtube.com/watch?v=dQw4w9WgXcQ'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Now it's your turn! Write the missing code snippets!\n", "\n", "__1. Write a grocery list with at least 5 items!__" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "grocery_list = " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**2. Update the grocery list with quantities!** \n", "So you will know that you need to buy three dozen eggs instead of three pieces. Which data structure fits the best for this type of data?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "updated_grocery_list =" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "**3. Create a unique list from a not unique list!**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "not_unique_list = [chr(random.randint(65, 90)) for _ in range(26)]\n", "unique_list = []\n", "print(not_unique_list)\n", "print(unique_list)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**4. Write a condition to check if a number is positive, negative or zero.**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "number = random.randint(-1, 1)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**5. FizzBuzz:**\n", "\n", "FizzBuzz is one of the most common programming exercise. The task is to examine a number, and act according to these rules:\n", "- if the number is divisible by 3:\n", " - instead of the number, print 'Fizz'\n", "- if the number is divisible by 5:\n", " - instead of the number, print 'Buzz'\n", "- if the number is divisible by both 3 and 5:\n", " - instead of the number, print 'FizzBuzz'\n", "- otherwise:\n", " - print the number" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "numbers = list(range(30))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**6. Intolerance checking**\n", "\n", "- Create a dictionary with food ingredients\n", "- Create a list of intolarencies\n", "- Ask the user if he/she has any food intolarencies (show the created list to choose from)\n", "- Ask the user what he/she would like to eat\n", "- Print out if the selected food has incompatible ingredients\n", "\n", "##### 6.a Create a dictionary with food recipes and ingredients\n", "Every food consists of multiple ingredients" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ingredients = {}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### 6.b Create a list of intolarencies\n", "Write down all the ingredients that might cause allergic reaction (eg. nuts)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "intolarencies = []" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### 6.c Ask the user about intolerancies\n", "Generate a string containing all of the intolerancies for the user to choose from. \n", "*Hint*: if a list only consists of strings we can join the values together with the `join` command. \n", "Basic form: `'separator'.join(list)`\n", "\n", "Example:\n", "```python\n", "my_list = ['a', 'b', 'c']\n", "print(', '.join(my_list))\n", ">>> a, b, c\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "intolarency_string = \"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### 6.d Ask the user to select a food from the available list" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "intolerancy = \"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### 6.e Print if the user can eat the selected food" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "szisz_python_2025_automn", "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.13.7" } }, "nbformat": 4, "nbformat_minor": 1 }