{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "ULxWGdhVqcRt" }, "source": [ "# Chapter 3: Operators and Expressions\n", "\n", "```{image} abertura-light.png\n", ":alt: Five circles of points filled with chords linking each point to its multiple, forming cardioid patterns\n", ":class: abertura only-light\n", "```\n", "\n", "```{image} abertura-dark.png\n", ":alt: Five circles of points filled with chords linking each point to its multiple, forming cardioid patterns\n", ":class: abertura only-dark\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We have already seen how to store information in variables and work with different data types. Now it is time to learn how to **manipulate** that information through operators and expressions.\n", "\n", "**Operators** are special symbols that perform operations on values, such as adding two numbers, comparing strings, or combining logical conditions. **Expressions**, in turn, are combinations of values and operators that produce a result.\n", "\n", "Mastering operators and expressions is essential to:\n", "- Perform mathematical calculations of any complexity\n", "- Make decisions based on conditions\n", "- Validate user input\n", "- Manipulate strings, lists, and other collections\n", "- Write more concise and efficient code\n", "\n", "In this chapter we will see the main operators in Python, organized into categories: arithmetic, relational, logical, ternary, membership, assignment, and bitwise. We will also learn how operators interact with each other through **operator precedence**.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Arithmetic Operators\n", "\n", "Arithmetic operators are the first ones we learn in any programming language because they work much like the math we already know. They let us perform mathematical operations on numbers, whether integers or decimals.\n", "\n", "### Arithmetic Operators Table\n", "\n", "Python provides seven basic arithmetic operators. Let's get to know each one:\n", "\n", "| Operator | Symbol | Description | Example | Result |\n", "|---|---|---|---|---|\n", "| **Addition** | `+` | Adds two values | `3 + 5` | `8` |\n", "| **Subtraction** | `-` | Subtracts the second value from the first | `10 - 3` | `7` |\n", "| **Multiplication** | `*` | Multiplies two values | `4 * 2` | `8` |\n", "| **Division** | `/` | Divides the first value by the second (always returns a decimal) | `10 / 2` | `5.0` |\n", "| **Floor Division** | `//` | Divides and returns only the integer part | `10 // 3` | `3` |\n", "| **Modulo** | `%` | Returns the remainder of the division | `10 % 3` | `1` |\n", "| **Exponentiation** | `**` | Raises the first value to the power of the second | `2 ** 3` | `8` |\n", "\n", "### Understanding Each Operator\n", "\n", "Let's explore some of these operators in more detail:\n", "\n", "**Division (`/`) vs Floor Division (`//`)**\n", "\n", "The difference between `/` and `//` matters:\n", "- The `/` operator always returns a decimal number (float), even when the division is exact\n", "- The `//` operator returns only the integer part, discarding the decimal part\n", "\n", "```python\n", "print(10 / 2)\n", "print(10 // 2)\n", "print(10 / 3)\n", "print(10 // 3)\n", "```\n", "\n", "**Output:**\n", "```\n", "5.0\n", "5\n", "3.3333333333333335\n", "3\n", "```\n", "\n", "The figure below shows the three readings of the same division.\n", "\n", "```{image} divisao-euclidiana-light.png\n", ":alt: Two panels. In the first, ten dots grouped three by three, forming three complete groups and leaving one dot over outside them, with the expression 10 floor divided by 3 equals 3 written under the groups and 10 modulo 3 equals 1 written under the leftover. In the second, the equality 10 equals 3 times 3 plus 1, with the words dividend, divisor, quotient and remainder under the matching terms, and below it the line 10 divided by 3 equals 3.3333\n", ":class: only-light\n", "```\n", "\n", "```{image} divisao-euclidiana-dark.png\n", ":alt: Two panels. In the first, ten dots grouped three by three, forming three complete groups and leaving one dot over outside them, with the expression 10 floor divided by 3 equals 3 written under the groups and 10 modulo 3 equals 1 written under the leftover. In the second, the equality 10 equals 3 times 3 plus 1, with the words dividend, divisor, quotient and remainder under the matching terms, and below it the line 10 divided by 3 equals 3.3333\n", ":class: only-dark\n", "```\n", "\n", "**Modulo Operator (`%`)**\n", "\n", "The modulo operator is very useful in many situations:\n", "- Checking whether a number is even or odd\n", "- Determining whether a number is a multiple of another\n", "- Getting the last digit of a number\n", "- Cyclic operations (such as clocks)\n", "\n", "```python\n", "# Check whether a number is even\n", "number = 8\n", "if number % 2 == 0:\n", " print(f\"{number} is even\")\n", "else:\n", " print(f\"{number} is odd\")\n", "\n", "# Get the last digit of a number\n", "value = 12345\n", "last_digit = value % 10\n", "print(f\"Last digit: {last_digit}\")\n", "```\n", "\n", "**Output:**\n", "```\n", "8 is even\n", "Last digit: 5\n", "```\n", "\n", "**Exponentiation Operator (`**`)**\n", "\n", "The `**` operator replaces functions like `pow()` and makes the code more readable:\n", "\n", "```python\n", "# Compute the area of a circle: A = π * r²\n", "radius = 5\n", "PI = 3.14159\n", "area = PI * radius ** 2\n", "print(f\"Circle area: {area:.2f}\")\n", "```\n", "\n", "**Output:**\n", "```\n", "Circle area: 78.54\n", "```\n", "\n", "### Practical Examples\n", "\n", "Let's see examples that combine several operators in everyday situations:\n", "\n", "**Example 1: Shopping calculator with discount**\n", "\n", "```python\n", "original_price = 150.00\n", "quantity = 3\n", "discount_percent = 10\n", "\n", "# Calculations\n", "subtotal = original_price * quantity\n", "discount = subtotal * (discount_percent / 100)\n", "total = subtotal - discount\n", "\n", "print(f\"Subtotal: $ {subtotal:.2f}\")\n", "print(f\"Discount ({discount_percent}%): $ {discount:.2f}\")\n", "print(f\"Total to pay: $ {total:.2f}\")\n", "```\n", "\n", "**Output:**\n", "```\n", "Subtotal: $ 450.00\n", "Discount (10%): $ 45.00\n", "Total to pay: $ 405.00\n", "```\n", "\n", "**Example 2: Time conversion**\n", "\n", "```python\n", "# Convert total seconds into hours, minutes and seconds\n", "total_seconds = 3725\n", "\n", "hours = total_seconds // 3600 # How many full hours\n", "remainder_after_hours = total_seconds % 3600 # Remaining seconds\n", "minutes = remainder_after_hours // 60 # How many full minutes\n", "seconds = remainder_after_hours % 60 # Remaining seconds\n", "\n", "print(f\"{total_seconds} seconds is equivalent to:\")\n", "print(f\"{hours} hour(s), {minutes} minute(s) and {seconds} second(s)\")\n", "```\n", "\n", "**Output:**\n", "```\n", "3725 seconds is equivalent to:\n", "1 hour(s), 2 minute(s) and 5 second(s)\n", "```\n", "\n", "### Precedence of Arithmetic Operators\n", "\n", "Like in math, Python follows a specific order when evaluating expressions. That order is called **operator precedence**:\n", "\n", "| Priority | Operators | Note |\n", "|---|---|---|\n", "| 1st (highest) | `**` | Exponentiation |\n", "| 2nd | `*`, `/`, `//`, `%` | Multiplication, divisions, and modulo |\n", "| 3rd (lowest) | `+`, `-` | Addition and subtraction |\n", "\n", "**Important rules:**\n", "- Operators with the same precedence are evaluated **left to right**\n", "- Use **parentheses `()`** to override the evaluation order\n", "- When in doubt, use parentheses to make the code clearer\n", "\n", "**Precedence examples:**\n", "\n", "```python\n", "# Without parentheses: multiplication before addition\n", "result1 = 2 + 3 * 4\n", "print(result1)\n", "\n", "# With parentheses: we force addition first\n", "result2 = (2 + 3) * 4\n", "print(result2)\n", "\n", "# Complex example\n", "result3 = 2 ** 3 + 4 * 5 - 10 / 2\n", "print(result3)\n", "```\n", "\n", "**Output:**\n", "```\n", "14\n", "20\n", "23.0\n", "```\n", "\n", "### Unary Operators\n", "\n", "Unary operators act on a single value (unlike binary operators, which act on two values). In arithmetic, the most common unary operator is **negation** (`-`), which flips the sign of a number:\n", "\n", "```python\n", "positive_number = 10\n", "negative_number = -positive_number\n", "print(negative_number)\n", "\n", "# Unary operators have high precedence\n", "result = -5 + 2 * 3\n", "print(result)\n", "```\n", "\n", "**Output:**\n", "```\n", "-10\n", "1\n", "```\n", "\n", "**Practical example:**\n", "\n", "```python\n", "# Temperature with a variation\n", "initial_temperature = 25\n", "variation = -3 # Temperature dropped 3 degrees\n", "final_temperature = initial_temperature + variation\n", "print(f\"Initial temperature: {initial_temperature}°C\")\n", "print(f\"Variation: {variation}°C\")\n", "print(f\"Final temperature: {final_temperature}°C\")\n", "```\n", "\n", "**Output:**\n", "```\n", "Initial temperature: 25°C\n", "Variation: -3°C\n", "Final temperature: 22°C\n", "```\n", "\n", "> **Note:** Python has other unary operators, such as bitwise inversion (`~`), which we will see later in the bitwise operations section." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Relational Operators\n", "\n", "Now that we know how to do calculations with arithmetic operators, we need to learn how to **compare values**. That is where relational operators — also known as comparison operators — come in.\n", "\n", "These operators are essential for writing programs that make decisions. For example: checking whether a student passed, whether a product is in stock, whether a password is correct, or whether a user is old enough to access certain content.\n", "\n", "The result of a comparison is always a **boolean** value: `True` or `False`.\n", "\n", "### Relational Operators Table\n", "\n", "| Operator | Symbol | Description | Example | Result |\n", "|---|---|---|---|---|\n", "| **Equality** | `==` | Checks whether two values are equal | `5 == 5` | `True` |\n", "| **Inequality** | `!=` | Checks whether two values are different | `5 != 3` | `True` |\n", "| **Less than** | `<` | Checks whether the first is less than the second | `3 < 5` | `True` |\n", "| **Greater than** | `>` | Checks whether the first is greater than the second | `3 > 5` | `False` |\n", "| **Less than or equal** | `<=` | Checks whether the first is less than or equal to the second | `3 <= 5` | `True` |\n", "| **Greater than or equal** | `>=` | Checks whether the first is greater than or equal to the second | `5 >= 5` | `True` |\n", "\n", "```{admonition} Warning - Equality vs Assignment\n", ":class: warning\n", "Don't confuse the equality operator `==` (two equal signs) with the assignment operator `=` (one equal sign). The first **compares** values, the second **assigns** values!\n", "```\n", "\n", "### Basic Examples\n", "\n", "Let's see how to use these operators in practice:\n", "\n", "```python\n", "# Comparing numbers\n", "grade = 7.5\n", "average = 6.0\n", "\n", "print(f\"Grade equal to average? {grade == average}\")\n", "print(f\"Grade different from average? {grade != average}\")\n", "print(f\"Grade greater than average? {grade > average}\")\n", "print(f\"Grade greater than or equal to 7? {grade >= 7}\")\n", "print(f\"Grade less than 5? {grade < 5}\")\n", "```\n", "\n", "**Output:**\n", "```\n", "Grade equal to average? False\n", "Grade different from average? True\n", "Grade greater than average? True\n", "Grade greater than or equal to 7? True\n", "Grade less than 5? False\n", "```\n", "\n", "### String Comparison\n", "\n", "Comparisons don't only work with numbers. We can also compare strings! The comparison follows **lexicographic order** (alphabetical order), based on the Unicode values of the characters.\n", "\n", "```python\n", "name1 = \"Anna\"\n", "name2 = \"Bruno\"\n", "name3 = \"Anna\"\n", "\n", "print(f\"'{name1}' is equal to '{name3}'? {name1 == name3}\")\n", "print(f\"'{name1}' is different from '{name2}'? {name1 != name2}\")\n", "print(f\"'{name1}' comes before '{name2}'? {name1 < name2}\")\n", "```\n", "\n", "**Output:**\n", "```\n", "'Anna' is equal to 'Anna'? True\n", "'Anna' is different from 'Bruno'? True\n", "'Anna' comes before 'Bruno'? True\n", "```\n", "\n", "**Important points about string comparison:**\n", "- Comparison is **case-sensitive**: `\"Python\" != \"python\"`\n", "- Uppercase letters come before lowercase ones in Unicode order\n", "- To ignore case, convert the strings: `text.lower()` or `text.upper()`\n", "\n", "```python\n", "# Case-sensitive comparison\n", "print(\"Python\" == \"python\")\n", "\n", "# Case-insensitive comparison\n", "text1 = \"Python\"\n", "text2 = \"python\"\n", "print(text1.lower() == text2.lower())\n", "```\n", "\n", "**Output:**\n", "```\n", "False\n", "True\n", "```\n", "\n", "### Practical Examples\n", "\n", "**Example 1: Student approval system**\n", "\n", "```python\n", "final_grade = float(input(\"Enter the student's final grade: \"))\n", "minimum_average = 7.0\n", "\n", "if final_grade >= minimum_average:\n", " print(f\"Student PASSED with grade {final_grade}\")\n", "else:\n", " print(f\"Student FAILED with grade {final_grade}\")\n", "```\n", "\n", "**Sample run:**\n", "```\n", "Enter the student's final grade: 8.5\n", "Student PASSED with grade 8.5\n", "```\n", "\n", "**Example 2: Age validation**\n", "\n", "```python\n", "age = int(input(\"Enter your age: \"))\n", "minimum_age = 18\n", "\n", "if age >= minimum_age:\n", " print(\"Access granted.\")\n", "else:\n", " years_remaining = minimum_age - age\n", " print(f\"Access denied. You must be at least {minimum_age} years old.\")\n", " print(f\"{years_remaining} year(s) remaining.\")\n", "```\n", "\n", "**Sample run:**\n", "```\n", "Enter your age: 16\n", "Access denied. You must be at least 18 years old.\n", "2 year(s) remaining.\n", "```\n", "\n", "**Example 3: Login validation**\n", "\n", "```python\n", "correct_user = \"admin\"\n", "correct_password = \"1234\"\n", "\n", "user = input(\"Username: \")\n", "password = input(\"Password: \")\n", "\n", "if user == correct_user and password == correct_password:\n", " print(\"Login successful!\")\n", "else:\n", " print(\"Incorrect username or password.\")\n", "```\n", "\n", "**Sample run:**\n", "```\n", "Username: admin\n", "Password: 1234\n", "Login successful!\n", "```\n", "\n", "### Combining Comparisons\n", "\n", "Relational operators are often used with conditional structures (`if`, `elif`, `else`) and can be combined with logical operators (`and`, `or`, `not`), which we will see in the next section.\n", "\n", "Relational operators are the foundation for building intelligent programs that make decisions. They work together with conditional structures to control program flow based on different situations.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Logical Operators\n", "\n", "We saw that relational operators let us make simple comparisons. But what if we need to check **multiple conditions at the same time**? For example: \"Is the user older than 18 **AND** does she have a driver's license?\" or \"Was the payment made by card **OR** by PIX?\".\n", "\n", "For those situations, we use **logical operators**. They let us combine several boolean conditions into a single expression, building more complex and powerful logic.\n", "\n", "### Logical Operators Table\n", "\n", "| Operator | Symbol | Description | Example | Result | Precedence |\n", "|---|---|---|---|---|---|\n", "| **Logical AND** | `and` | Returns `True` only if **both** conditions are true | `True and False` | `False` | Medium |\n", "| **Logical OR** | `or` | Returns `True` if **at least one** of the conditions is true | `True or False` | `True` | Low |\n", "| **Negation** | `not` | Inverts the boolean value | `not True` | `False` | High |\n", "\n", "### Understanding Each Operator\n", "\n", "**`and` Operator (Logical AND)**\n", "\n", "The `and` operator requires **all** conditions to be true:\n", "\n", "```python\n", "age = 20\n", "has_license = True\n", "\n", "can_drive = (age >= 18) and has_license\n", "print(can_drive)\n", "```\n", "\n", "**Output:**\n", "```\n", "True\n", "```\n", "\n", "**Truth Table for `and`:**\n", "\n", "| Condition A | Condition B | A and B |\n", "|------------|------------|---------|\n", "| `True` | `True` | `True` |\n", "| `True` | `False` | `False` |\n", "| `False` | `True` | `False` |\n", "| `False` | `False` | `False` |\n", "\n", "**`or` Operator (Logical OR)**\n", "\n", "The `or` operator needs **at least one** condition to be true:\n", "\n", "```python\n", "has_card = False\n", "has_cash = True\n", "\n", "can_pay = has_card or has_cash\n", "print(can_pay)\n", "```\n", "\n", "**Output:**\n", "```\n", "True\n", "```\n", "\n", "**Truth Table for `or`:**\n", "\n", "| Condition A | Condition B | A or B |\n", "|------------|------------|---------|\n", "| `True` | `True` | `True` |\n", "| `True` | `False` | `True` |\n", "| `False` | `True` | `True` |\n", "| `False` | `False` | `False` |\n", "\n", "**`not` Operator (Negation)**\n", "\n", "The `not` operator inverts the boolean value:\n", "\n", "```python\n", "is_raining = False\n", "go_running = not is_raining\n", "print(go_running)\n", "```\n", "\n", "**Output:**\n", "```\n", "True\n", "```\n", "\n", "**Truth Table for `not`:**\n", "\n", "| Condition | not Condition |\n", "|----------|--------------|\n", "| `True` | `False` |\n", "| `False` | `True` |\n", "\n", "### Precedence of Logical Operators\n", "\n", "When we combine multiple logical operators, they are evaluated in this order:\n", "1. **`not`** (highest precedence)\n", "2. **`and`** (medium precedence)\n", "3. **`or`** (lowest precedence)\n", "\n", "```python\n", "# Example without parentheses\n", "result1 = True or True and False\n", "print(result1)\n", "\n", "# Example with parentheses (we change the order)\n", "result2 = (True or True) and False\n", "print(result2)\n", "```\n", "\n", "**Output:**\n", "```\n", "True\n", "False\n", "```\n", "\n", "```{admonition} Tip - Code Clarity\n", ":class: tip\n", "Even when not required, use parentheses to make your expressions clearer and easier to read!\n", "```\n", "\n", "### Practical Examples\n", "\n", "**Example 1: Check whether a number is in a range**\n", "\n", "```python\n", "grade = float(input(\"Enter the grade (0-10): \"))\n", "\n", "# Check whether the grade is between 0 and 10\n", "valid_grade = (grade >= 0) and (grade <= 10)\n", "\n", "if valid_grade:\n", " print(f\"Grade {grade} is valid!\")\n", "else:\n", " print(f\"Grade {grade} is invalid! Enter a value between 0 and 10.\")\n", "```\n", "\n", "**Sample run:**\n", "```\n", "Enter the grade (0-10): 8.5\n", "Grade 8.5 is valid!\n", "```\n", "\n", "**Example 2: Checking multiple payment methods**\n", "\n", "```python\n", "payment_method = input(\"Payment method (card/cash/pix): \").lower()\n", "\n", "# Accepts any of the three methods\n", "payment_accepted = (payment_method == \"card\") or \\\n", " (payment_method == \"cash\") or \\\n", " (payment_method == \"pix\")\n", "\n", "if payment_accepted:\n", " print(\"Payment accepted!\")\n", "else:\n", " print(\"Payment method not accepted.\")\n", "```\n", "\n", "**Sample run:**\n", "```\n", "Payment method (card/cash/pix): pix\n", "Payment accepted!\n", "```\n", "\n", "**Example 3: Access system with multiple validations**\n", "\n", "```python\n", "age = int(input(\"Enter your age: \"))\n", "has_authorization = input(\"Do you have parental authorization? (yes/no): \").lower() == \"yes\"\n", "\n", "# Can enter if: age 18+ OR (under 18 BUT has authorization)\n", "can_enter = (age >= 18) or (age < 18 and has_authorization)\n", "\n", "if can_enter:\n", " print(\"Access granted!\")\n", "else:\n", " print(\"Access denied. People under 18 need authorization.\")\n", "```\n", "\n", "**Sample run:**\n", "```\n", "Enter your age: 16\n", "Do you have parental authorization? (yes/no): yes\n", "Access granted!\n", "```\n", "\n", "**Example 4: Strong-password validation**\n", "\n", "```python\n", "password = input(\"Enter your password: \")\n", "\n", "# Criteria for a strong password\n", "has_min_chars = len(password) >= 8\n", "has_digit = any(char.isdigit() for char in password)\n", "has_letter = any(char.isalpha() for char in password)\n", "\n", "# Password is strong if it meets ALL criteria\n", "strong_password = has_min_chars and has_digit and has_letter\n", "\n", "if strong_password:\n", " print(\"Strong password! Registration successful.\")\n", "else:\n", " print(\"Weak password! Use at least 8 characters, including letters and numbers.\")\n", "```\n", "\n", "**Sample run:**\n", "```\n", "Enter your password: python123\n", "Strong password! Registration successful.\n", "```\n", "\n", "**Example 5: Using `not` to invert a condition**\n", "\n", "```python\n", "age = int(input(\"Enter your age: \"))\n", "\n", "# Check whether NOT of legal age\n", "if not (age >= 18):\n", " print(\"You are a minor.\")\n", "else:\n", " print(\"You are an adult.\")\n", "```\n", "\n", "**Sample run:**\n", "```\n", "Enter your age: 16\n", "You are a minor.\n", "```\n", "\n", "### Simplifying Logical Expressions\n", "\n", "Sometimes we can simplify our logical expressions. For example:\n", "\n", "```python\n", "x = 5\n", "# More verbose form\n", "if (x > 0) == True:\n", " print(\"Positive\")\n", "\n", "# Simplified form (better)\n", "if x > 0:\n", " print(\"Positive\")\n", "\n", "# Another example\n", "age = 20\n", "# More verbose form\n", "if not (age < 18):\n", " print(\"Adult\")\n", "\n", "# Simplified form (better)\n", "if age >= 18:\n", " print(\"Adult\")\n", "```\n", "\n", "### Putting It All Together\n", "\n", "Logical operators are extremely powerful when combined with relational operators:\n", "\n", "```python\n", "# Store discount system\n", "purchase_value = float(input(\"Purchase value: $ \"))\n", "is_vip_customer = input(\"Is a VIP customer? (yes/no): \").lower() == \"yes\"\n", "first_purchase = input(\"Is this the first purchase? (yes/no): \").lower() == \"yes\"\n", "\n", "# 20% discount for VIP OR first purchase above $ 100\n", "has_discount = is_vip_customer or (first_purchase and purchase_value > 100)\n", "\n", "if has_discount:\n", " final_value = purchase_value * 0.8 # 20% discount\n", " print(f\"You got a 20% discount!\")\n", " print(f\"Final value: $ {final_value:.2f}\")\n", "else:\n", " print(f\"Final value: $ {purchase_value:.2f}\")\n", "```\n", "\n", "Logical operators are essential for building programs that make complex decisions based on multiple conditions. Mastering them lets you write more sophisticated code and solve real-world problems!\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Ternary Operator (Conditional Expression)\n", "\n", "When you need to **choose between two values** depending on a condition, Python offers the **ternary operator**, also called a **conditional expression**. It lets you write in **a single line** what we would normally do with `if/else` across multiple lines.\n", "\n", "### Syntax\n", "\n", "```text\n", "value_if_true if condition else value_if_false\n", "```\n", "\n", "The reading is direct: \"use `value_if_true` **if** the condition is true, **otherwise** use `value_if_false`\".\n", "\n", "### Basic Example\n", "\n", "Suppose we want to classify a number as \"even\" or \"odd\":\n", "\n", "```python\n", "number = 10\n", "classification = \"even\" if number % 2 == 0 else \"odd\"\n", "print(f\"{number} is {classification}\")\n", "```\n", "\n", "**Output:**\n", "```\n", "10 is even\n", "```\n", "\n", "The equivalent block `if/else` version would be longer:\n", "\n", "```python\n", "number = 10\n", "if number % 2 == 0:\n", " classification = \"even\"\n", "else:\n", " classification = \"odd\"\n", "print(f\"{number} is {classification}\")\n", "```\n", "\n", "Both forms produce the same result — the ternary just condenses the logic into a single expression that **produces a value**.\n", "\n", "The figure below shows the three operands and the order Python evaluates them in.\n", "\n", "```{image} ternario-light.png\n", ":alt: Two panels. In the first, the expression even if number modulo 2 equals zero else odd, with brackets under the three operands and numbered dots above them, the number one over the condition in the middle of the line, the two over the left value and the three over the right value. Two arrows leave the condition below the line and rise to each of the values, labelled True on the left and False on the right. In the second panel, the same expression with the number ten in place of the variable, the condition evaluating to True, the right value dimmed and a straight arrow going down from the left value to the word even\n", ":class: only-light\n", "```\n", "\n", "```{image} ternario-dark.png\n", ":alt: Two panels. In the first, the expression even if number modulo 2 equals zero else odd, with brackets under the three operands and numbered dots above them, the number one over the condition in the middle of the line, the two over the left value and the three over the right value. Two arrows leave the condition below the line and rise to each of the values, labelled True on the left and False on the right. In the second panel, the same expression with the number ten in place of the variable, the condition evaluating to True, the right value dimmed and a straight arrow going down from the left value to the word even\n", ":class: only-dark\n", "```\n", "\n", "### Why Is It Called \"Ternary\"?\n", "\n", "Most operators we have seen so far are **binary** (they act on two values: `2 + 3`, `x and y`). We have also seen **unary** operators (acting on a single value: `-x`, `not x`). The **ternary** operator acts on **three operands**: the value returned when the condition is true, the condition itself, and the value returned when the condition is false.\n", "\n", "### More Examples\n", "\n", "**Example 1: Discount based on a minimum amount**\n", "\n", "```python\n", "purchase_amount = 250\n", "discount = 0.10 if purchase_amount > 200 else 0.05\n", "print(f\"Discount: {discount * 100:.0f}%\")\n", "```\n", "\n", "**Output:**\n", "```\n", "Discount: 10%\n", "```\n", "\n", "**Example 2: Pass/fail message**\n", "\n", "```python\n", "grade = 7.5\n", "result = \"Approved\" if grade >= 6 else \"Failed\"\n", "print(result)\n", "```\n", "\n", "**Output:**\n", "```\n", "Approved\n", "```\n", "\n", "**Example 3: Absolute value without `abs()`**\n", "\n", "```python\n", "x = -8\n", "modulus = x if x >= 0 else -x\n", "print(modulus)\n", "```\n", "\n", "**Output:**\n", "```\n", "8\n", "```\n", "\n", "### Nesting (Use With Care)\n", "\n", "Ternaries can be chained, but readability drops fast. When you need more than two options, prefer block `if/elif/else` (which we will see in the next chapter):\n", "\n", "```python\n", "grade = 8.5\n", "concept = \"A\" if grade >= 9 else \"B\" if grade >= 7 else \"C\" if grade >= 5 else \"D\"\n", "print(concept)\n", "```\n", "\n", "**Output:**\n", "```\n", "B\n", "```\n", "\n", "**How to read the chain.** The `else` of a ternary accepts any expression, and a ternary is an expression. So what comes after the first `else` is **another whole ternary**, and so on. Writing the parentheses Python assumes makes it visible:\n", "\n", "```text\n", "\"A\" if grade >= 9 else (\"B\" if grade >= 7 else (\"C\" if grade >= 5 else \"D\"))\n", "```\n", "\n", "Evaluation follows the same rule as the basic example, one level at a time: it tests `grade >= 9`; since that is false, the value of the expression becomes the ternary inside the first parentheses, which tests `grade >= 7`. Since `8.5 >= 7` is true, the result is `\"B\"` and the remaining levels are never even read.\n", "\n", "**The same decision as a block.** Each `else` followed by a new ternary becomes an `elif`, and the last `else` stays as the final `else`:\n", "\n", "```python\n", "grade = 8.5\n", "if grade >= 9:\n", " concept = \"A\"\n", "elif grade >= 7:\n", " concept = \"B\"\n", "elif grade >= 5:\n", " concept = \"C\"\n", "else:\n", " concept = \"D\"\n", "print(concept)\n", "```\n", "\n", "**Output:**\n", "```\n", "B\n", "```\n", "\n", "Both forms produce the same result for any grade. The difference is that the block version puts each condition at the start of a line, in the order they are tested, while the chained one forces you to read to the end to find out how many levels there are.\n", "\n", "```{admonition} Tip - When to use the ternary\n", ":class: tip\n", "- **Use it** when the choice between two values fits comfortably on one line and makes the code more direct.\n", "- **Avoid it** when the condition or the values are long — block `if/else` reads better.\n", "- Remember that the ternary is an **expression** (it produces a value that can be assigned or passed to a function), while block `if/else` is a **statement** (it executes code). This difference becomes important in the next chapter, when we combine ternaries with list comprehensions.\n", "```\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Membership Operators\n", "\n", "So far, we have learned how to do calculations, comparisons, and combine conditions. But we often need to check whether an element **belongs** or **does not belong** to a collection of data. For example: checking whether a letter is in a word, whether a name is in a list of approved candidates, or whether a product is available in stock.\n", "\n", "For these situations, Python provides the **membership operators**: `in` and `not in`.\n", "\n", "### Membership Operators Table\n", "\n", "| Operator | Symbol | Description | Example | Result |\n", "|---|---|---|---|---|\n", "| **Member of** | `in` | Checks if a value is present in the sequence | `'a' in 'python'` | `False` |\n", "| **Not member of** | `not in` | Checks if a value is not present in the sequence | `'a' not in 'python'` | `True` |\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", " \n", "

Visual demonstration of the in and not in operators

\n", "
\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Supported Sequence Types\n", "\n", "Membership operators work with several types of collections:\n", "- **Strings**: check whether a letter or word is contained\n", "- **Lists**: check whether an element exists in the list\n", "- **Tuples**: check membership in tuples\n", "- **Sets**: check membership (very efficient)\n", "- **Dictionaries**: check whether a key exists (not values!)\n", "\n", "### Basic Examples\n", "\n", "**Checking in strings:**\n", "\n", "```python\n", "phrase = \"Python is amazing\"\n", "\n", "print('P' in phrase)\n", "print('Java' in phrase)\n", "print('python' in phrase)\n", "print('Python' in phrase)\n", "\n", "# Ignoring upper/lowercase\n", "print('python' in phrase.lower())\n", "```\n", "\n", "**Output:**\n", "```\n", "True\n", "False\n", "False\n", "True\n", "True\n", "```\n", "\n", "**Checking in lists:**\n", "\n", "```python\n", "fruits = ['apple', 'banana', 'orange', 'grape']\n", "\n", "print('banana' in fruits)\n", "print('watermelon' in fruits)\n", "print('watermelon' not in fruits)\n", "```\n", "\n", "**Output:**\n", "```\n", "True\n", "False\n", "True\n", "```\n", "\n", "**Checking in dictionaries:**\n", "\n", "```python\n", "stock = {'rice': 50, 'beans': 30, 'pasta': 40}\n", "\n", "# Checks the KEYS (not the values)\n", "print('rice' in stock)\n", "print('sugar' in stock)\n", "print(50 in stock)\n", "```\n", "\n", "**Output:**\n", "```\n", "True\n", "False\n", "False\n", "```\n", "\n", "### Practical Examples\n", "\n", "**Example 1: Vowel validation**\n", "\n", "```python\n", "letter = input(\"Enter a letter: \").lower()\n", "vowels = 'aeiou'\n", "\n", "if letter in vowels:\n", " print(f\"'{letter}' is a vowel.\")\n", "else:\n", " print(f\"'{letter}' is a consonant.\")\n", "```\n", "\n", "**Sample run:**\n", "```\n", "Enter a letter: A\n", "'a' is a vowel.\n", "```\n", "\n", "**Example 2: Menu of options**\n", "\n", "```python\n", "valid_options = ['1', '2', '3', '4', 'exit']\n", "option = input(\"Choose an option (1-4 or 'exit'): \")\n", "\n", "if option in valid_options:\n", " print(f\"You chose: {option}\")\n", "else:\n", " print(\"Invalid option! Please try again.\")\n", "```\n", "\n", "**Sample run:**\n", "```\n", "Choose an option (1-4 or 'exit'): 2\n", "You chose: 2\n", "```\n", "\n", "**Example 3: Permissions list (blacklist/whitelist)**\n", "\n", "```python\n", "blocked_users = ['spam_user', 'bot123', 'fake_account']\n", "user = input(\"Enter your username: \").lower()\n", "\n", "if user in blocked_users:\n", " print(\"Access denied! User is blocked.\")\n", "else:\n", " print(\"Welcome!\")\n", "```\n", "\n", "**Sample run:**\n", "```\n", "Enter your username: bot123\n", "Access denied! User is blocked.\n", "```\n", "\n", "**Example 4: Checking multiple keywords**\n", "\n", "```python\n", "text = input(\"Enter a sentence: \").lower()\n", "forbidden_words = ['spam', 'scam', 'fraud']\n", "\n", "# Check whether any forbidden word is in the text\n", "contains_spam = any(word in text for word in forbidden_words)\n", "\n", "if contains_spam:\n", " print(\"Message blocked! It contains forbidden terms.\")\n", "else:\n", " print(\"Message sent successfully!\")\n", "```\n", "\n", "**Sample run:**\n", "```\n", "Enter a sentence: Special offer with no scam\n", "Message blocked! It contains forbidden terms.\n", "```\n", "\n", "**Example 5: Department-based access control**\n", "\n", "```python\n", "# Access levels by department\n", "admin_departments = ['IT', 'HR', 'Board']\n", "department = input(\"Enter your department: \")\n", "\n", "if department in admin_departments:\n", " print(f\"ADMINISTRATOR access granted for {department}\")\n", "else:\n", " print(f\"USER access granted for {department}\")\n", "```\n", "\n", "**Sample run:**\n", "```\n", "Enter your department: IT\n", "ADMINISTRATOR access granted for IT\n", "```\n", "\n", "### Difference Between `in` for Strings and Lists\n", "\n", "It is important to understand how `in` behaves differently in strings and lists:\n", "\n", "```python\n", "# In strings: checks for a substring\n", "print('ana' in 'banana')\n", "\n", "# In lists: checks for the full element\n", "print('ana' in ['ba', 'na', 'na'])\n", "print('na' in ['ba', 'na', 'na'])\n", "```\n", "\n", "**Output:**\n", "```\n", "True\n", "False\n", "True\n", "```\n", "\n", "### Combining With Other Operators\n", "\n", "Membership operators work well combined with logical operators:\n", "\n", "```python\n", "# Movie rating system\n", "age = int(input(\"Enter your age: \"))\n", "movie = input(\"Enter the movie name: \")\n", "\n", "adult_movies = ['Movie A', 'Movie B', 'Movie C']\n", "\n", "# Can watch if: NOT an adult movie OR age 18+\n", "can_watch = (movie not in adult_movies) or (age >= 18)\n", "\n", "if can_watch:\n", " print(f\"You can watch '{movie}'\")\n", "else:\n", " print(f\"You cannot watch '{movie}' - rated 18+\")\n", "```\n", "\n", "**Sample run:**\n", "```\n", "Enter your age: 16\n", "Enter the movie name: Kids Movie\n", "You can watch 'Kids Movie'\n", "```\n", "\n", "### Important Notes\n", "\n", "**Case-Sensitive:**\n", "\n", "The check distinguishes upper from lowercase:\n", "```python\n", "print('Python' in 'python')\n", "print('Python'.lower() in 'python')\n", "```\n", "\n", "**Output:**\n", "```\n", "False\n", "True\n", "```\n", "\n", "**In Dictionaries:**\n", "\n", "The `in` operator checks only the **keys**, not the values:\n", "```python\n", "data = {'name': 'John', 'age': 25}\n", "print('name' in data)\n", "print('John' in data)\n", "print('John' in data.values())\n", "```\n", "\n", "**Output:**\n", "```\n", "True\n", "False\n", "True\n", "```\n", "\n", "**Strings and Substrings:**\n", "\n", "In strings, `in` finds substrings, not just individual characters:\n", "```python\n", "print('thon' in 'Python')\n", "```\n", "\n", "**Output:**\n", "```\n", "True\n", "```\n", "\n", "Membership operators are extremely useful for validations, filters, and membership checks, making code cleaner and more readable!\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Assignment Operators\n", "\n", "We have already seen the simple assignment operator (`=`) when declaring variables. But Python offers **combined** assignment operators that make our code more concise and efficient. These operators perform an operation and assign the result to the variable in a single step.\n", "\n", "### Assignment Operators Table\n", "\n", "| Operator | Description | Example | Equivalent | Result |\n", "|---|---|---|---|---|\n", "| `=` | Simple assignment | `x = 5` | - | `x` receives `5` |\n", "| `+=` | Add and assign | `x += 3` | `x = x + 3` | `x` is incremented by `3` |\n", "| `-=` | Subtract and assign | `x -= 2` | `x = x - 2` | `x` is decremented by `2` |\n", "| `*=` | Multiply and assign | `x *= 4` | `x = x * 4` | `x` is multiplied by `4` |\n", "| `/=` | Divide and assign | `x /= 2` | `x = x / 2` | `x` is divided by `2` |\n", "| `//=` | Integer divide and assign | `x //= 3` | `x = x // 3` | `x` receives the integer division by `3` |\n", "| `%=` | Modulo and assign | `x %= 5` | `x = x % 5` | `x` receives the remainder of division by `5` |\n", "| `**=` | Exponentiate and assign | `x **= 2` | `x = x ** 2` | `x` is squared |\n", "\n", "### Why Use Combined Assignment Operators?\n", "\n", "Combined operators make code:\n", "- **Shorter**: less typing\n", "- **More readable**: clearer intent\n", "- **More efficient**: in some cases, can be optimized by the interpreter\n", "\n", "```python\n", "# Traditional form\n", "counter = 0\n", "counter = counter + 1\n", "print(counter)\n", "\n", "# Combined operator form (better)\n", "counter = 0\n", "counter += 1\n", "print(counter)\n", "```\n", "\n", "**Output:**\n", "```\n", "1\n", "1\n", "```\n", "\n", "### Basic Examples\n", "\n", "**Increment and Decrement:**\n", "\n", "```python\n", "# Increment\n", "points = 10\n", "points += 5\n", "print(f\"Points: {points}\")\n", "\n", "# Decrement\n", "lives = 3\n", "lives -= 1\n", "print(f\"Lives remaining: {lives}\")\n", "```\n", "\n", "**Output:**\n", "```\n", "Points: 15\n", "Lives remaining: 2\n", "```\n", "\n", "**Math Operations:**\n", "\n", "```python\n", "# Multiplication\n", "price = 50.0\n", "price *= 2\n", "print(f\"Price: $ {price}\")\n", "\n", "# Division\n", "amount = 100\n", "amount /= 4\n", "print(f\"Amount: {amount}\")\n", "\n", "# Exponentiation\n", "base = 2\n", "base **= 3\n", "print(f\"Result: {base}\")\n", "```\n", "\n", "**Output:**\n", "```\n", "Price: $ 100.0\n", "Amount: 25.0\n", "Result: 8\n", "```\n", "\n", "### Practical Examples\n", "\n", "**Example 1: Game scoring system**\n", "\n", "```python\n", "points = 0\n", "print(f\"Initial points: {points}\")\n", "\n", "# Player answers an easy question correctly\n", "points += 10\n", "print(f\"Easy question right! Points: {points}\")\n", "\n", "# Player answers a hard question correctly\n", "points += 50\n", "print(f\"Hard question right! Points: {points}\")\n", "\n", "# Player uses a hint (loses half of the points)\n", "points //= 2\n", "print(f\"Used hint! Points: {points}\")\n", "```\n", "\n", "**Output:**\n", "```\n", "Initial points: 0\n", "Easy question right! Points: 10\n", "Hard question right! Points: 60\n", "Used hint! Points: 30\n", "```\n", "\n", "**Example 2: Compound interest calculation**\n", "\n", "```python\n", "initial_capital = float(input(\"Initial capital: $ \"))\n", "interest_rate = float(input(\"Interest rate (% per month): \"))\n", "months = int(input(\"Number of months: \"))\n", "\n", "capital = initial_capital * (1 + interest_rate / 100) ** months\n", "\n", "print(f\"Final capital: $ {capital:.2f}\")\n", "print(f\"Profit: $ {capital - initial_capital:.2f}\")\n", "```\n", "\n", "**Sample run:**\n", "```\n", "Initial capital: $ 1000\n", "Interest rate (% per month): 5\n", "Number of months: 3\n", "Final capital: $ 1157.63\n", "Profit: $ 157.63\n", "```\n", "\n", "The `**` exponent applies all three months of interest at once. To follow the value month by month, instead of only the total, you need repetition, which we will see in the next chapter.\n", "\n", "**Example 3: Character counter**\n", "\n", "This example uses `for` to walk through the text one character at a time. Do not worry about the repetition syntax now: it is the subject of the [`for` Loop Structure](https://heltonmaia.com/pythonbook_en/chapters/ch4/ch4.html#for-loop-structure) in the next chapter.\n", "\n", "```python\n", "text = input(\"Enter some text: \")\n", "\n", "vowels = 0\n", "consonants = 0\n", "spaces = 0\n", "\n", "for char in text.lower():\n", " if char in 'aeiou':\n", " vowels += 1\n", " elif char.isalpha():\n", " consonants += 1\n", " elif char == ' ':\n", " spaces += 1\n", "\n", "print(f\"Vowels: {vowels}\")\n", "print(f\"Consonants: {consonants}\")\n", "print(f\"Spaces: {spaces}\")\n", "```\n", "\n", "**Sample run:**\n", "```\n", "Enter some text: Python is amazing\n", "Vowels: 6\n", "Consonants: 9\n", "Spaces: 2\n", "```\n", "\n", "**Example 4: Progressive discount calculator**\n", "\n", "```python\n", "original_price = float(input(\"Product price: $ \"))\n", "quantity = int(input(\"Quantity: \"))\n", "\n", "# Progressive discount by quantity\n", "discount_percent = 0\n", "\n", "if quantity >= 10:\n", " discount_percent += 10\n", "if quantity >= 20:\n", " discount_percent += 5\n", "if quantity >= 50:\n", " discount_percent += 10\n", "\n", "total_price = original_price * quantity\n", "total_price *= (1 - discount_percent / 100)\n", "\n", "print(f\"\\nOriginal price: $ {original_price * quantity:.2f}\")\n", "print(f\"Discount: {discount_percent}%\")\n", "print(f\"Final price: $ {total_price:.2f}\")\n", "```\n", "\n", "**Sample run:**\n", "```\n", "Product price: $ 50\n", "Quantity: 25\n", "\n", "Original price: $ 1250.00\n", "Discount: 15%\n", "Final price: $ 1062.50\n", "```\n", "\n", "### Assignment Operators with Strings\n", "\n", "The `+=` and `*=` operators also work with strings:\n", "\n", "```python\n", "# Concatenation with +=\n", "message = \"Hello\"\n", "message += \", world!\"\n", "print(message)\n", "\n", "# Repetition with *=\n", "separator = \"-\"\n", "separator *= 30\n", "print(separator)\n", "\n", "# Building text gradually\n", "report = \"Report:\\n\"\n", "report += \"- Item 1\\n\"\n", "report += \"- Item 2\\n\"\n", "report += \"- Item 3\\n\"\n", "print(report)\n", "```\n", "\n", "**Output:**\n", "```\n", "Hello, world!\n", "------------------------------\n", "Report:\n", "- Item 1\n", "- Item 2\n", "- Item 3\n", "\n", "```\n", "\n", "### Assignment Operators with Lists\n", "\n", "With lists, combined operators can append elements or concatenate lists:\n", "\n", "```python\n", "# Append elements with +=\n", "numbers = [1, 2, 3]\n", "numbers += [4, 5]\n", "print(numbers)\n", "\n", "# Repeat list with *=\n", "sequence = [0]\n", "sequence *= 5\n", "print(sequence)\n", "```\n", "\n", "**Output:**\n", "```\n", "[1, 2, 3, 4, 5]\n", "[0, 0, 0, 0, 0]\n", "```\n", "\n", "### Important Notes\n", "\n", "**Precedence:**\n", "\n", "Assignment operators have low precedence and are evaluated from **right to left**:\n", "\n", "```python\n", "x = y = 10\n", "print(f\"x = {x}, y = {y}\")\n", "```\n", "\n", "**Output:**\n", "```\n", "x = 10, y = 10\n", "```\n", "\n", "**Python does not have `++` or `--`:**\n", "\n", "```{admonition} Important - Increment Operators\n", ":class: warning\n", "Unlike C or Java, Python does not have unary increment/decrement operators (`++` and `--`). Use `+=` and `-=` instead!\n", "```\n", "\n", "```python\n", "# Wrong in Python\n", "# counter++ # Error!\n", "# counter-- # Error!\n", "\n", "# Correct in Python\n", "counter = 0\n", "counter += 1\n", "print(counter)\n", "counter -= 1\n", "print(counter)\n", "```\n", "\n", "**Output:**\n", "```\n", "1\n", "0\n", "```\n", "\n", "**In-place modification:**\n", "\n", "Combined operators modify the original variable:\n", "\n", "```python\n", "list_a = [1, 2, 3]\n", "list_b = list_a\n", "list_a += [4, 5]\n", "\n", "print(list_a)\n", "print(list_b)\n", "```\n", "\n", "**Output:**\n", "```\n", "[1, 2, 3, 4, 5]\n", "[1, 2, 3, 4, 5]\n", "```\n", "\n", "Both lists changed because the two names point to the **same object**: `list_b = list_a` copies nothing, it only gives a second name to the same list. When you want an independent copy, clone the list with `.copy()` or with the `list()` constructor:\n", "\n", "```python\n", "list_a = [1, 2, 3]\n", "list_b = list_a.copy() # creates a new object in memory, with the same values\n", "list_a += [4, 5]\n", "\n", "print(list_a)\n", "print(list_b)\n", "```\n", "\n", "**Output:**\n", "```\n", "[1, 2, 3, 4, 5]\n", "[1, 2, 3]\n", "```\n", "\n", "Only the middle line changed, and now `list_b` stays untouched.\n", "\n", "### When to Use Combined Assignment Operators\n", "\n", "Use combined operators when:\n", "- You are updating a variable based on its previous value\n", "- The code becomes clearer and more concise\n", "- You are doing repetitive operations (loops, counters, accumulators)\n", "\n", "```python\n", "# Good use: accumulator, adding to the previous value\n", "total = 0\n", "total += 10\n", "total += 25\n", "total += 7\n", "print(f\"Total: {total}\")\n", "\n", "# Good use: counter, subtracting on each attempt used\n", "attempts = 3\n", "attempts -= 1\n", "print(f\"Attempts left: {attempts}\")\n", "attempts -= 1\n", "print(f\"Attempts left: {attempts}\")\n", "```\n", "\n", "**Sample output (with the correct password):**\n", "```\n", "Enter the password (3 attempts): 1234\n", "Access granted!\n", "```\n", "\n", "Combined assignment operators are powerful tools that make code more elegant and expressive, especially in loops and repetitive operations!\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Bitwise Operations\n", "\n", "So far we have worked with operators that handle numbers in a \"natural\" way — adding, subtracting, comparing. But there is an even more fundamental level: **bitwise operations**. These operations work directly on the binary representation of numbers (0s and 1s).\n", "\n", "Although they may look advanced, bitwise operations matter in areas such as:\n", "- **Cryptography**: scrambling and protecting data\n", "- **Data compression**: reducing file size\n", "- **Hardware communication**: controlling electronic devices\n", "- **Performance optimization**: very fast operations in low-level systems\n", "- **Image manipulation**: pixel processing\n", "\n", "### Binary Representation\n", "\n", "Before getting into the operators, let's recall how numbers are represented in binary:\n", "\n", "```python\n", "# Convert decimal to binary\n", "number = 5\n", "binary = bin(number)\n", "print(f\"{number} in binary: {binary}\")\n", "\n", "# Convert binary to decimal\n", "binary_string = \"1101\"\n", "decimal = int(binary_string, 2)\n", "print(f\"{binary_string} in decimal: {decimal}\")\n", "```\n", "\n", "**Output:**\n", "```\n", "5 in binary: 0b101\n", "1101 in decimal: 13\n", "```\n", "\n", "> **Note:** The `0b` prefix indicates that the number is in binary format.\n", "\n", "> **Other operators:** Python also offers the bitwise inversion operator (`~`), but it is rarely used in basic programming and will not be covered in this chapter.\n", "\n", "### Bit Shift Operators\n", "\n", "Shift operators move the bits of a number to the left or right. These operations are equivalent to multiplying or dividing by powers of 2.\n", "\n", "#### Left Shift (`<<`)\n", "\n", "Moves the bits to the left, filling with zeros on the right. Each shifted position **multiplies the number by 2**.\n", "\n", "```python\n", "number = 5\n", "\n", "# Shift 1 position to the left\n", "result1 = number << 1\n", "print(f\"{number} << 1 = {result1}\")\n", "\n", "# Shift 2 positions to the left\n", "result2 = number << 2\n", "print(f\"{number} << 2 = {result2}\")\n", "\n", "# Shift 3 positions to the left\n", "result3 = number << 3\n", "print(f\"{number} << 3 = {result3}\")\n", "```\n", "\n", "**Output:**\n", "```\n", "5 << 1 = 10\n", "5 << 2 = 20\n", "5 << 3 = 40\n", "```\n", "\n", "**Formula:** `n << k` is equivalent to `n * (2 ** k)`\n", "\n", "#### Right Shift (`>>`)\n", "\n", "Moves the bits to the right, discarding the bits that \"fall off\". Each shifted position **divides the number by 2** (integer division).\n", "\n", "```python\n", "number = 20\n", "\n", "# Shift 1 position to the right\n", "result1 = number >> 1\n", "print(f\"{number} >> 1 = {result1}\")\n", "\n", "# Shift 2 positions to the right\n", "result2 = number >> 2\n", "print(f\"{number} >> 2 = {result2}\")\n", "\n", "# Shift 3 positions to the right\n", "result3 = number >> 3\n", "print(f\"{number} >> 3 = {result3}\")\n", "```\n", "\n", "**Output:**\n", "```\n", "20 >> 1 = 10\n", "20 >> 2 = 5\n", "20 >> 3 = 2\n", "```\n", "\n", "**Formula:** `n >> k` is equivalent to `n // (2 ** k)`\n", "\n", "### Visualizing Shifts\n", "\n", "Let's see visually what happens to the bits:\n", "\n", "The figure below shows both directions on the same number. They are the same digits, one place forward or back, and the value changes because each cell is worth twice the one to its right.\n", "\n", "```{image} deslocamento-light.png\n", ":alt: Two panels. In the first, the number 12 written as eight bit cells, 00001100, and below it the result of shifting one place to the left, 00011000, which is 24. Eight arrows link each bit to the neighbouring cell on the left and a new zero appears in the last cell on the right. In the second panel, the same 12 and the result of shifting one place to the right, 00000110, which is 6, with the arrows pointing right and the new zero entering through the first cell on the left\n", ":class: only-light\n", "```\n", "\n", "```{image} deslocamento-dark.png\n", ":alt: Two panels. In the first, the number 12 written as eight bit cells, 00001100, and below it the result of shifting one place to the left, 00011000, which is 24. Eight arrows link each bit to the neighbouring cell on the left and a new zero appears in the last cell on the right. In the second panel, the same 12 and the result of shifting one place to the right, 00000110, which is 6, with the arrows pointing right and the new zero entering through the first cell on the left\n", ":class: only-dark\n", "```\n", "\n", "\n", "```python\n", "number = 12\n", "\n", "print(f\"Original number: {number:4d} -> {bin(number)}\")\n", "print(f\"Shifted << 1: {number << 1:4d} -> {bin(number << 1)}\")\n", "print(f\"Shifted << 2: {number << 2:4d} -> {bin(number << 2)}\")\n", "print()\n", "print(f\"Original number: {number:4d} -> {bin(number)}\")\n", "print(f\"Shifted >> 1: {number >> 1:4d} -> {bin(number >> 1)}\")\n", "print(f\"Shifted >> 2: {number >> 2:4d} -> {bin(number >> 2)}\")\n", "```\n", "\n", "**Output:**\n", "```\n", "Original number: 12 -> 0b1100\n", "Shifted << 1: 24 -> 0b11000\n", "Shifted << 2: 48 -> 0b110000\n", "\n", "Original number: 12 -> 0b1100\n", "Shifted >> 1: 6 -> 0b110\n", "Shifted >> 2: 3 -> 0b11\n", "```\n", "\n", "\n", "The two animations below repeat the shift step by step, with the numbers the examples above used. The cell marked `in` holds the zero that is about to enter, and the cell marked `out` receives the digit that leaves the byte.\n", "\n", "```{image} deslocamento-esquerda-light.gif\n", ":alt: Animation in ten frames. The number 5 appears as eight bit cells and, on each shift to the left, every digit moves one cell in that direction, a zero enters through the cell marked in, on the right, and the digit that leaves goes to the cell marked out, on the left. The decimal value goes from 5 to 10, then 20 and 40\n", ":class: only-light\n", "```\n", "\n", "```{image} deslocamento-esquerda-dark.gif\n", ":alt: Animation in ten frames. The number 5 appears as eight bit cells and, on each shift to the left, every digit moves one cell in that direction, a zero enters through the cell marked in, on the right, and the digit that leaves goes to the cell marked out, on the left. The decimal value goes from 5 to 10, then 20 and 40\n", ":class: only-dark\n", "```\n", "\n", "```{image} deslocamento-direita-light.gif\n", ":alt: Animation in ten frames. The number 20 appears as eight bit cells and, on each shift to the right, every digit moves one cell in that direction, a zero enters through the cell marked in, on the left, and the digit that leaves goes to the cell marked out, on the right. The value goes from 20 to 10, then 5 and 2, and on the last shift the digit that leaves is a 1\n", ":class: only-light\n", "```\n", "\n", "```{image} deslocamento-direita-dark.gif\n", ":alt: Animation in ten frames. The number 20 appears as eight bit cells and, on each shift to the right, every digit moves one cell in that direction, a zero enters through the cell marked in, on the left, and the digit that leaves goes to the cell marked out, on the right. The value goes from 20 to 10, then 5 and 2, and on the last shift the digit that leaves is a 1\n", ":class: only-dark\n", "```\n", "\n", "Look at the last frame of the second animation. The digit that leaves is a `1`, and it does not come back: `2 << 3` gives 16, not 20. That is what integer division means here, and it is the difference between `>>` and ordinary division.\n", "\n", "### Practical Examples\n", "\n", "**Example 1: Fast multiplication and division by powers of 2**\n", "\n", "```python\n", "# Multiply by 2, 4, 8...\n", "value = 7\n", "print(f\"{value} * 2 = {value << 1}\")\n", "print(f\"{value} * 4 = {value << 2}\")\n", "print(f\"{value} * 8 = {value << 3}\")\n", "\n", "print()\n", "\n", "# Divide by 2, 4, 8...\n", "value = 100\n", "print(f\"{value} / 2 = {value >> 1}\")\n", "print(f\"{value} / 4 = {value >> 2}\")\n", "print(f\"{value} / 8 = {value >> 3}\")\n", "```\n", "\n", "**Output:**\n", "```\n", "7 * 2 = 14\n", "7 * 4 = 28\n", "7 * 8 = 56\n", "\n", "100 / 2 = 50\n", "100 / 4 = 25\n", "100 / 8 = 12\n", "```\n", "\n", "**Example 2: Check whether a number is a power of 2**\n", "\n", "```python\n", "# A number is a power of 2 if, in binary, it has a single bit set to 1.\n", "# The trick: n & (n - 1) clears the rightmost bit 1.\n", "number = 16\n", "print(f\"{number} in binary: {bin(number)[2:]}\")\n", "print(f\"{number - 1} in binary: {bin(number - 1)[2:]}\")\n", "print(f\"{number} & {number - 1} = {number & (number - 1)}\")\n", "print(f\"Is it a power of 2? {number > 0 and (number & (number - 1)) == 0}\")\n", "\n", "number = 15\n", "print(f\"\\n{number} & {number - 1} = {number & (number - 1)}\")\n", "print(f\"Is it a power of 2? {number > 0 and (number & (number - 1)) == 0}\")\n", "```\n", "\n", "**Output:**\n", "```\n", "16 in binary: 10000\n", "15 in binary: 1111\n", "16 & 15 = 0\n", "Is it a power of 2? True\n", "\n", "15 & 14 = 14\n", "Is it a power of 2? False\n", "```\n", "\n", "**Example 3: Convert between binary and decimal**\n", "\n", "```python\n", "print(\"Decimal -> Binary conversions:\")\n", "print(f\"Decimal: {5:3d} | Binary: {bin(5)[2:]:>8s}\")\n", "print(f\"Decimal: {28:3d} | Binary: {bin(28)[2:]:>8s}\")\n", "print(f\"Decimal: {100:3d} | Binary: {bin(100)[2:]:>8s}\")\n", "\n", "print(\"\\nBinary -> Decimal conversions:\")\n", "print(f\"Binary: {'1010':>8s} | Decimal: {int('1010', 2)}\")\n", "print(f\"Binary: {'11001':>8s} | Decimal: {int('11001', 2)}\")\n", "```\n", "\n", "**Output:**\n", "```\n", "Decimal -> Binary conversions:\n", "Decimal: 5 | Binary: 101\n", "Decimal: 28 | Binary: 11100\n", "Decimal: 100 | Binary: 1100100\n", "\n", "Binary -> Decimal conversions:\n", "Binary: 1010 | Decimal: 10\n", "Binary: 11001 | Decimal: 25\n", "```\n", "\n", "### Other Bitwise Operators\n", "\n", "While we did not detail them in this introductory chapter, Python offers other bit-manipulation operators:\n", "\n", "- **`&` (AND)**: returns 1 only if both bits are 1\n", "- **`|` (OR)**: returns 1 if at least one bit is 1\n", "- **`^` (XOR)**: returns 1 if the bits are different\n", "- **`~` (NOT)**: inverts every bit\n", "\n", "These operators are extremely useful in low-level programming and we will see more of them in advanced chapters.\n", "\n", "### When to Use Bitwise Operations?\n", "\n", "Most of the time you will use the regular arithmetic operators. Use bitwise operations when:\n", "- You need extreme performance in specific calculations\n", "- You work with low-level communication protocols\n", "- You manipulate flags and bit masks\n", "- You implement cryptography or compression algorithms\n", "- You work with image processing\n", "\n", "For beginners, **understanding the concept** matters more than mastering every detail. As you advance in programming, these operations will become more relevant!\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Operator Precedence (Summary)\n", "\n", "Throughout this chapter, we have seen many kinds of operators. When we combine several of them in a single expression, Python needs to decide **which operation to run first**. That order is determined by **operator precedence**.\n", "\n", "Understanding precedence is crucial to:\n", "- Write correct expressions\n", "- Read and understand other people's code\n", "- Avoid subtle bugs in complex calculations\n", "\n", "### Full Precedence Table\n", "\n", "The table below lists the operators in precedence order, from **highest** (evaluated first) to **lowest** (evaluated last):\n", "\n", "| Priority | Operator(s) | Type | Example | Description |\n", "|---|---|---|---|---|\n", "| **1st (Highest)** | `()` | Parentheses | `(2 + 3) * 4` | Group expressions and force evaluation |\n", "| **2nd** | `**` | Exponentiation | `2 ** 3` | Power |\n", "| **3rd** | `~`, `+`, `-` | Unary | `-x`, `~5`, `+3` | Negation, bit inversion, positive sign |\n", "| **4th** | `*`, `/`, `//`, `%` | Multiplicative | `4 * 2`, `10 / 3`, `10 % 3` | Multiplication, division, integer division, modulo |\n", "| **5th** | `+`, `-` | Additive | `5 + 3`, `10 - 2` | Addition and subtraction |\n", "| **6th** | `<<`, `>>` | Bit shift | `8 << 1`, `16 >> 2` | Left/right shift |\n", "| **7th** | `&` | Bitwise AND | `5 & 3` | Bitwise AND |\n", "| **8th** | `^` | Bitwise XOR | `5 ^ 3` | Bitwise exclusive OR |\n", "| **9th** | `\\|` | Bitwise OR | `5 \\| 3` | Bitwise OR |\n", "| **10th** | `==`, `!=`, `<`, `<=`, `>`, `>=` | Relational | `x > 5`, `a == b` | Comparisons |\n", "| **11th** | `in`, `not in` | Membership | `'a' in 'python'` | Membership checks |\n", "| **12th** | `not` | Logical NOT | `not True` | Logical inversion |\n", "| **13th** | `and` | Logical AND | `True and False` | Logical AND |\n", "| **14th** | `or` | Logical OR | `True or False` | Logical OR |\n", "| **15th (Lowest)** | `=`, `+=`, `-=`, `*=`, etc. | Assignment | `x = 5`, `y += 3` | Value assignment |\n", "\n", "### Important Rules\n", "\n", "**Parentheses are your friends**\n", "\n", "```{admonition} Rule of Thumb - Operator Precedence\n", ":class: tip\n", "When in doubt about evaluation order, use parentheses! They make code more readable and ensure the desired order.\n", "```\n", "\n", "```python\n", "# Without parentheses - can be confusing\n", "result = 10 + 5 * 2 - 3\n", "print(result)\n", "\n", "# With parentheses - clear intent\n", "result = 10 + (5 * 2) - 3\n", "print(result)\n", "\n", "# Changing the order\n", "result = (10 + 5) * (2 - 3)\n", "print(result)\n", "```\n", "\n", "**Output:**\n", "```\n", "17\n", "17\n", "-15\n", "```\n", "\n", "**Same precedence: left to right**\n", "\n", "When operators share the same precedence, they are evaluated **left to right**:\n", "\n", "```python\n", "result = 10 - 5 - 2\n", "print(result)\n", "\n", "result = 100 / 10 / 2\n", "print(result)\n", "```\n", "\n", "**Output:**\n", "```\n", "3\n", "5.0\n", "```\n", "\n", "**Exception:** Exponentiation (`**`) is evaluated **right to left**:\n", "\n", "```python\n", "result = 2 ** 3 ** 2\n", "print(result)\n", "```\n", "\n", "**Output:**\n", "```\n", "512\n", "```\n", "\n", "**Assignment has the lowest precedence**\n", "\n", "Assignment operators are always evaluated last:\n", "\n", "```python\n", "x = 5 + 3 * 2\n", "print(x)\n", "```\n", "\n", "**Output:**\n", "```\n", "11\n", "```\n", "\n", "### Step-by-Step Practical Examples\n", "\n", "**Example 1: Expression with multiple operators**\n", "\n", "```python\n", "result = 2 + 3 * 4 ** 2 - 10 / 2\n", "print(result)\n", "```\n", "\n", "**Evaluation order:**\n", "1. `4 ** 2` = 16 (exponentiation - highest)\n", "2. `3 * 16` = 48 (multiplication)\n", "3. `10 / 2` = 5.0 (division)\n", "4. `2 + 48` = 50 (addition - left to right)\n", "5. `50 - 5.0` = 45.0 (subtraction)\n", "\n", "**Output:**\n", "```\n", "45.0\n", "```\n", "\n", "**Example 2: Combining logical and relational operators**\n", "\n", "```python\n", "age = 25\n", "has_license = True\n", "result = age >= 18 and has_license or not has_license\n", "print(result)\n", "```\n", "\n", "**Evaluation order:**\n", "1. `age >= 18` = True (relational)\n", "2. `not has_license` = False (logical NOT)\n", "3. `True and True` = True (and - left to right)\n", "4. `True or False` = True (or)\n", "\n", "**Output:**\n", "```\n", "True\n", "```\n", "\n", "**Example 3: Bitwise and arithmetic operations**\n", "\n", "```python\n", "result = 5 + 3 << 2\n", "print(result)\n", "```\n", "\n", "**Evaluation order:**\n", "1. `5 + 3` = 8 (addition has higher precedence than shift)\n", "2. `8 << 2` = 32 (left shift)\n", "\n", "**Output:**\n", "```\n", "32\n", "```\n", "\n", "**But if we want to shift 3 first:**\n", "\n", "```python\n", "result = 5 + (3 << 2)\n", "print(result)\n", "```\n", "\n", "**Output:**\n", "```\n", "17\n", "```\n", "\n", "### Complete Example: Complex Expression\n", "\n", "Let's evaluate an expression that combines many kinds of operators:\n", "\n", "```python\n", "a = 10\n", "b = 5\n", "c = 2\n", "\n", "result = a + b * c ** 2 >= 30 and not b < c or a // b == 2\n", "print(result)\n", "```\n", "\n", "**Step by step:**\n", "1. `c ** 2` = 4 (exponentiation - highest)\n", "2. `b * 4` = 20 and `a // b` = 2 (multiplication and integer division)\n", "3. `a + 20` = 30 (addition)\n", "4. `30 >= 30` = True, `b < c` = False, `2 == 2` = True (relational)\n", "5. `not False` = True (logical NOT)\n", "6. `True and True` = True (and)\n", "7. `True or True` = True (or)\n", "\n", "**Output:**\n", "```\n", "True\n", "```\n", "\n", "### Tips for Writing Clear Code\n", "\n", "**Use parentheses generously**\n", "\n", "```python\n", "# Less clear\n", "x = 10\n", "y = 5\n", "z = 0\n", "if x > 5 and y < 10 or z == 0:\n", " print(\"Condition is true\")\n", "\n", "# Clearer\n", "if (x > 5 and y < 10) or (z == 0):\n", " print(\"Condition is true\")\n", "```\n", "\n", "**Output:**\n", "```\n", "Condition is true\n", "Condition is true\n", "```\n", "\n", "**Use intermediate variables**\n", "\n", "```python\n", "# Less clear\n", "a = 10\n", "b = 5\n", "c = 3\n", "d = 20\n", "e = 100\n", "f = 50\n", "g = 60\n", "h = True\n", "\n", "if a + b * c > d and e / f < g or h:\n", " print(\"Result: True\")\n", "\n", "# Clearer\n", "weighted_sum = a + b * c\n", "ratio = e / f\n", "if (weighted_sum > d and ratio < g) or h:\n", " print(\"Result: True\")\n", "```\n", "\n", "**Output:**\n", "```\n", "Result: True\n", "Result: True\n", "```\n", "\n", "```{admonition} Rule of Thumb - Operator Precedence\n", ":class: tip\n", "Operator precedence is a powerful tool, but don't abuse it! **Clear code beats \"clever\" code**. When in doubt:\n", "- Use parentheses\n", "- Break complex expressions apart\n", "- Add explanatory comments\n", "\n", "With practice, you will internalize these precedences naturally and write code that is both efficient and readable!\n", "```\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "gb8mmUPo9iil" }, "source": [ "## Exercises\n", "\n", "Before starting the exercises, it's important to note that for tests with multiple inputs on the same line, it's useful to use the `.split()` method. This method divides the string received by `input()` into substrings, using whitespace as delimiters. It returns a list containing the resulting substrings.\n", "\n", "For example, for an input: 1 1 6 6 4 4\n", "```python\n", "input_data = input().split()\n", "print(input_data)\n", "```\n", "When executing the above code with the input `1 1 6 6 4 4`, the output will be:\n", "```text\n", "['1', '1', '6', '6', '4', '4']\n", "```\n", "\n", "---\n", "\n", "1. Given the mathematical expression: $a = 4 * (2 + 3) - 7$. Create a variable called `a` and assign to it the result of this expression. Then, create a variable called `b` and assign to it the value of `a` multiplied by 2. Finally, print the values of `a` and `b`.\n", "\n", "```text\n", "# Test 1\n", "Input: No input\n", "Output:\n", "The value of 'a' is: 13\n", "The value of 'b' is: 26\n", "``` \n", "\n", "2. Write a program that asks the user for a positive integer between 100 and 1000. Then, the program should calculate the remainder of dividing this number by 5, store the result in a variable called remainder, and print this value.\n", "\n", "Make sure the program handles invalid inputs appropriately. If the user enters a negative number or a number outside the specified range, display the following error message: \"Please enter a positive integer between 100 and 1000.\"\n", "\n", "```text\n", "# Test 1\n", "Input: 172\n", "Output: The remainder of dividing 172 by 5 is 2.\n", "\n", "# Test 2\n", "Input: -10\n", "Output: Please enter a positive integer between 100 and 1000.\n", "\n", "# Test 3\n", "Input: 2000\n", "Output: Please enter a positive integer between 100 and 1000.\n", "\n", "# Test 4\n", "Input: 500\n", "Output: The remainder of dividing 500 by 5 is 0.\n", "```\n", "\n", "3. Write a program that converts a temperature from Celsius to Fahrenheit. Use the formula: $F = \\frac{9}{5} * C + 32$.\n", "\n", "- Ask the user to enter the temperature in Celsius.\n", "- Then, convert the entered temperature to Fahrenheit using the provided formula.\n", "- Finally, display the conversion result to the user, formatted with 2 decimal places.\n", "\n", "```text\n", "# Test 1\n", "Input: 20.5\n", "Output: The temperature in Fahrenheit is: 68.90\n", "\n", "# Test 2\n", "Input: 0.75\n", "Output: The temperature in Fahrenheit is: 33.35\n", "```\n", "\n", "4. Write a program that receives an integer between 10 and 20 as input. The program should convert this number to its binary representation, removing the `'0b'` prefix from the conversion. Then, each bit of this binary representation will be saved in a list, where each position of the list will contain one of the bits. Finally, the program should print the result.\n", "\n", "```text\n", "# Test 1\n", "Input: 10\n", "Output: ['1', '0', '1', '0']\n", "\n", "# Test 2\n", "Input: 16\n", "Output: ['1', '0', '0', '0', '0']\n", "\n", "# Test 3\n", "Input: 34\n", "Output: The entered number is not within the allowed range.\n", "```\n", "\n", "5. Using tuples, you should receive the coordinates of a rectangle in the Cartesian plane, where `(x_min, y_min)` represents the lower left corner and `(x_max, y_max)` represents the upper right corner. Additionally, you have a point represented by a pair of coordinates `(x, y)`.\n", "\n", "Your task is to write a program that determines if the point is inside, touching the edge, or outside the rectangle. The program should print a message to standard output indicating the verification result.\n", "\n", "See the didactic ASCII drawing example for Test 1:\n", "- The `+` represents the rectangle's corners.\n", "- The `.` represents the point.\n", "- The rectangle's coordinates are `(x_min, y_min) = (1,1)` and `(x_max, y_max) = (6,6)`.\n", "- The point's coordinates are `(x, y) = (4,4)`.\n", "\n", "```markdown\n", "7 | \n", "6 | +--------------+ (6,6)\n", "5 | | |\n", "4 | | .(4,4) |\n", "3 | | |\n", "2 | | |\n", "1 | +--------------+\n", "0 | (1,1) \n", " -+--+--+--+--+--+--+--+\n", " 0 1 2 3 4 5 6 7\n", "\n", "```\n", "\n", "```text\n", "# Test 1\n", "Input: 1 1 6 6 4 4\n", "Output: The point is inside the rectangle.\n", "\n", "# Test 2\n", "Input: 1 1 6 6 6 6\n", "Output: The point is touching the edge of the rectangle.\n", "\n", "# Test 3\n", "Input: 1 1 6 6 0 1\n", "Output: The point is outside the rectangle.\n", "\n", "# Test 4\n", "Input: 1 1 6 6 1 7\n", "Output: The point is outside the rectangle.\n", "\n", "# Test 5\n", "Input: 1 1 6 6 6 1\n", "Output: The point is touching the edge of the rectangle.\n", "\n", "# Test 6\n", "Input: 1 1 6 6 4 6\n", "Output: The point is touching the edge of the rectangle.\n", "```\n", "\n", "6. Develop an authentication system that uses a dictionary called `users_passwords` to store the names and passwords of two users. The program should ask the user to enter their username and password. Then, the system should verify if the entered credentials match those stored in the dictionary. If the credentials are correct, the program should display a message \"Login successful! Welcome, user.\". Otherwise, it should inform the user \"Access denied. Invalid credentials.\".\n", "\n", "Note: Only three users will be stored.\n", "\n", "```text\n", "# Test 1\n", "Input: user1 pass123 user2 abc456 user3 123456 user1 pass123\n", "Output: >> Login successful! Welcome, user1.\n", "\n", "# Test 2\n", "Input: user1 pass143 user2 abc452 user3 654321 user2 123abc\n", "Output: >> Access denied. Invalid credentials.\n", "```\n", "7. You are a biologist working in a natural park and are in charge of monitoring three species of migratory birds. Each species has a set of preferred islands for nesting during migration season. The species' preferences are as follows:\n", "\n", "- **Species 1**: Prefers islands with IDs from 1 to 10.\n", "- **Species 2**: Prefers islands with IDs from 6 to 17.\n", "\n", "Some islands are shared between species, which can lead to resource competition. Your job is to identify which islands are shared to implement conservation measures. Therefore, given a user input corresponding to one of the island IDs, check if this specific island is a competition area or if it's exclusive to one of the species.\n", "\n", "```text\n", "# Test 1\n", "Input: 2\n", "Output: Island 2 is exclusive to Species 1. \n", "Therefore, it is not shared with other species.\n", "\n", "# Test 2\n", "Input: 6\n", "Output: Island 6 is shared between species: 1 2.\n", "\n", "# Test 3\n", "Input: 10\n", "Output: Island 10 is shared between species: 1 2.\n", "\n", "# Test 4\n", "Input: 17\n", "Output: \n", "Island 17 is exclusive to Species 2. \n", "Therefore, it is not shared with other species.\n", "```\n", "\n", "8. Helping Hacker Neo Unravel the Truth About Reality.\n", "\n", "**The Matrix Story:**\n", "Neo, a talented hacker, lives a double life. In the world he knows, he is an ordinary programmer. But what if there existed a hidden reality, a truth he never imagined?\n", "\n", "After being contacted by Morpheus, Neo faces a critical choice: take the red pill and unravel the truth, or take the blue pill and continue living his life as always.\n", "\n", "**Program Phases:**\n", "\n", "**Phase 1: The Choice** ● ●\n", "- Neo must choose between the red pill and the blue pill. The choice is made through user input:\n", " - If the user types \"Red\", Neo advances to phase 2.\n", " - If the user types \"Blue\", Neo continues living his normal life and the program ends.\n", "\n", "**Phase 2: Unraveling Reality**\n", "- Neo needs to question the reality he lives in. He must answer three questions:\n", " - Is the reality you know real? (Yes or No)\n", " - Is there a hidden reality? (Yes or No)\n", " - Do you want to unravel the truth? (Yes or No)\n", "\n", "**Phase 3: Exploring the Truth**\n", "- If Neo answers \"Yes\" to all questions in phase 2, he will have access to information about the truth, and the program ends with a success message.\n", "- If Neo answers \"No\" to any of the questions in phase 2, he continues living his normal life, and the program ends with a message that the choice is his.\n", "\n", "**Test Examples:**\n", "\n", "```text\n", "# Test 1\n", "Input: Red Yes No Yes\n", "Output: The choice is yours, Neo continues living his normal life.\n", "\n", "# Test 2\n", "Input: Blue\n", "Output: Neo continues living his normal life.\n", "\n", "# Test 3\n", "Input: Red No Yes Yes \n", "Output: The choice is yours, Neo continues living his normal life.\n", "\n", "# Test 4\n", "Input: Red Yes Yes Yes\n", "Output: Neo will have access to information about the truth.\n", "```\n", "\n", "9. You are a professional photographer. During a job, you come across a crystal clear lake surrounded by immense mountains. Your goal is to capture an epic aerial photo of the lake, using a drone. To ensure the best perspective, you need to determine the ideal flight height for the drone. For this, you'll need to know the horizontal distance between you and the lake shore, as well as the vertical height you want to reach with the drone.\n", "\n", "The hypotenuse, which represents the diagonal distance traveled by the drone, can be calculated using the Pythagorean Theorem:\n", "\n", "$ Hypotenuse = \\sqrt(AdjacentLeg^2 + OppositeLeg^2) $\n", "\n", "Your program will receive as input, in meters, the length of the adjacent leg and the opposite leg, and will calculate the corresponding hypotenuse.\n", "\n", "**Test Examples:**\n", "\n", "```text\n", "# Test 1\n", "Input: 50 30\n", "Output: 58.31 meters\n", "\n", "# Test 2\n", "Input: 40 20\n", "Output: 44.72 meters\n", "\n", "# Test 3\n", "Input: 70 50\n", "Output: 86.02 meters\n", "```\n", "\n", "10. A craftsman is working on two pieces: a metal cone and a wooden parallelepiped. To help him in his project, you need to develop a program that receives the dimension information in cm of these objects and calculates their volumes and masses.\n", "\n", "- Receive as input the following information for the cone: Height and Radius.\n", "- Then, receive the information for the parallelepiped: Height, Width, and Length.\n", "\n", "Considering the appropriate mathematical formulas to calculate the volume of each object:\n", "\n", "Cone Volume: $V_{\\text{cone}} = \\frac{1}{3} \\pi r^2 h$\n", "\n", "Parallelepiped Volume: $ V_{\\text{parallelepiped}} = l \\times w \\times h $\n", "\n", "Calculate the mass of each object, considering that the metal density is 8 g/cm³ and the wood density is 0.5 g/cm³. Which of the two objects, cone or parallelepiped, is heavier? Consider that they have the same weight if the mass difference is less than 5g.\n", "\n", "**Test Examples:**\n", "\n", "```text\n", "# Test 1\n", "Input: 10 5 19 8 6\n", "Output: The cone is heavier at 2094.4g.\n", "\n", "# Test 2\n", "Input: 4 2 10 8 8\n", "Output: The parallelepiped is heavier at 320.0g.\n", "\n", "# Test 3\n", "Input: 10 2.44 10 10 10\n", "Output: The parallelepiped and cone have the same weight.\n", "\n", "# Test 4\n", "Input: 20 4.886 20 20 20\n", "Output: The parallelepiped and cone have the same weight.\n", "```" ] } ], "metadata": { "colab": { "provenance": [], "toc_visible": true }, "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.20" } }, "nbformat": 4, "nbformat_minor": 4 }