{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "ULxWGdhVqcRt" }, "source": [ "# Chapter 1: Introduction to Python Programming\n", "\n", "```{image} abertura-light.png\n", ":alt: Four mazes of continuous strokes that fill the frame without ever crossing, the colour advancing along the path\n", ":class: abertura only-light\n", "```\n", "\n", "```{image} abertura-dark.png\n", ":alt: Four mazes of continuous strokes that fill the frame without ever crossing, the colour advancing along the path\n", ":class: abertura only-dark\n", "```" ] }, { "cell_type": "markdown", "metadata": { "id": "TUXPVopGqgeo" }, "source": [ "## What is Computer Programming?\n", "\n", "Programming is the art and science of creating sets of instructions that allow computers to perform specific tasks. This process uses logic and algorithms through a **programming language**, which serves as the means of communication between human reasoning and machine execution.\n", "\n", "This skill is the foundation of modern technology, being essential in areas such as engineering, science, healthcare, and business. More than just automating processes, knowing how to program stimulates creative problem-solving and drives innovation.\n", "\n", "In practice, the programmer converts abstract concepts into structured commands. Beyond the technical aspect, programming is a powerful tool for exploring new ideas and a way to structure thinking from different perspectives and levels of abstraction." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Within the context of Python, this is a high-level, interpreted, and multi-paradigm language. This means that Python stands out for its ease of learning and use, being applicable to a wide range of purposes. Its versatility is reinforced by its ability to support various programming paradigms, providing developers with a flexible and adaptable approach to solving problems in different domains {cite}`python_docs`.\n", "\n", "For a broader view of its history and impact, I recommend the documentary **[The Story of Python](https://youtu.be/GfH4QL4VqJ0?si=GBAio4_c_DvPcuGt)**, which shows how the language evolved and established its place in the world of technology.\n", "\n", "Python plays significant roles in various areas. Below is a brief summary of some of these possibilities:\n", "\n", "- **Engineering and Sciences:** Used in simulation, data analysis and visualization, as well as being widely employed in machine learning projects. Its clear and concise syntax, along with an extensive library of scientific modules, makes it a popular choice for these applications {cite}`mckinney_python_2017`.\n", "\n", "- **Business:** An essential tool for data analysis, process automation, and web application development. Python's flexibility and efficiency make it versatile for business solutions {cite}`sweigart_automate_2020`.\n", "\n", "- **Education:** Considered the most popular programming language for teaching in schools and universities, its simple and intuitive syntax facilitates learning, even for beginners {cite}`matthes_python_2019`.\n", "\n", "- **Entertainment:** Employed in game creation, mobile applications, and other entertainment software. Python's robustness and flexibility allow the development of high-quality applications in various areas {cite}`lutz_learning_2013`.\n", "\n", "- **Healthcare:** Widely used in medical data analysis, specialized software development, and medical research. Its analytical capability and adaptability make it a valuable tool for innovation and research in healthcare {cite}`psf_healthcare`.\n", "\n", "Beyond its presence in major sectors, Python's versatility allows solving everything from simple daily tasks to complex engineering challenges. Its main applications include:\n", "\n", "- **Data and Science:** Analysis, visualization, and advanced mathematical simulations.\n", "- **Artificial Intelligence:** Machine Learning and generative models.\n", "- **Web Development:** Creating websites, APIs, and back-end services.\n", "- **Automation and Networks:** Process scripts, infrastructure automation, and cybersecurity.\n", "- **Systems and Media:** Game development, Internet of Things (IoT), and media manipulation.\n", "\n", "Python's flexibility makes it an indispensable tool in various areas, offering a solid foundation for innovation in today's technological landscape. Mastering Python is not just an essential skill, but also a way to explore the constant innovations and challenges of this rapidly evolving technological world. According to the updated IEEE Spectrum ranking for 2025, Python continues to consolidate its position as the most influential and used programming language, driven by the omnipresence of generative artificial intelligence ([spectrum.ieee.org/top-programming-languages-2025](https://spectrum.ieee.org/top-programming-languages-2025))" ] }, { "cell_type": "markdown", "metadata": { "id": "rGKHTTkn1BMc" }, "source": [ "## What do you need to get started?\n", "\n", "To begin your Python learning journey, in addition to this documentation, it's essential to have the following requirements:\n", "\n", "1. **Computer with Internet Access:** \n", " Essential for downloading libraries, consulting official documentation, and using AI tools. The connection enriches the learning experience and facilitates access to modern language models.\n", "\n", "2. **Text Editor or AI-Powered IDE:** \n", " Choose a tool that fits your workflow:\n", " - **AI-Native:** [Cursor](https://www.cursor.com/) (integrated with Claude and GPT) and [Antigravity](https://antigravity.google/) (IDE focused on AI-assisted development).\n", " - **Extensions and Terminal:** [Visual Studio Code](https://code.visualstudio.com/) with Copilot, [NeoVim](https://neovim.io/), or command-line tools to interact directly with **Gemini**, **Claude**, and **Copilot CLI**.\n", " - **Python-Specific:** [PyCharm](https://www.jetbrains.com/pycharm/) or the classic [IDLE](https://docs.python.org/3/library/idle.html).\n", " - **Online (No installation):** [Google Colab](https://colab.research.google.com/), [Replit](https://replit.com), or [Jupyter Notebook](https://jupyter.org/).\n", "\n", "3. **Python Interpreter:** \n", " Download the latest version at [python.org](https://www.python.org/). Python is famous for being \"batteries included,\" bringing almost everything you need natively.\n", "\n", "Equipped with these resources, you'll be ready to explore and enhance your Python skills. Whether working locally on your computer or in online environments, you'll have the flexibility needed to dive into the world of programming, adapting to your learning style.\n", "\n", "**Tip:** Since Python is an **interpreted** language, code is executed directly without the need for an extra compilation step. This makes the development cycle much more agile and beginner-friendly." ] }, { "cell_type": "markdown", "metadata": { "id": "DzIku84CyrC0" }, "source": [ "## Writing your first Python program\n", "\n", "Let's create a simple program that adds two numbers and displays the result. Save the code below in a file called `sum.py`:\n", "\n", "```python\n", "a = 1\n", "b = 2\n", "sum = a + b\n", "print(sum)\n", "```\n", "\n", "### What happens in the code?\n", "\n", "- **Assignment:** `a = 1` and `b = 2` create **variables** (memory spaces) to store the numbers.\n", "- **Processing:** `sum = a + b` performs the calculation and stores the result in a new variable.\n", "- **Output:** The `print(sum)` function displays the final value (3) in the console.\n", "\n", "### How to execute:\n", "\n", "1. Open the terminal (or command prompt).\n", "2. Navigate to the folder where you saved the file.\n", "3. Type the command: `python sum.py` (on some systems use `python3`).\n", "\n", "**Tip:** If you're using **Jupyter Notebook**, **Google Colab**, or **Cursor**, just type the code in a cell and press `Shift + Enter` to see the result instantly." ] }, { "cell_type": "markdown", "metadata": { "id": "CyHHkXhuHch2" }, "source": [ "## How does a Python program work?\n", "\n", "The execution of Python code occurs in stages that ensure its portability and efficiency. The process follows the flow illustrated below:\n", "\n", "1. **Source Code (.py):** This is the text you write. When you execute it, the **Interpreter** comes into action.\n", "2. **Compilation to Bytecode:** The interpreter converts your code into an intermediate form called **Bytecode** (or object code). This makes execution faster than reading the plain text every time.\n", "3. **Python Virtual Machine (PVM):** This is where the program actually runs. The PVM processes the bytecode, integrates the necessary **libraries**, and interacts with the operating system to deliver the final result.\n", "\n", "```{image} fluxo-python-light.png\n", ":alt: Flowchart of the path of a Python program, from the .py source code to the running program, through the compiler, the bytecode and the virtual machine, which receives the modules and talks to the operating system\n", ":class: only-light\n", "```\n", "\n", "```{image} fluxo-python-dark.png\n", ":alt: Flowchart of the path of a Python program, from the .py source code to the running program, through the compiler, the bytecode and the virtual machine, which receives the modules and talks to the operating system\n", ":class: only-dark\n", "```\n", "**Figure: Python code execution flow.**\n", "\n", "**Technical note:** Modern versions of Python (such as CPython) may use **Just-In-Time (JIT)** compilers to further optimize performance during execution, transforming frequent bytecode sections directly into machine code {cite}`lutz_learning_2013`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Basic structure of a Python program\n", "\n", "A Python program follows simple logic: **Input**, **Processing**, and **Output**. Just like in a cooking recipe, the algorithm organizes a defined sequence of steps to perform a specific task.\n", "\n", "### Code Organization\n", "\n", "Although it's possible to write loose commands, best practice recommends organizing code into functions. The model below is the community standard:\n", "\n", "```python\n", "def main():\n", " # Your main code here\n", " print(\"Hello, Python!\")\n", "\n", "if __name__ == \"__main__\":\n", " main()\n", "```\n", "\n", "**The importance of `if __name__ == \"__main__\":`**\n", "This check ensures that the `main()` function is executed only when the file is run directly. If this script is imported by another program in the future, it won't execute the main code automatically.\n", "\n", "### Indentation and Style\n", "\n", "Unlike other languages, indentation in Python (the spaces at the beginning of the line) is not just aesthetic: **it's mandatory**. It defines the hierarchy and grouping of code blocks. Python's official style guide, **[PEP 8](https://peps.python.org/pep-0008/)**, recommends using **4 spaces** per level to maintain readability." ] }, { "cell_type": "markdown", "metadata": { "id": "vCssW6YEGJRH" }, "source": [ "(interacting-with-the-user)=\n", "## Interacting with the user\n", "\n", "Let's make the program dynamic using the `input()` function, which allows capturing data typed by the user.\n", "\n", "```python\n", "name = input(\"What is your name? \")\n", "age = input(\"What is your age? \")\n", "\n", "print(f\"Hello {name}, you are {age} years old.\")\n", "```\n", "\n", "**New concepts applied:**\n", "- **`input()`**: Pauses execution and waits for user input.\n", "- **f-strings**: The `f` prefix before the quotes (`f\"...\"`) allows inserting variables directly into the text between curly braces `{ }`, making the code much more intuitive and clean." ] }, { "cell_type": "markdown", "metadata": { "id": "vCssW6YEGJRH" }, "source": [ "### Commenting your code\n", "\n", "Comments are essential for you and other developers to understand the logic behind program decisions. In Python, there are two main ways to insert these annotations:\n", "\n", "**Single-Line Comments** \n", "Use the `#` symbol for brief explanations or to temporarily disable a line of code.\n", "```python\n", "name = input(\"What is your name? \") # Captures the user's name\n", "```\n", "\n", "**Multi-Line Comments (Docstrings)** \n", "For longer explanations or function documentation, use triple quotes (`'''` or `\"\"\"`).\n", "```python\n", "\"\"\"\n", "This block calculates eligibility based on age.\n", "It's good practice to document complex logic here.\n", "\"\"\"\n", "age = 20\n", "eligible = int(age) > 18\n", "print(eligible)\n", "```\n", "\n", "**Best Practices:**\n", "- **Be objective:** Explain the \"why\" of a decision, not just the \"what\" the code does (the code itself should already say that).\n", "- **Keep it updated:** An outdated comment is worse than no comment. Always review notes when changing the logic.\n", "- **Avoid the obvious:** There's no need to comment every simple line; save comments for parts that require greater cognitive effort." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## How to learn programming strategically\n", "\n", "Learning programming requires more than just memorizing syntax; it's about training your brain to process logic and retain information efficiently. Understanding how your mind works can radically transform your progress {cite}`oakley2021uncommon`.\n", "\n", "### The balance between memories\n", "\n", "**Working memory** acts as a temporary \"work desk,\" handling immediate problems. Since its capacity is limited, trying to learn everything at once creates overload. **Long-term memory**, on the other hand, is your definitive knowledge warehouse. The secret to deep learning is transferring logic from the desk to the warehouse through proven techniques:\n", "\n", "**Spaced Repetition** \n", "Instead of studying 10 hours in a single day, review content at increasing intervals (1 day, 3 days, 1 week). This signals to the brain that the information is important, consolidating it in long-term memory {cite}`cepeda_2006`.\n", "\n", "**Interleaving Topics** \n", "Avoid focusing on a single subject for too long. Alternate between practicing a new command, reading documentation, and solving a small bug. This alternation strengthens neural connections and makes your learning more flexible {cite}`rohrer_2012`.\n", "\n", "### Active Practice and the New AI Era\n", "\n", "Reading about code is passive; writing code is **active practice**. True learning happens when you face the error and seek the solution {cite}`ericsson_pool_2016`.\n", "\n", "**The role of AI in learning** \n", "Tools like **Gemini**, **Claude**, and **Copilot** are powerful assistants, but should be used strategically. Instead of asking AI to solve the entire problem, use it to:\n", "- Explain a confusing error message.\n", "- Suggest alternatives for a piece of code you've already written.\n", "- Generate practical challenges for you to solve.\n", "\n", "**Building your knowledge base** \n", "Use note-taking tools like [Obsidian](https://obsidian.md/) or [Notion](https://www.notion.com/) to create your own \"second brain.\" Recording what you've learned in your own words is one of the most effective ways to cement the content." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Practice Exercises\n", "\n", "Complete the exercises below to consolidate your learning. Remember: the secret is to try solving without copying and seek to understand each error that arises.\n", "\n", "### Exercise 1: Your first message\n", "Write a program that displays the message: `Hello world, I'm learning Python!`. This simple exercise ensures your environment is configured correctly.\n", "\n", "
\n", "\n", "### Exercise 2: Student Registration\n", "Create a program that captures a student's **name** and **ID number** and displays a formatted welcome message. \n", "\n", "*Hint: Use **[f-strings](#interacting-with-the-user)** to organize the output elegantly.*\n", "\n", "
\n", "\n", "### Exercise 3: Simple Order Calculation\n", "Develop a script that asks for the **product name**, **quantity**, and **unit price**. The program should calculate the total value and display an order summary.\n", "\n", "*Note: You'll need to convert the quantity to `int` and the price to `float` before performing the calculation.*\n", "\n", "
\n", "\n", "### Exercise 4: Your age in days\n", "Create a program that asks the user's age and tells them approximately how many days they've lived (consider a year as 365 days).\n", "\n", "
\n", "\n", "### Exercise 5: Logic and Flow\n", "A system must verify if a student passed. The rule is: if the average is greater than or equal to 7.0, they are **Passed**, otherwise they are **Failed**.\n", "\n", "Which of the alternatives below represents the correct logical flow for this program?\n", "\n", "{.alternativas}\n", "- **A)** `Start` ➔ `Average >= 7.0?` ➔ `Read Average` ➔ `If YES: \"Passed\"` ➔ `End`\n", "- **B)** `Start` ➔ `Read Average` ➔ `Average >= 7.0?` ➔ `If YES: \"Passed\"` or `If NO: \"Failed\"` ➔ `End`\n", "- **C)** `Start` ➔ `Show \"Passed\"` ➔ `Read Average` ➔ `Average >= 7.0?` ➔ `End`\n", "- **D)** `Start` ➔ `Average >= 7.0?` ➔ `Show \"Failed\"` ➔ `End`\n", "- **E)** `Read Average` ➔ `Start` ➔ `Average >= 7.0?` ➔ `If YES: \"Failed\"` ➔ `End`\n", "\n", "**Hint:** Remember the fundamental order: **Input** ➔ **Processing** ➔ **Output**.\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## References\n", "\n", "```{bibliography}\n", ":filter: docname in docnames\n", "```\n" ] } ], "metadata": { "colab": { "provenance": [] }, "kernelspec": { "display_name": "Python 3 (jupyter)", "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 }