{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "ULxWGdhVqcRt" }, "source": [ "# Chapter 2: Data Types and Conditional Structures\n", "\n", "```{image} abertura-light.png\n", ":alt: A mosaic of character blocks, each block with a texture and a colour set by the depth of the decision that made it\n", ":class: abertura only-light\n", "```\n", "\n", "```{image} abertura-dark.png\n", ":alt: A mosaic of character blocks, each block with a texture and a colour set by the depth of the decision that made it\n", ":class: abertura only-dark\n", "```" ] }, { "cell_type": "markdown", "metadata": { "id": "euhixBFzp2a9" }, "source": [ "Variables are essential for storing information during program execution. Understanding data types is fundamental for writing functional and readable programs, as each data type is designed to store a specific type of information, such as integers, real numbers, strings, and booleans. Whenever more details about the topics are needed, it's recommended to access the [official Python documentation](https://docs.python.org/3/tutorial/index.html).\n", "\n", "## Defining Variables \n", "\n", "A variable is an identifier that represents a value. Variable declaration is done using the assignment operator (`=`). For example, the following line creates a variable called `name` and assigns the value \"Maria\" to it:\n", "\n", "```python\n", "name = \"Maria\"\n", "```\n", "\n", "
\n", "\n", "To access the value stored in a variable, simply use its name. The following example shows how to print the value stored in the `name` variable:\n", "\n", "```python\n", "name = \"Maria\"\n", "print(name)\n", "```\n", "**Code Output**\n", "```\n", "Maria\n", "```\n", "\n", "### Rules for Naming Variables\n", "\n", "Python has specific rules for creating variable names:\n", "\n", "| Rule | Valid Example | Invalid Example |\n", "|-------|----------------|------------------|\n", "| Must start with letter or `_` | `name`, `_value` | `1name` |\n", "| Can contain letters, numbers and `_` | `grade1`, `total_value` | `total-value` |\n", "| Cannot contain spaces | `my_variable` | `my variable` |\n", "| Case-sensitive | `name` ≠ `Name` | - |\n", "\n", "**Style convention:** In Python, the convention for variable names is to use **snake_case**, that is, lowercase words separated by underscores (`_`).\n", "\n", "```python\n", "# Good practices\n", "user_age = 25\n", "total_value = 100.50\n", "\n", "# Avoid\n", "UserAge = 25 # CamelCase style (used for classes)\n", "```\n", "\n", "\n", "\n", "### Reserved Words\n", "\n", "Python has reserved words that cannot be used as variable names because they have special meanings in the language. Examples include: `if`, `else`, `for`, `while`, `def`, `class`, `return`, `True`, `False`, `None`, among others.\n", "\n", "```python\n", "# This will cause a syntax error\n", "# class = \"Python\" # 'class' is a reserved word\n", "```\n", "\n", "\n", "\n", "```{admonition} Reserved Words\n", ":class: seealso\n", "To see the complete list of reserved words, consult the [official Python documentation](https://docs.python.org/3/reference/lexical_analysis.html#keywords).\n", "```\n", "\n", "The following video demonstrates how to use the Python interpreter in the terminal to create a variable and display its value:\n", "\n", "\n", "\n", "## Formatting Data Output \n", "Let's start with formatting, as this will help in understanding all the following examples. The `print()` function is used to display information on the screen, and can print strings, numbers, and other data types. \n", "\n", "**Displaying a Simple Message** \n", "```python\n", "print(\"Hello, world!\")\n", "```\n", "**Code Output**\n", "```\n", "Hello, world!\n", "```\n", "\n", "**Showing Information Concatenated with Commas** \n", "```python\n", "name = \"Maria\"\n", "age = 30\n", "print(\"Her name is\", name, \"and she is\", age, \"years old.\")\n", "```\n", "**Code Output**\n", "```\n", "Her name is Maria and she is 30 years old.\n", "```\n", "\n", "The following video demonstrates creating variables and using the `print()` function with concatenation:\n", "\n", "\n", "\n", "In this example, the `name` and `age` variables are concatenated with strings and separated by commas to create the final message. `print()` automatically inserts a space between elements.\n", "\n", "**Customizing the Separator (`sep`)** \n", "We can modify the separator using the `sep` argument, which defines what will be inserted between items: \n", "```python\n", "print(\"Maria\", \"30 years\", sep=\" - \")\n", "```\n", "**Code Output**\n", "```\n", "Maria - 30 years\n", "```\n", "By default, the separator is a space (`\" \"`), but we can change it as needed.\n", "\n", "**Using f-strings**\n", "\n", "```python\n", "name = \"Maria\"\n", "age = 30\n", "print(f\"Her name is {name} and she is {age} years old.\")\n", "```\n", "**Code Output**\n", "```\n", "Her name is Maria and she is 30 years old.\n", "```\n", "F-strings allow you to directly incorporate variables into the string, making the code more readable and concise.\n", "\n", "**Displaying Information on Multiple Lines with `\\n`**\n", "\n", "```python\n", "name = \"Maria\"\n", "age = 30\n", "print(\"Her name is\", name, \"\\nand she is\", age, \"years old.\")\n", "\n", "# Using f-string to get the same output\n", "print(f\"Her name is {name}\\nand she is {age} years old.\")\n", "```\n", "**Code Output**\n", "```\n", "Her name is Maria \n", "and she is 30 years old.\n", "```\n", "The line break (`\\n`) is used to format the output on multiple lines.\n", "\n", "**Formatting Numbers with Decimal Places**\n", "\n", "```python\n", "value = 123.456789\n", "print(f\"The formatted value is: {value:.2f}\")\n", "```\n", "\n", "**Code Output**\n", "```\n", "The formatted value is: 123.46\n", "```\n", "\n", "Inside the f-string, `:.2f` describes how the number should **look**: the `f` asks for floating-point notation and the `.2`, for two decimal places. The value stored in `value` stays the same; only what goes to the screen changes.\n", "\n", "The number of places is your choice, and the formatting also pads with zeros when places are missing:\n", "\n", "```python\n", "value = 123.456789\n", "print(f\"{value:.1f}\")\n", "print(f\"{10:.2f}\")\n", "```\n", "\n", "**Code Output**\n", "```\n", "123.5\n", "10.00\n", "```\n", "\n", "The second line is why `:.2f` shows up so often with prices: `10` becomes `10.00`, and a column of values lines up.\n", "\n", "Rounding always goes to the nearest value. The last digit can surprise you when a number looks like it falls exactly halfway, because not every decimal has an exact binary representation. That is the subject of **Floating-Point Precision**, later in this chapter." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Reading Data with `input()`\n", "\n", "The `input()` function allows the program to receive data from the user during execution. It displays a message (optional) and waits until the user types something and presses Enter.\n", "\n", "**Basic Example**\n", "```python\n", "name = input(\"Enter your name: \")\n", "print(f\"Hello, {name}!\")\n", "```\n", "**Code Output**\n", "```\n", "Enter your name: Maria\n", "Hello, Maria!\n", "```\n", "\n", "**Important:** The `input()` function always returns a **string** (`str`), even if the user types a number.\n", "\n", "```python\n", "age = input(\"Enter your age: \")\n", "print(f\"Data type: {type(age)}\")\n", "```\n", "**Code Output**\n", "```\n", "Enter your age: 25\n", "Data type: