diff --git a/Intro_Python_Data_types_1.ipynb b/Intro_Python_Data_types_1.ipynb new file mode 100644 index 0000000..1134f84 --- /dev/null +++ b/Intro_Python_Data_types_1.ipynb @@ -0,0 +1,3421 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "P-pZCCGaPtU6" + }, + "source": [ + "# LAB | Intro Python Data Types" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "dtejTWtAPtU8" + }, + "source": [ + "![elgif](https://media.giphy.com/media/coxQHKASG60HrHtvkt/giphy.gif)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "YY47OWZJPtU8" + }, + "source": [ + "In this course, we will use Jupyter notebooks to write and execute Python code, so the first step will be to learn how to use them.\n", + "Notebook documents (or \"notebooks\", all in lowercase) are documents created by the Jupyter Notebook application, which contain both computer code (for example, Python) and rich text elements (paragraphs, equations, figures, links, etc...).\n", + "Notebooks are made up of cells, which are blocks of code or rich text. Each of these is editable, although you will primarily be modifying code cells to answer questions.\n", + "\n", + "### Technical Description of a Jupyter Notebook\n", + "\n", + "The Jupyter Notebook application is a server-client application that allows editing and executing notebook documents through a web browser. The IBM version of the Jupyter Notebook application is installed on a remote server and is accessed through the internet.\n", + "\n", + "A notebook kernel is a \"computational engine\" that executes the code contained in a notebook document. The ipython kernel, mentioned in this guide, runs Python code. There are kernels for many other languages (see the Kernels menu above).\n", + "\n", + "When you open a notebook document, the associated kernel starts automatically. By running the notebook (either cell by cell or through the Cell -> Run All menu), the kernel performs the calculations and produces the results. Depending on the type of calculations, the kernel can consume a significant amount of CPU and RAM. Keep in mind that the RAM is not released until the kernel is closed." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "1hyw_SzDPtU8" + }, + "source": [ + "### Introduction to PEP-8 and `import this`\n", + "\n", + "#### PEP-8\n", + "\n", + "[PEP-8](https://peps.python.org/pep-0008/), also known as \"Python Enhancement Proposal 8\", is the style guide for writing code in Python. It was conceived to facilitate the reading and understanding of code, promoting consistency in the way Python programmers write their code. Some of the key principles of PEP-8 include using indents of four spaces, lines that do not exceed 79 characters, and the definition of functions and variables in lowercase names separated by underscores. It is highly recommended to adhere to PEP-8 to maintain clean and readable Python code.\n", + "\n", + "#### `import this`\n", + "\n", + "The command `import this` or [PEP-20](https://peps.python.org/pep-0020/) in Python is a little \"easter egg\" included in the language, which when executed, displays the **\"Zen of Python\"**. The \"Zen of Python\" is a collection of 19 aphorisms that express the design philosophy of the Python language. Some of these aphorisms emphasize the importance of code readability and simplicity over complexity. You can see these aphorisms at any time while programming in Python by executing the command `import this` in your Python console or script.\n", + "\n", + "To use it, simply type the following command in your Python interpreter:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "G4VCgtHiPtU9" + }, + "outputs": [], + "source": [ + "import this" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "o8Zb4KA6PtU9" + }, + "source": [ + "![otrogif](https://media.giphy.com/media/MT5UUV1d4CXE2A37Dg/giphy.gif)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "toc": true, + "id": "y3urkb8rPtU9" + }, + "source": [ + "" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "lang": "en", + "id": "KSqGSbfKPtU-" + }, + "source": [ + "## 1. Cell types in Jupyter Notebook" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "l6-0eU0cPtU-" + }, + "source": [ + "`ctrl-enter`: executes the active cell and stays in that cell\n", + "\n", + "`shift-enter`: executes the active cell and moves to the next cell\n", + "\n", + "*Try it* Execute the following cells:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "kFZQmgajPtU-", + "outputId": "fa94cc0a-21fb-4238-b5ca-babe3327a637" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Hello World\n" + ] + } + ], + "source": [ + "print (\"Hello World\")" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "scrolled": true, + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "XgwsUP8PPtU-", + "outputId": "bb84d95b-98d7-4ea5-8810-1a6d096922fa" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Second line\n" + ] + } + ], + "source": [ + "print (\"Second line\")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "fZPlqH4QPtU-" + }, + "source": [ + "**Inserting New Cells:**\n", + "When a cell is selected in blue (click on the left margin of the cell) or, if you are editing the cell, press the escape key, a blue box appears around it.\n", + "\n", + "Type:\n", + "- `a` (above) to create a new empty cell above the active cell at that time\n", + "- `b` (below) to create a new empty cell below the active cell at that time\n", + "\n", + "*Try it: Add a cell below and then a cell above*\n", + "\n", + "**Markdown Code:**\n", + "The `m` shortcut (with the selection in blue) changes the computing cell to markdown. This allows creating rich text elements to document the code.\n", + "Conversely, you can convert a cell into a code cell using the `y` shortcut.\n", + "\n", + "*Try it: Convert the first cell below into a code cell and run it, and the cell below into a markdown cell*\n", + "\n", + "#### **Not a code cell right now:**\n", + "print(\"Now it is a code cell :)\")" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "id": "XTNy7h9yPtU-" + }, + "outputs": [], + "source": [ + "#### **This is a cell for coding**" + ] + }, + { + "cell_type": "code", + "source": [ + "print(\"This is a code cell\")" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "htU71uHJQBSu", + "outputId": "a359532f-0d90-4a4c-82ba-70a205f98bb1" + }, + "execution_count": 4, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "This is a code cell\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "AGPF-dJbPtU-" + }, + "source": [ + "#### **Exercise: Converting Code to Markdown**\n", + "\n", + "In this exercise, your task will be to convert the following code cells that contain headings and rich text into markdown cells. This way, instead of appearing as a block of code, they will be displayed as formatted text.\n", + "\n", + "1. Select the first cell that contains the headings and the rich text written as code.\n", + "2. Use the `m` shortcut (making sure the cell is highlighted in blue) to convert the code cell into a markdown cell.\n", + "3. Press `Shift+Enter` or `Ctrl+Enter` to run the cell and see the result.\n", + "4. If you've done the step correctly, you should see the headings and rich text (bold, italics, etc.) applied instead of as a block of code.\n", + "\n", + "*Try it: Convert the cells with the headings and rich text from code to markdown and run them to see the result.*\n", + "\n", + "Remember, the cells should look just like the example cells provided below.\n", + "\n", + "Good luck!" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "scrolled": true, + "colab": { + "base_uri": "https://localhost:8080/", + "height": 106 + }, + "id": "7eMLcKY3PtU_", + "outputId": "584f0b3f-eac9-4770-acce-8a901a207a8c" + }, + "outputs": [ + { + "output_type": "error", + "ename": "SyntaxError", + "evalue": "invalid syntax (ipython-input-3645573057.py, line 6)", + "traceback": [ + "\u001b[0;36m File \u001b[0;32m\"/tmp/ipython-input-3645573057.py\"\u001b[0;36m, line \u001b[0;32m6\u001b[0m\n\u001b[0;31m **bold**\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" + ] + } + ], + "source": [ + "# Header 1\n", + "## Header 2\n", + "### Header 3\n", + "#### Header 4\n", + "\n", + "**bold**\n", + "\n", + "*italic*\n", + "\n", + "a blank line is a paragraph\n", + "\n", + "this is a new paragraph" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "O1fNS2HUPtU_" + }, + "source": [ + "If you have successfully converted the cell to a markdown cell, it should be displayed just like the cell below." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "ul3JCrG0PtU_" + }, + "source": [ + "# Header 1\n", + "## Header 2\n", + "### Header 3\n", + "#### Header 4\n", + "\n", + "**bold**\n", + "\n", + "*italic*\n", + "\n", + "a blank line is a paragraph\n", + "\n", + "this is a new paragraph" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "JokPw1SkPtU_" + }, + "source": [ + "### Explanation of Markdown Elements\n", + "\n", + "In the provided example, there are two very useful and common Markdown elements: links and images.\n", + "\n", + "1. **Link**\n", + " The first line `[name](url)` is a link. The syntax for creating a link is to place the link text between square brackets `[]` and the URL between parentheses `()`. Clicking on the text \"This is Google\" will take you to the Google Spain web page.\n", + "\n", + "2. **Image**\n", + " The second line `![name](url image)` is an image. The syntax for inserting an image is very similar to that of a link, but it starts with an exclamation mark `!`. The text between square brackets `[]` serves as an alternative description for the image, which is displayed if the image cannot be rendered for any reason. In this case, when running the cell, you will see the text \"This is an image (which will not render)\" if the image cannot be loaded from the provided URL.\n", + "\n", + "You can try these elements for yourself in any markdown cell. Give it a try!" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "KJyiSXzMPtU_" + }, + "source": [ + "**Link**\n", + "[This is google](https://www.google.es)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "dxiF7rwfPtU_" + }, + "source": [ + "**Image**:\n", + "![This image (won't render)](https://m.facebook.com/IronhackSpain/photos/a.644771729221628/1108169482881848/?type=3&source=44&ref=py_c)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "4j4GFdRaPtU_" + }, + "source": [ + "### Shortcuts" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "sAnoeFvnPtU_" + }, + "source": [ + "**Final Keyboard Shortcut Reminder**\n", + "\n", + "To execute the cell:\n", + "\n", + "- `ctrl + enter`\n", + "- `shift + enter` # this executes the cell and moves to the next one\n", + "\n", + "To insert new cells:\n", + "\n", + "- `a` for a new cell above\n", + "- `b` for a new cell below\n", + "- `d + d` for shortcut mode (deletes the selected cell)\n", + "\n", + "To toggle between markdown and code:\n", + "\n", + "- `m` or `y` to switch between markdown and code\n", + "\n", + "# Type of Data\n", + "In this section, we will explore different types of data you can encounter and use in Python. Understanding the different types of data is fundamental to working effectively with Python.\n", + "\n", + "- **Integers**: These are numbers without decimal points, and can be either positive or negative. For example, -3, 0, 42 are all integers.\n", + "\n", + "- **Floating-point Numbers (Float)**: These are numbers that contain decimal points or are written in scientific notation. They include values like 3.14, -0.001, or 2.5e2.\n", + "\n", + "- **Strings**: Strings are sequences of characters (letters, numbers, symbols, emojis) enclosed in single (`'`) or double (`\"`) quotes. For example, \"Hello, World\" or 'Python3' are strings.\n", + "\n", + "- **Booleans (Boolean)**: Boolean values can only be `True` (true) or `False` (false), and represent the outcome of logical operations.\n", + "\n", + "Remember, Python is a dynamically typed and strongly typed language, which means you do not need to explicitly declare the data type of a variable; Python will infer it for you.\n", + "\n", + "\n", + "## Integer Numbers\n", + "Integer numbers, also known as \"integers\" in English, are a type of data that represents whole numbers, that is, without decimals. They can be both positive and negative. In Python, you can assign an integer value to a variable simply by writing the number without any decimal or quotes. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "id": "A3AtmpmPPtU_" + }, + "outputs": [], + "source": [ + "whole_number = 4" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "PeVXAZXVPtU_" + }, + "source": [ + "In this cell, we are declaring a variable called `an_integer` and assigning it the value 4, which is an integer number." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "scrolled": true, + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "8CDQqbO1PtU_", + "outputId": "20139c61-f013-497e-dd2e-524974ef8dfc" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "4" + ] + }, + "metadata": {}, + "execution_count": 7 + } + ], + "source": [ + "whole_number" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "8EC5AfNfPtU_" + }, + "source": [ + "Here, we are simply writing the name of the variable. This will make the Jupyter notebook print its value, which is 4." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "scrolled": true, + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "9fp20OTAPtU_", + "outputId": "5eeb8f6f-dc7b-49b2-a08e-0a4795900d40" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "4\n" + ] + } + ], + "source": [ + "print(whole_number)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "jyCJifOtPtU_" + }, + "source": [ + "In this cell, we are using the `print()` function to print the value of the variable `an_integer`. You will also see 4 as output here, but unlike the previous cell, you are specifically using a function to print the value." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "n-mIYBggPtU_", + "outputId": "70e77bde-3b74-4ba5-b159-18b796e10e5d" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "20" + ] + }, + "metadata": {}, + "execution_count": 9 + } + ], + "source": [ + "a = 10\n", + "b = 20\n", + "a\n", + "b # Notebook prints last value" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "_P70GSBLPtU_" + }, + "source": [ + "In this set of lines, first we assign 10 to `a` and 20 to `b`. Then, we write `a` and `b` on separate lines, but the Jupyter notebook will only print the value of `b`, since it is the last one in the cell. This is indicated with the comment # Notebook prints the last value." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "scrolled": true, + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "WGPHVahHPtU_", + "outputId": "5ca0ca6b-c31e-4f32-be7d-d1aee153fe18" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "10\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "20" + ] + }, + "metadata": {}, + "execution_count": 10 + } + ], + "source": [ + "a = 10\n", + "b = 20\n", + "print(a)\n", + "b # Notebook prints last value" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "3DkVakuAPtU_" + }, + "source": [ + "Here, it is similar to the previous cell, but this time we are using the `print()` function to print the value of `a` before simply writing `b`. You will see both 10 (the output of `print(a)`) and 20 (the value of `b`) in the output." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "gEAqDTSZPtU_", + "outputId": "6a088cd4-07dd-4719-9ee8-c1f51f509fce" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "int" + ] + }, + "metadata": {}, + "execution_count": 11 + } + ], + "source": [ + "type(a)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "aBpvdE4qPtVA" + }, + "source": [ + "Finally, we are using the `type()` function to print the data type of the variable `a`, which in this case is ``, indicating that it is an integer number." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "lang": "en", + "id": "8RYtZDFxPtVA" + }, + "source": [ + "## Real numbers (floats)\n", + "In this section, we are going to explore another data type in Python: real numbers, also known as \"floats.\" Floats can represent fractional numbers, meaning numbers that have both an integer part and a decimal part. They can be both positive and negative.\n", + "\n", + "In Python, you can create a float by simply including a decimal point in the number, or by using scientific notation for very large or very small numbers. Here are some examples:\n", + "\n", + "x = 5.67\n", + "\n", + "y = -0.23\n", + "\n", + "z = 3.0e8\n", + "\n", + "In this code:\n", + "- `x` is a float representing the number 5.67.\n", + "- `y` is a float representing the number -0.23.\n", + "- `z` is a float representing the number 300,000,000 (or 3.0 × 10^8, using scientific notation).\n", + "\n", + "Just like with integers, you can use the `type()` function to check the data type of a variable. For example, `type(x)` will return ``, indicating that `x` is a float.\n", + "\n", + "Floats are useful when you need to perform calculations that require decimal precision. Now, let's practice working with floats in Python with some exercises." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "id": "uqB16Q_aPtVA" + }, + "outputs": [], + "source": [ + "a = 12.34" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "KNd1dtsdPtVA" + }, + "source": [ + "In the previous cell, we assigned the float number 12.34 to the variable `a`. Now, let's print the value of `a` to verify it." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "nUXtxhP_PtVA", + "outputId": "dfae85e8-d318-4bb2-e11f-584fd4e93a5b" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "12.34\n" + ] + } + ], + "source": [ + "print(a)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "bWvglplWPtVA" + }, + "source": [ + "Now, let's use the `type()` function to check the data type of the variable `a`. This should confirm that it is a float number." + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "0BM_Bg54PtVD", + "outputId": "30fb949d-e950-462f-b35c-2ee18da7c10d" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "float" + ] + }, + "metadata": {}, + "execution_count": 14 + } + ], + "source": [ + "type(a)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "id": "KbIn2Q-bPtVD" + }, + "outputs": [], + "source": [ + "b = 12.0" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "5AEbYKtfPtVE" + }, + "source": [ + "Now, try to predict the data type of the variable `b` before verifying it with the `type()` function. Do you think it is:\n", + "- **int?**\n", + "- **float?**" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "scrolled": true, + "id": "GSrOhZ_VPtVE" + }, + "outputs": [], + "source": [ + "# type(b)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "MOkdMZ0tPtVE" + }, + "source": [ + "In this last cell, we verify the data type of `b` using the `type()` function. Although `b` has a value that could be an integer, it is considered a float because it includes a decimal point." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "lang": "en", + "id": "x8Biai88PtVE" + }, + "source": [ + "## Basic operations\n", + "In this section, we will explore some basic operations in Python. We will learn how to perform addition, subtraction, division, and how to obtain the modulus and floor division. We will also see how we can use the modulus to determine if a number is even or odd. Let's start with some practical exercises!" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "id": "yxnxfCm2PtVE" + }, + "outputs": [], + "source": [ + "a = 10\n", + "b = 3" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "scrolled": true, + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "bcBMGScoPtVE", + "outputId": "13d9724a-e7ab-47bc-955b-1bead343edde" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "13" + ] + }, + "metadata": {}, + "execution_count": 18 + } + ], + "source": [ + "10 + 3" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "GkC-gd5ePtVE" + }, + "source": [ + "In the previous cell, we simply added 10 and 3 directly in a code cell. Now, we will do the same, but using the variables `a` and `b` that we have defined previously." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "scrolled": true, + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "D8Gggde9PtVE", + "outputId": "13c88b86-598d-42be-9415-cd1e7c39654a" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "13" + ] + }, + "metadata": {}, + "execution_count": 19 + } + ], + "source": [ + "# Sum\n", + "a + b" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "SCmfSmGvPtVE" + }, + "source": [ + "Now we will proceed to perform a subtraction using the same variables, `a` and `b`." + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "ghh-qQ_XPtVE", + "outputId": "76abda60-7579-4140-b223-941db2cfe47a" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "7" + ] + }, + "metadata": {}, + "execution_count": 20 + } + ], + "source": [ + "# difference\n", + "\n", + "a - b" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "x0qbG-sQPtVE" + }, + "source": [ + "Next, we will explore how to perform divisions in Python. First, we will perform a regular division and then check the data type of the result." + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "id": "Xg-mmo-0PtVE" + }, + "outputs": [], + "source": [ + "# division\n", + "\n", + "division = a / b" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "mWPNcYgaPtVE", + "outputId": "80f33f36-8f55-466f-952a-3179d18b44ce" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "float" + ] + }, + "metadata": {}, + "execution_count": 22 + } + ], + "source": [ + "type(division)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "zmiPaB0FPtVE" + }, + "source": [ + "Now, let's learn about \"floor division,\" which rounds the result of the division down to the nearest integer. We will also check the data type of the result." + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "PWbJcRCvPtVE", + "outputId": "30edddf8-8495-4540-ee11-0fba92fcc3df" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "3" + ] + }, + "metadata": {}, + "execution_count": 23 + } + ], + "source": [ + "# division: floor division: rounded division\n", + "\n", + "floor_division = a // b\n", + "floor_division" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "onHqRDA5PtVE", + "outputId": "616bce56-10d8-463a-c626-494027481bdf" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "int" + ] + }, + "metadata": {}, + "execution_count": 24 + } + ], + "source": [ + "type(floor_division)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "b0XxAQWnPtVE" + }, + "source": [ + "Next, we will explore the modulo operator (`%`), which gives us the remainder of a division. First, we will find the modulo of `a` divided by `b`." + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "0R3hM7vDPtVE", + "outputId": "4eaa4da2-a7b0-4c07-a720-3fb2972bc23c" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "1" + ] + }, + "metadata": {}, + "execution_count": 25 + } + ], + "source": [ + "# Module: Remainder of the division\n", + "\n", + "a % b" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "KA3a96KwPtVE" + }, + "source": [ + "To better understand how divisions and the modulo operator work, we will print the values of `a` and `b`." + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "t3awtXVTPtVE", + "outputId": "cef04a9f-3b53-42e1-c850-a96c98a8dc76" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "10" + ] + }, + "metadata": {}, + "execution_count": 26 + } + ], + "source": [ + "a" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "LbRjiCjNPtVE", + "outputId": "d57d6f06-3465-4b53-dbce-0cc2b2d904a6" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "3" + ] + }, + "metadata": {}, + "execution_count": 27 + } + ], + "source": [ + "b" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "R1rW4oRpPtVE" + }, + "source": [ + "Next, we will use the modulo operator to determine if the numbers in a list are even or odd. If a number divided by 2 yields a remainder of 0, then it is even. Let's create a loop that iterates over a list of numbers and tells us if each number is even or odd." + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "VIhSraQvPtVE", + "outputId": "fa9f36be-a139-4c8d-c4e7-7a64eb600fbe" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "El numero 1 NO es par\n", + "El numero 2 es par\n", + "El numero 3 NO es par\n", + "El numero 4 es par\n", + "El numero 5 NO es par\n", + "El numero 6 es par\n" + ] + } + ], + "source": [ + "# Even / odd -> modulo (remainder)\n", + "# If the remainder of a division by two is zero: even\n", + "\n", + "\n", + "list_ = [1, 2, 3, 4, 5, 6]\n", + "\n", + "for i in list_:\n", + " if i % 2 == 0:\n", + " print(f\"El numero {i} es par\")\n", + " else:\n", + " print(f\"El numero {i} NO es par\")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "dYvljZKMPtVF" + }, + "source": [ + "### Practical Exercise\n", + "Now that we have explored some basic operations in Python, it's your turn to give it a try.\n", + "\n", + "**Instructions:**\n", + "1. Create two new variables, `x` and `y`, and assign any integer number to each of them.\n", + "2. Perform the following operations using these variables:\n", + " - Addition\n", + " - Subtraction\n", + " - Multiplication\n", + " - Division and check the type of result\n", + " - Floor division and check the type of result\n", + " - Find the modulo (remainder of division)\n", + "3. Use a `for` loop to iterate over a list of numbers from 1 to 10 and print whether each number is even or odd.\n", + "\n", + "Don't forget to print the results to verify your solutions." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "cA7btmp3PtVF" + }, + "outputs": [], + "source": [ + "# your solution here" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "3S1sJ0scPtVF" + }, + "source": [ + "### built-in and imported things\n", + "\n", + "In the world of Python, you will often work with different methods and functions to perform specific tasks in your code. \"Methods\" and \"functions\" are essentially things that perform actions (or, as we colloquially say, \"things that do things\"). Below, we'll explore two main categories of these: built-in things and imported things (*summary: methods = functions = things that do things*).\n", + "\n", + "- **Built-in methods:**\n", + "These are functions or things that are already included in Python when you install it. You don't need to install anything extra to use them. Some examples are the `print` and `sum` methods.\n", + "\n", + "- **Imported things:**\n", + "Sometimes, you might need to use functions or things that are not directly built into Python. In these cases, you'll need to import them from an external library. Before you can use these functions, you'll need to install the corresponding library with a `pip install` or `conda install` command, and then import it into your script.\n", + "\n", + "Below, we'll explore some examples of both types of \"things\":" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "nf6zjUonPtVF", + "outputId": "0c48b1da-b758-4dc5-cf27-06158567622b" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "This is built-in\n" + ] + } + ], + "source": [ + "# First, let's explore a built-in method: print\n", + "# The print method allows us to print messages to the console.\n", + "print(\"This is built-in\")" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "1E9JtPm7PtVF", + "outputId": "31fbfd6d-1522-431b-8ede-c97f4f26d513" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'THIS IS A STRING'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 30 + } + ], + "source": [ + "# Another example of a built-in method is upper.\n", + "# This method converts a string of text to uppercase.\n", + "\"This is a string\".upper()" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": { + "id": "yItM_3_3PtVF" + }, + "outputs": [], + "source": [ + "# Now, let's explore how to import and use things from an external library.\n", + "# First, we need to import the library. In this case, we're importing the math library.\n", + "import math" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "133xOETDPtVF", + "outputId": "cb2f4da4-9b2e-4b98-e149-3e5ae86f166c" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "8789" + ] + }, + "metadata": {}, + "execution_count": 32 + } + ], + "source": [ + "# Next, we use a function from the math library: floor.\n", + "# The floor function rounds a number down to the nearest integer.\n", + "math.floor(8789.098767)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "lang": "en", + "id": "tGxx4SIZPtVF" + }, + "source": [ + "## Strings (character strings)\n", + "\n", + "Character strings, also known as \"strings,\" are a sequence of characters, which can include letters, numbers, symbols, and even emojis. Strings can be enclosed in double or single quotes, and we can even define multi-line strings using triple quotes. Below, we'll explore various examples and features of strings in Python.\n", + "\n", + "Examples of defining a string with different types of quotes:" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": { + "scrolled": true, + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "9bcrMkZIPtVF", + "outputId": "814b6a2e-bd0f-4ab8-e653-4e78cb61acd9" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'This is a string'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 33 + } + ], + "source": [ + "\"This is a string\"" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "dbzW8jSzPtVF", + "outputId": "be274182-fc3b-4ff0-f0f0-6855d8b5c9b9" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'This is a string with simple quotes'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 34 + } + ], + "source": [ + "'This is a string with simple quotes'" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": { + "scrolled": true, + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "YkRqK165PtVF", + "outputId": "d7b561b4-fdac-42d6-9473-5517e22cd421" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'This is a string with simple quotes'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 35 + } + ], + "source": [ + "\"This is a string with simple quotes\" #End Of Line" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "0RDUU3M-PtVF" + }, + "source": [ + "We can assign a string to a variable, as shown here:" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "1ygihHnzPtVF", + "outputId": "a23dd97f-e4d1-48fc-f71c-0bd5c113e178" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'4'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 36 + } + ], + "source": [ + "this_is_also_a_string = \"4\"\n", + "this_is_also_a_string" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "QB9ygNMGPtVF" + }, + "source": [ + "We can check the type of a variable using the `type` function:" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "A81QkNbzPtVF", + "outputId": "b8299227-5f72-4cee-e5a3-de93b692f049" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "str" + ] + }, + "metadata": {}, + "execution_count": 37 + } + ], + "source": [ + "type(this_is_also_a_string)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "1LUr1vmTPtVF" + }, + "source": [ + "Attempting to create a multi-line string without triple quotes will result in an error:" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 106 + }, + "id": "hMoH096JPtVF", + "outputId": "9ae8f4ff-e3a2-4bb7-d84a-7f67ab212557" + }, + "outputs": [ + { + "output_type": "error", + "ename": "SyntaxError", + "evalue": "unterminated string literal (detected at line 1) (ipython-input-2937582216.py, line 1)", + "traceback": [ + "\u001b[0;36m File \u001b[0;32m\"/tmp/ipython-input-2937582216.py\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m \"This is a string\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m unterminated string literal (detected at line 1)\n" + ] + } + ], + "source": [ + "\"This is a string\n", + "with multiple lines\"" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "-up-RoepPtVF" + }, + "source": [ + "To create a multi-line `string` correctly, we should use triple quotes:" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "YRSTZOSKPtVF", + "outputId": "e7f4c948-7c21-450f-ce2a-711ea0edbf2a" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'\\nThis is a string\\nwith multiple liness'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 39 + } + ], + "source": [ + "\"\"\"\n", + "This is a string\n", + "with multiple liness\"\"\"" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "xPboz3R_PtVF" + }, + "source": [ + "We can also print a multi-line `string` using the print function and triple quotes:" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "ndWI1mYGPtVF", + "outputId": "45ee8a0e-f5b1-49bf-c8bf-5211cc322828" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\n", + "This is a string\n", + "with multiple liness\n" + ] + } + ], + "source": [ + "print(\"\"\"\n", + "This is a string\n", + "with multiple liness\"\"\")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "jtZ3q3qXPtVF" + }, + "source": [ + "#### icons\n", + "Strings can contain emojis, as shown here:" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "d61rFxZzPtVF", + "outputId": "1081d927-d87d-44ff-860f-a186ddf2d4d7" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'😍'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 41 + } + ], + "source": [ + "\"😍\" #emojis -> They are strings" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": { + "id": "Ad72-hCHPtVG" + }, + "outputs": [], + "source": [ + "heart_face = \"😍\"" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "xYPNq8v4PtVG", + "outputId": "bd2f8283-5c07-44cc-8361-4b4a5afcb209" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'😍'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 43 + } + ], + "source": [ + "heart_face" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "OeZuOM_RPtVG", + "outputId": "edf833b0-ea37-44bd-87c0-1cee9f555c58" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "str" + ] + }, + "metadata": {}, + "execution_count": 44 + } + ], + "source": [ + "type(heart_face)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "lang": "en", + "id": "KnSm7NZ3PtVG" + }, + "source": [ + "## Casting in Python\n", + "\n", + "Type conversion, also known as \"casting,\" refers to the process of converting one data type to another. Previously, we have seen data types such as `int`, `string`, or `float`. Well, it turns out that it's possible to convert from one type to another. But first, let's look at the different types of conversions or type transformations that can be performed. There are two:\n", + "\n", + "**Implicit conversion:** This is done automatically by Python. It occurs when we perform certain operations with two different types, Python converts it in the background without the need for the programmer to explicitly indicate it.\n", + "\n", + "**Explicit conversion:** We do this explicitly, such as converting a `str` to `int` with `int()` or to `float` with `float()`. This type of conversion is done using predefined Python functions.\n", + "\n", + "It's important to note that not all data types can be safely converted between each other. For example, trying to convert a text string containing letters to an integer will result in an error. Therefore, it's always a good practice to handle potential errors using exception control structures, which we'll see later in the course.\n", + "\n", + "Let's see some examples of each to better understand how they work!\n", + "\n", + "### Implicit conversion\n", + "This type of conversion is done automatically by Python, practically without us noticing. However, it's important to know what's happening under the hood to avoid future problems.\n", + "\n", + "The simplest example where we can see this behavior is as follows:\n", + "- `a` is an `int`\n", + "- `b` is a `float`\n", + "\n", + "But if we add `a` and `b` and store the result in `a`, we can see how Python has internally converted the `int` to `float` to perform the operation, and the resulting variable is a `float`. However, there are other cases where Python is not as smart and is unable to perform the conversion. If we try to add an `int` to a `string`, we'll get a `TypeError`." + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "metadata": { + "id": "gIuqLkgcPtVG" + }, + "outputs": [], + "source": [ + "a = 5 # This is a int\n", + "b = 4.5 # This is a float" + ] + }, + { + "cell_type": "code", + "execution_count": 46, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "i0U2NquQPtVG", + "outputId": "1ad5ce91-87d7-458b-e815-fb04e33c91db" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "9.5\n" + ] + } + ], + "source": [ + "c = a + b # Python automatically converts a to float to perform the operation\n", + "print(c) # The result, 9.5, is a float" + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 159 + }, + "id": "G5wp-Yc6PtVG", + "outputId": "92bf3200-f441-4b5f-ba0f-e214580efd70" + }, + "outputs": [ + { + "output_type": "error", + "ename": "TypeError", + "evalue": "can only concatenate str (not \"int\") to str", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m/tmp/ipython-input-3849243611.py\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# But, if we try to perform an operation between a string and an integer:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0md\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m\"Hola\"\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0ma\u001b[0m \u001b[0;31m# This will cause a TypeError\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m: can only concatenate str (not \"int\") to str" + ] + } + ], + "source": [ + "# But, if we try to perform an operation between a string and an integer:\n", + "d = \"Hola\" + a # This will cause a TypeError" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "lang": "en", + "id": "VOkZXDCzPtVG" + }, + "source": [ + "### explicit conversion\n", + "\n", + "On the other hand, we can perform explicit conversions between types or castings using different functions provided by Python. The most commonly used ones are:\n", + "\n", + "`float()`, `str()`, `int()`, `list()`, `set()`\n", + "\n", + "#### Convert float to int\n", + "\n", + "To convert from float to int we should use `int()`. But be careful, because the integer type cannot store decimals, so we'll lose whatever comes after the decimal point." + ] + }, + { + "cell_type": "code", + "execution_count": 48, + "metadata": { + "id": "uqG1qQBFPtVG" + }, + "outputs": [], + "source": [ + "# Example of explicit conversion\n", + "float_number = 5.7\n", + "int_number = int(float_number)" + ] + }, + { + "cell_type": "code", + "execution_count": 49, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "dqncWLj4PtVG", + "outputId": "cc4384e2-8f94-4a1f-ba3f-bda087ab6626" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "5.7\n" + ] + } + ], + "source": [ + "print(float_number) # The result will be 5, losing the decimal part." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "lang": "en", + "id": "OjOFJytXPtVG" + }, + "source": [ + "#### Convert a float to a string\n", + "Podemos convertir un float a un string de texto utilizando `str()`. Podemos ver en el siguiente código cómo cambia el tipo de `a` después de la conversión." + ] + }, + { + "cell_type": "code", + "execution_count": 50, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "bfrH60PvPtVG", + "outputId": "c2ea8724-39b2-49f9-f4b5-ded8e37771e7" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\n" + ] + } + ], + "source": [ + "# Example of converting a float to a string\n", + "a = 3.14159\n", + "print(type(a)) # This will print: " + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "h5j2B_2oPtVG", + "outputId": "53085db7-5005-40dd-a3e5-3b3b75dc92b0" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\n", + "3.14159\n" + ] + } + ], + "source": [ + "a = str(a)\n", + "print(type(a)) # This will print: \n", + "print(a) # This will print: 3.14159, but now as a string." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "lang": "en", + "id": "buLMrBLdPtVG" + }, + "source": [ + "#### Convert int to str\n", + "Just like the conversion to float we saw earlier, we can convert from int to str using `str()`. Let's see an example below:" + ] + }, + { + "cell_type": "code", + "execution_count": 52, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "VQOWwXpiPtVG", + "outputId": "a45c899d-28ea-4974-c006-f1c37a0cc44f" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\n" + ] + } + ], + "source": [ + "# Example of converting an integer to a string\n", + "a = 42\n", + "print(type(a)) # This will print: " + ] + }, + { + "cell_type": "code", + "execution_count": 53, + "metadata": { + "scrolled": true, + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "x9_Kk11xPtVG", + "outputId": "86fc7718-5015-4a78-8066-c5579439d636" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\n", + "42\n" + ] + } + ], + "source": [ + "a = str(a)\n", + "print(type(a)) # This will print: \n", + "print(a) # This will print: \"42\", but now as a string." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "JU1Yt0AaPtVG" + }, + "source": [ + "#### Exercise\n", + "\n", + "Now it's your turn to try converting from int to str. Perform the following tasks:\n", + "\n", + "1. Create a variable `age` and assign your age as an integer.\n", + "2. Convert the variable `age` to a string using the `str()` function.\n", + "3. Concatenate the string \"My age is: \" with the variable `age` (now a string) and store the result in a new variable called `message`.\n", + "4. Print the variable `message` to the console.\n", + "\n", + "Below is a basic outline you can use:" + ] + }, + { + "cell_type": "code", + "execution_count": 55, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "bd1OkqxxPtVG", + "outputId": "89cace32-6541-4c7f-8ea7-e4dcab74f0f3" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "My age is: 41\n" + ] + } + ], + "source": [ + "# Step 1: Create a variable age with your age as an integer\n", + "age = 41\n", + "\n", + "# Step 2: Convert the variable age to a string\n", + "age = str(41)\n", + "\n", + "# Step 3: Concatenate \"My age is: \" with the variable age and store the result in a new variable called message\n", + "message = \"My age is: \" + age\n", + "\n", + "# Step 4: Print the variable message\n", + "print(message)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "lang": "en", + "id": "SMrm_bK-PtVG" + }, + "source": [ + "## Input and output data\n", + "\n", + "In the development of programs, we often need to interact with users by allowing them to input data and displaying results or messages. Python provides simple and straightforward methods to achieve this, making it easy to create interactive and user-friendly scripts. Below, we will explore how we can accomplish this using Python.\n", + "\n", + "### Input\n", + "\n", + "To assign a variable to a value entered by the user from the console, we use the `input()` function. This function can take an optional argument: the message or prompt that you want to display on the screen to guide the user on what type of information is expected to be entered. It's essential to note that, regardless of the type of data the user enters, the `input()` function will always return a string. Here's the basic outline of how it works:\n", + "\n", + "`input(message)`: Displays the message on the terminal and returns a string with the user's input.\n", + "\n", + "Often, it may be necessary to convert this string to a different data type, depending on how you plan to use the entered value in your script. This can be done using type conversion techniques, or \"casting,\" which we discussed in earlier sections." + ] + }, + { + "cell_type": "code", + "execution_count": 56, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 52 + }, + "id": "stCggG2zPtVG", + "outputId": "d7be7183-e9c5-4f50-8605-9e7df375de03" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "dobro jutro\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'dobro jutro'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 56 + } + ], + "source": [ + "salutation = input()\n", + "salutation" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "NyJZcyQhPtVG" + }, + "source": [ + "Ahora, vamos a personalizar el mensaje que aparece cuando pedimos una entrada al usuario utilizando el argumento `prompt` de la función `input()`." + ] + }, + { + "cell_type": "code", + "execution_count": 57, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "IVvFpBrZPtVG", + "outputId": "4b105f82-d85e-4a7b-a79e-25d70470edd9" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "This is a promptdobro jutro\n" + ] + } + ], + "source": [ + "salutation = input(prompt = \"This is a prompt\")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "WR60G6X9PtVG" + }, + "source": [ + "Let's continue by requesting more information from the user, such as their name and a number. Then, we'll experiment with the operations we can perform with these inputs." + ] + }, + { + "cell_type": "code", + "execution_count": 58, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 52 + }, + "id": "ReEnjdc1PtVG", + "outputId": "08a7a943-7ca8-4734-86e1-df89af9dc4b4" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Write here your name: Daniel\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'Daniel'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 58 + } + ], + "source": [ + "name = input(\"Write here your name: \")\n", + "name" + ] + }, + { + "cell_type": "code", + "execution_count": 59, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 52 + }, + "id": "Qa8LTcm2PtVH", + "outputId": "5457be7e-917c-4f1c-eb51-f01d5b07e554" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Write here your number: 41\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'41'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 59 + } + ], + "source": [ + "number = input(\"Write here your number: \")\n", + "number" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "txLJgaIFPtVH" + }, + "source": [ + "When trying to operate with a string representing a number, we'll see that it doesn't behave like a real number. For example, if we try to multiply it by 10 or divide it by 2, we'll get errors or undesired behaviors." + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "dCKGsumVPtVH", + "outputId": "5e0ba5d7-6a91-497f-935b-67bdf135bd94" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'41414141414141414141'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 60 + } + ], + "source": [ + "number * 10" + ] + }, + { + "cell_type": "code", + "execution_count": 61, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 159 + }, + "id": "BTCmgiXAPtVH", + "outputId": "b58e5bb9-44bd-41b1-8bea-e8a3b3cbd7d1" + }, + "outputs": [ + { + "output_type": "error", + "ename": "TypeError", + "evalue": "unsupported operand type(s) for /: 'str' and 'int'", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m/tmp/ipython-input-1563180574.py\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# This will generate an error because we're trying to divide a string.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mnumber\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for /: 'str' and 'int'" + ] + } + ], + "source": [ + "# This will generate an error because we're trying to divide a string.\n", + "number / 2" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "8y9GbUbLPtVH" + }, + "source": [ + "To avoid these problems, we can convert the input to a number using the `int()` function. Once the input is an integer, we can perform numerical operations with it." + ] + }, + { + "cell_type": "code", + "execution_count": 62, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "ajySqcgEPtVH", + "outputId": "f07457dd-5c4d-48fc-9a55-751900571456" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Write here your number: 41\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "41" + ] + }, + "metadata": {}, + "execution_count": 62 + } + ], + "source": [ + "number = int(input(\"Write here your number: \"))\n", + "number" + ] + }, + { + "cell_type": "code", + "execution_count": 63, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "9pXdlQT9PtVH", + "outputId": "b3f2adce-ad48-4145-d288-c84b7b1ee24f" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "int" + ] + }, + "metadata": {}, + "execution_count": 63 + } + ], + "source": [ + "type(number)" + ] + }, + { + "cell_type": "code", + "execution_count": 64, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "8cD_W_SFPtVH", + "outputId": "d1214c06-3a75-42f5-f75f-09bb0cc29a0d" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "20" + ] + }, + "metadata": {}, + "execution_count": 64 + } + ], + "source": [ + "int(number / 2)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "PZnzwye5PtVH" + }, + "source": [ + "**Final Reflections**\n", + "\n", + "It's important to anticipate potential issues in user inputs and manage them properly to avoid errors during execution. One way to do this is through defensive programming, where the validity of inputs is checked before proceeding with operations. Additionally, we can use flow control structures, such as `if/else`, and error handling with `try/except` to handle unexpected situations more elegantly.\n", + "\n", + "Considerations:\n", + "- Anticipate a potential problem -> Defensive programming.\n", + "- Ensure the number is an integer before performing operations that require integers.\n", + "- Use conditional logic (`if/else`) to handle different cases.\n", + "- Proactively handle errors using `try/except` to prevent failures during execution.\n", + "\n", + "### Print\n", + "\n", + "The `print()` function is used to write the specified message to the screen or another standard output device.\n", + "\n", + "The message can be a string or any other object; the object will be converted to a string before being written to the screen. Let's explore some of the functionalities and peculiarities of the `print()` function.\n", + "\n", + "**Observations**:\n", + "\n", + "- **OUR FRIEND**: The `print()` function is a fundamental tool for debugging code. It allows us to visualize the values of different variables at various points in our code, making it easier to identify errors or \"bugs\".\n", + "- **Debugging**: It's the process of identifying and fixing errors in the code. Using `print()` is one of the simplest ways to \"debug\", that is, to search for and fix errors in the code.\n", + "\n", + "Let's see how it works in the following code snippet:" + ] + }, + { + "cell_type": "code", + "execution_count": 65, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "GyHeV0-2PtVH", + "outputId": "03fb16a8-25ff-4bef-c8ca-aae36d5f9917" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "str" + ] + }, + "metadata": {}, + "execution_count": 65 + } + ], + "source": [ + "greeting = \"Hellooooo\"\n", + "type(greeting)" + ] + }, + { + "cell_type": "code", + "execution_count": 66, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "AuJBYaTRPtVH", + "outputId": "ef02d4ad-31a6-4993-92fd-0aca7e285f4a" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Hellooooo\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "NoneType" + ] + }, + "metadata": {}, + "execution_count": 66 + } + ], + "source": [ + "type(print(greeting))" + ] + }, + { + "cell_type": "code", + "execution_count": 67, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "7hXz4WrLPtVH", + "outputId": "904bcbd3-88c1-4d9f-9347-cf184dd41d24" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "str" + ] + }, + "metadata": {}, + "execution_count": 67 + } + ], + "source": [ + "type(greeting)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "RBzFovWqPtVH" + }, + "source": [ + "#### Reflections\n", + "You'll notice that when we use `print()`, the type it returns is `NoneType`. This is because `print()` is a function that performs an action (printing something to the console) but does not return any value (its return is `None`). This is an important distinction, especially when compared with functions that do return values.\n", + "\n", + "#### Warning\n", + "- It's crucial to remember that `print()` prints to the console but does not return a value that can be used in subsequent operations in the code.\n", + "\n", + "## Format\n", + "In this section, we'll explore different ways to format strings in Python, which can be particularly useful when we want to include variable values within a string. There are several ways to do this in Python, including concatenating strings using `+`, using a comma `,`, using the `.format()` method, or through f-strings. Below, we will see examples of each of these methods and analyze the resulting data types." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "zkckihPpPtVH" + }, + "source": [ + "### Format - 1" + ] + }, + { + "cell_type": "code", + "execution_count": 74, + "metadata": { + "id": "hMiNYMC0PtVH" + }, + "outputs": [], + "source": [ + "# First Case: This Could Be a Use Case for Input and Output Functions\n", + "name = \"Danielito\"\n", + "age = 41" + ] + }, + { + "cell_type": "code", + "execution_count": 75, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "ltbrjD8SPtVH", + "outputId": "2e29f669-e320-49e6-b25f-b6bc0d0e94e7" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'Hello my name is Danielito and my age is 41'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 75 + } + ], + "source": [ + "# Using Concatenation with '+'\n", + "greeting = \"Hello my name is \" + name + \" and my age is \" + str(age)\n", + "greeting" + ] + }, + { + "cell_type": "code", + "execution_count": 76, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "chFvMgP6PtVH", + "outputId": "62312741-ae23-4284-d86b-87bdaea67adf" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "('Hello my name is ', 'Danielito', ' and my age is ', '41')" + ] + }, + "metadata": {}, + "execution_count": 76 + } + ], + "source": [ + "# Using a Comma to Concatenate\n", + "greeting = \"Hello my name is \", name, \" and my age is \", str(age)\n", + "greeting" + ] + }, + { + "cell_type": "code", + "execution_count": 77, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "RznAR4PRPtVH", + "outputId": "b1f24bcd-3530-4469-81ad-7183034c809e" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "tuple" + ] + }, + "metadata": {}, + "execution_count": 77 + } + ], + "source": [ + "# Checking the Type of the Variable `greeting`\n", + "type(greeting)" + ] + }, + { + "cell_type": "code", + "execution_count": 78, + "metadata": { + "id": "LSkBzvwkPtVH" + }, + "outputs": [], + "source": [ + "# Adding Some Options to Reflect On What Type of Data We Have Here:\n", + "# 1. String\n", + "# 2. List\n", + "# 3. Tuple\n", + "# 4. CSV: Comma Separated Values?" + ] + }, + { + "cell_type": "code", + "execution_count": 79, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "l8bVqNxOPtVH", + "outputId": "03adc90d-0f97-4b6f-e83e-8667dc27835a" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'Hello my name is Danielito and my age is 41'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 79 + } + ], + "source": [ + "# Using f-strings for cleaner formatting\n", + "greeting = f\"Hello my name is {name} and my age is {age}\"\n", + "greeting" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "M0n5zgqGPtVH" + }, + "source": [ + "### Format - 2" + ] + }, + { + "cell_type": "code", + "execution_count": 80, + "metadata": { + "id": "Jw8E9kcGPtVH" + }, + "outputs": [], + "source": [ + "# Second case:\n", + "name = \"Rio\"\n", + "age = 4" + ] + }, + { + "cell_type": "code", + "execution_count": 81, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "29p5yiuzPtVH", + "outputId": "d60e926a-5fe2-459a-c297-92c94b87a5b5" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'Hello my name is Rio and my age is 4'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 81 + } + ], + "source": [ + "# Using the .format() Method to Insert Values into a String\n", + "greeting = \"Hello my name is {} and my age is {}\".format(name, age)\n", + "greeting" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "38YFlSB5PtVH" + }, + "source": [ + "**Exercise**\n", + "\n", + "Now that we've learned several ways to format strings in Python, it's time to put our knowledge into practice. In this exercise, we'll ask you to use the `input()` function to request certain information from the user, and then format that information using at least two of the methods we've discussed previously (concatenation with '+', using commas, f-strings, or the `.format()` method).\n", + "\n", + "Instructions:\n", + "1. Ask the user to enter their name and age using the `input()` function.\n", + "2. Create a greeting message that includes the user's name and age, using two different string formatting methods.\n", + "3. Print both messages on the console to verify your work." + ] + }, + { + "cell_type": "code", + "execution_count": 83, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "UW9S_UZJPtVH", + "outputId": "c3b05322-3a23-4843-bf00-0a5382cabe65" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Please enter your name: Rio\n", + "Please enter your age: 4\n", + "Hello my name is Rio and I am 4 years old.\n" + ] + } + ], + "source": [ + "name=input(\"Please enter your name: \")\n", + "age=input(\"Please enter your age: \")\n", + "print(f\"Hello my name is {name} and I am {age} years old.\")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "lang": "es", + "id": "xfoGfCJ-PtVH" + }, + "source": [ + "## Strings\n", + "\n", + "In Python, as we've seen before, a string is a sequence of characters enclosed in single (`'`), double (`\"`), or triple (`'''` or `\"\"\"`) quotes. Strings are immutable, which means that once created, we cannot modify their content directly, although we can create new strings from manipulations of the original through various methods and operations. These can contain letters, numbers, special characters, spaces, or a combination of all of them." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "lang": "en", + "id": "k08HQ5XuPtVI" + }, + "source": [ + "### String Methods\n", + "\n", + "Methods are actions or functions that an object can perform. Just as Python offers us a number of \"built-in\" functions, it also provides us with a series of pre-created methods. These methods depend on the type of object we are working with, and in the case of strings, they allow us to perform a variety of operations to manipulate and inspect them.\n", + "\n", + "In this section, we will explore some of the most commonly used string methods during the bootcamp, using a `sample_string` to demonstrate their functionality. As we progress through the bootcamp, it is essential to become familiar with these methods, as they can significantly ease your coding process.\n", + "\n", + "For a more comprehensive view of string methods, feel free to consult the [Python documentation](https://docs.python.org/3/library/stdtypes.html#string-methods). I always use Google :)" + ] + }, + { + "cell_type": "code", + "execution_count": 84, + "metadata": { + "id": "oX7dlbwwPtVI" + }, + "outputs": [], + "source": [ + "sample_string = \"this is a string\"" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "0g869jkgPtVI" + }, + "source": [ + "- `capitalize` Returns a copy of the string with its first character in uppercase and the rest in lowercase. It's ideal for when we want a sentence or title to begin with a more formal touch. Let's try it with the example!" + ] + }, + { + "cell_type": "code", + "execution_count": 85, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "iGNqHnWIPtVI", + "outputId": "08005419-fef6-47b6-92be-fcc1e0804a33" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'This is a string'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 85 + } + ], + "source": [ + "sample_string.capitalize()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "U54IDE_dPtVI" + }, + "source": [ + "- `upper` Returns a copy of the string but with all characters in uppercase. It's perfect for emphasizing something strongly or simply to match the formatting of different texts. Let's put it to the test with a string we have here!" + ] + }, + { + "cell_type": "code", + "execution_count": 86, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "w2YTJwEOPtVI", + "outputId": "49179095-f7a0-4edb-fe33-b809ae960ba1" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'THIS IS A STRING'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 86 + } + ], + "source": [ + "sample_string.upper()" + ] + }, + { + "cell_type": "code", + "execution_count": 87, + "metadata": { + "scrolled": true, + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "Xx6Kw3H4PtVI", + "outputId": "cff21798-881a-4ff0-857e-41f9447d37d7" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "True" + ] + }, + "metadata": {}, + "execution_count": 87 + } + ], + "source": [ + "# We can also check if the string is in upper case format (uppercase letters)\n", + "sample_string.upper().isupper()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "9UCApI10PtVI" + }, + "source": [ + "- `lower` Returns a copy of the string but with all characters in lowercase. This method is great for when we want to maintain uniformity in our text or simply to avoid \"SHOUTING\" in a digital conversation. Let's see how it works with a practical example!" + ] + }, + { + "cell_type": "code", + "execution_count": 88, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "zZZe3JQKPtVI", + "outputId": "6fe5028d-fbed-48e8-98d8-632d808285f0" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'this is a string'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 88 + } + ], + "source": [ + "sample_string.lower()" + ] + }, + { + "cell_type": "code", + "execution_count": 89, + "metadata": { + "scrolled": false, + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "AwTzg0APPtVI", + "outputId": "edb4b6f0-05c7-445a-fb71-56c05e070f62" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "True" + ] + }, + "metadata": {}, + "execution_count": 89 + } + ], + "source": [ + "sample_string.lower().islower()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "hGBV9LroPtVI" + }, + "source": [ + "- `swapcase` This method is like swapping clothes at a costume party: it converts all uppercase characters to lowercase and vice versa in the string. It's especially useful if we want to quickly reverse the capitalization of a text string. Let's try it with an example!" + ] + }, + { + "cell_type": "code", + "execution_count": 90, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "xJ-v0lF8PtVI", + "outputId": "d7ab20ec-5dc3-41be-8376-5848595106dc" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'THIS IS A STRING'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 90 + } + ], + "source": [ + "sample_string.swapcase()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "s3xNkgoOPtVI" + }, + "source": [ + "- `title` This method returns a version of the string where each word starts with an uppercase character, and the rest of the characters are in lowercase. It's as if it turns the string into a book or movie title, giving it a more formal and polished look. Let's see how it works with a practical example!" + ] + }, + { + "cell_type": "code", + "execution_count": 91, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "laZzIJWtPtVI", + "outputId": "37a1219e-a4b1-41d6-c467-2c55758f1b33" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'This Is A String'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 91 + } + ], + "source": [ + "sample_string.title()" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "UHw5HwauPtVI" + }, + "source": [ + "- `join(iterable)` This method returns a string that is the concatenation of the strings in the iterable. It's worth noting that a TypeError will be raised if there are non-string values in the iterable, including bytes objects. The separator between the elements is the string provided by this method. It's an effective way to join multiple strings into one, using a specific separator that the string itself defines. Let's see how we can use it with some examples!" + ] + }, + { + "cell_type": "code", + "execution_count": 92, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "tOM7YDUTPtVI", + "outputId": "fef3e63c-512f-41d7-f43b-861d6c60c9fd" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'Santi 🥸 Clara 🥸 Laura 🥸 Albert'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 92 + } + ], + "source": [ + "# New example\n", + "list_of_strings = [\"Santi\", \"Clara\", \"Laura\", \"Albert\"]\n", + "\" 🥸 \".join(list_of_strings)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "9OfQQ9D6PtVI" + }, + "source": [ + "- `startswith` This method returns `True` if the string starts with the specified prefix; otherwise, it returns `False`. It's interesting to note that the prefix can also be a tuple of prefixes to look for. Moreover, it has two optional parameters: `start`, which allows specifying from which position in the string to start checking, and `end`, which indicates where to stop the check. Let's see some examples to better understand how it works:" + ] + }, + { + "cell_type": "code", + "execution_count": 93, + "metadata": { + "id": "k5Q4MV9dPtVI" + }, + "outputs": [], + "source": [ + "number = \"3434567\"" + ] + }, + { + "cell_type": "code", + "execution_count": 94, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "zOZXgJDZPtVI", + "outputId": "3bcfcf7b-137b-4f9e-ee06-680e82adec57" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "False" + ] + }, + "metadata": {}, + "execution_count": 94 + } + ], + "source": [ + "number.startswith(\"+\")" + ] + }, + { + "cell_type": "code", + "execution_count": 95, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "IVAh-SzdPtVI", + "outputId": "1becab05-22bb-4ec1-e53f-f10a99599541" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "True" + ] + }, + "metadata": {}, + "execution_count": 95 + } + ], + "source": [ + "number.startswith(\"34\")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "KgBiSR5VPtVI" + }, + "source": [ + "- `endswith` This method works similarly to the `startswith` method, but in this case, it checks if the string ends with the specified suffix. If so, it returns `True`; otherwise, it returns `False`. Like `startswith`, this method allows specifying the optional parameters `start` and `end` to define the range of the string to perform the check. Below, we present some examples to illustrate how it works:" + ] + }, + { + "cell_type": "code", + "execution_count": 96, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "IQuRpqtpPtVI", + "outputId": "352e2a1f-2935-44f4-8bd0-274463462cec" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "True" + ] + }, + "metadata": {}, + "execution_count": 96 + } + ], + "source": [ + "number.endswith(\"67\")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "7Mu2PmmaPtVI" + }, + "source": [ + "- `str.lstrip([chars])` This method returns a copy of the original string but without the characters specified in the `chars` argument found at the beginning of it. If no argument is specified (that is, it's omitted or none is present), whitespace will be removed by default. It's important to note that the `chars` argument does not act as a prefix; instead, it removes all possible combinations of the values found within it. Here we show you some examples to better understand how this method works:" + ] + }, + { + "cell_type": "code", + "execution_count": 97, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "DZsa5FHHPtVI", + "outputId": "0805b1fb-03bc-451f-90dc-1505844fa94f" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "##This is an example.\n" + ] + } + ], + "source": [ + "# We define a string with some spaces and characters at the beginning\n", + "original_string = \" ##This is an example.\"\n", + "\n", + "# We use the lstrip method to remove the white spaces at the beginning\n", + "modified_string = original_string.lstrip()\n", + "print(modified_string)\n", + "# Output: \"##This is an example.\"" + ] + }, + { + "cell_type": "code", + "execution_count": 98, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "5MZ80PdVPtVI", + "outputId": "c540c4cc-6639-46ac-92c6-8045873f5a29" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "This is an example.\n" + ] + } + ], + "source": [ + "# We can also use lstrip to remove other characters by specifying an argument\n", + "modified_string2 = original_string.lstrip(\" #\")\n", + "print(modified_string2)\n", + "# Output: \"This is an example.\"" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "K6ZgyjMOPtVI" + }, + "source": [ + "- `lstrip` The `lstrip` method in Python is used to remove unwanted characters found at the beginning of a string. You can use it in two ways: without arguments, which will remove all white spaces at the beginning of the string; or with a specific set of characters as an argument (indicated in parentheses), which will remove all instances of those characters found at the beginning of the string.\n", + "\n", + "- `rstrip` Similarly, the `rstrip` method is used to remove characters at the end of a string. It works in the same way as `lstrip`, but affects the end of the string instead of the beginning. If no set of characters is specified, it will remove all white spaces found at the end of the string.\n", + "\n", + "- `replace` The `replace` method is used to replace all occurrences of a specific substring (`old`) with a new substring (`new`). You can use it in two ways: without the optional `count` argument, which will replace all occurrences found in the string; or by specifying the `count` argument, which will limit the number of replacements to the amount indicated. This method returns a copy of the original string with the substitutions made, leaving the original string intact." + ] + }, + { + "cell_type": "code", + "execution_count": 99, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + }, + "id": "4TY6Je_pPtVI", + "outputId": "9fb17d03-47fa-4d01-c6e3-8c7a1a69a3db" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "' This is an example.'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 99 + } + ], + "source": [ + "original_string.replace(\"#\", \"\")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "id": "qil2_q5YPtVJ" + }, + "source": [ + "- `split` The `split` method is used to divide a string into a list of words based on a specified delimiter (the `sep` parameter). If no delimiter is specified (or is set to `None`), whitespace (spaces, tabs, new lines, etc.) will be used as the default delimiter. This method is especially useful when you want to break down a string into smaller components to perform additional operations or analysis on each individual fragment." + ] + }, + { + "cell_type": "code", + "execution_count": 100, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "FF-w3DwvPtVJ", + "outputId": "3aa2eb1f-9ddd-4f6d-a751-1971e06a08ad" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "['Hello', 'my', 'name', 'is', 'Santo']" + ] + }, + "metadata": {}, + "execution_count": 100 + } + ], + "source": [ + "sentence = \"Hello my name is Santo\"\n", + "sentence.split(\" \")" + ] + }, + { + "cell_type": "code", + "execution_count": 101, + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "zMzlL4i5PtVJ", + "outputId": "1ee96d89-94d6-471d-ab78-48a921deed9c" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "['H', 'llo my nam', ' is Santo']" + ] + }, + "metadata": {}, + "execution_count": 101 + } + ], + "source": [ + "sentence.split(\"e\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "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.9.13" + }, + "nbTranslate": { + "displayLangs": [ + "en", + "es" + ], + "hotkey": "alt-a", + "langInMainMenu": true, + "sourceLang": "es", + "targetLang": "en", + "useGoogleTranslate": true + }, + "toc": { + "base_numbering": 1, + "nav_menu": {}, + "number_sections": true, + "sideBar": true, + "skip_h1_title": true, + "title_cell": "Table of Contents", + "title_sidebar": "Contents", + "toc_cell": true, + "toc_position": { + "height": "calc(100% - 180px)", + "left": "10px", + "top": "150px", + "width": "222.891px" + }, + "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 + }, + "colab": { + "provenance": [] + } + }, + "nbformat": 4, + "nbformat_minor": 0 +} \ No newline at end of file