#020 - Python Essentials | 03 - Getting Started

This article provides all the essentials you need to create your first Python calculation.

Welcome to the latest edition of the Flocode newsletter. Today, for complete beginners, we delve into the fundamentals of getting up and running with Python. We'll build a simple calculator as a warm-up for future deep dives.

We are starting at the start, installation and basic environments.

All of my Python work is within the Windows environment. I assume this is the case for every practicing engineer (at least in the civil and structural sectors). Please vote below so we can find out!

On Learning Python

Throughout this article, I provide code examples and introduce some broader Python concepts. Don't get bogged down in the details just yet; these concepts will become clear as we progress through the Python landscape in future articles.

Just hang in there. Subliminal unconscious learning is happening here, and it will consolidate as we march forward. Don't sweat the gaps or the details; we’ll get there. I recommend trying to follow along with the examples herein.

Why Python for Engineers?

Python is accessible to beginners yet powerful enough for complex tasks, making it a preferred choice for professionals across various engineering disciplines. From automating mundane tasks to processing large data sets and even aiding in complex computational design, Python's capabilities are vast, varied and growing.

Python offers a unique combination of readability, efficiency, and a vast library ecosystem. These attributes can streamline many traditional engineering processes, effectively saving time and enhancing productivity. Whether working on data analysis or automation or integrating with CAD and FEA software, Python provides a platform to extend your technical capabilities. The possibilities are as limitless as your creativity.

Check out the Flocode post archive for specific engineering applications and use cases that may interest you further.

Setting Up Python

This process is tailored specifically for Windows users, although we haven't forgotten our Mac and Linux colleagues (i.e. blackguards) – links for these platforms are provided below.

Setting up Python on your Windows machine is a pretty straightforward process. Here's a step-by-step guide to get you started:

  1. Downloading Python: Visit the official Python website (python.org) and download the latest version of Python for Windows. Choose the installer that matches your system's architecture (32-bit or 64-bit).

  2. Running the Installer: Launch the downloaded installer.

  3. Check the box that says "Add Python to PATH" before you click "Install Now.” This step is CRUCIAL as it makes Python accessible from the Command Prompt.

  4. Verifying the Installation: To ensure Python is installed correctly, open your Command Prompt (press the Windows key + R) and type python --version. If the installation was successful, you should see the Python version number displayed.

  5. Updating pip: Pip is Python's package manager (think of it like an app store), a critical tool. In the Command Prompt, type:

    python -m pip install --upgrade pip/

Now that Python is installed, you're all set. Next, we'll introduce Python environments and dive into creating simple Python programs.

Exploring Python Environments for Beginners

As a new Python user, it's essential to understand the various environments where you can write and execute Python code. Each environment has unique features and use cases, making them suitable for different stages of your learning and development process.

As we delve into the diverse environments for running and accessing Python, it's important to set the context for our discussion. In my professional practice, nearly all of my coding is conducted within Visual Studio Code, a dynamic and powerful Interactive Development Environment (IDE). This tool is designed for efficiency, offering advanced features that cater to a streamlined coding process. The upcoming explanation of the broad spectrum of Python environments, from simple interfaces like the IDLE to more complex ones like command lines and shells, aims to give you a comprehensive understanding of the options available and their specific utilities.

In practical terms, a deep dive into these various environments may not be necessary for your daily coding tasks. They are stepping stones, providing foundational knowledge and context. As you progress in your Python journey, especially in an engineering context, an IDE like Visual Studio Code will likely become your primary workspace due to its integration capabilities, user-friendly interface, and efficiency in the development process.

Understanding the full range of Python environments is part of developing a well-rounded skill set. This knowledge ensures you are equipped with the necessary context and appreciation for the tools at your disposal, helping you make informed choices about your coding practices. You will access these tools from your preferred command center for different reasons. Now, let's explore these environments in detail.

  1. Command Line (CMD): This is the primary interface for interacting with your operating system using text-based commands. After installing Python and adding it to your PATH, you can run Python directly from the CMD by typing python. This environment is ideal for executing single-line Python commands and scripts.

  2. PowerShell: Similar to CMD, PowerShell is another command-line interface provided by Windows, but with more advanced features and support for Python. Beginners might not notice much difference between CMD and PowerShell for basic Python tasks, but PowerShell offers more powerful scripting capabilities.

  3. Python Interpreter: This is an interactive way to work with Python. You can enter Python commands one at a time and see the results immediately. Access it by typing python in CMD or PowerShell. It's great for quick tests and learning basic syntax, as it provides immediate feedback.

  4. Python IDLE: IDLE stands for Integrated Development and Learning Environment. It's a simple, user-friendly environment included with Python installations. IDLE has a text editor for writing scripts and an interpreter for running them. It’s particularly useful for beginners due to its simplicity and the built-in Python documentation.

  5. Shell: In Python, a shell refers to a user interface to access an operating system's services. In Python IDLE, the shell is where your code gets executed. It's interactive, meaning you can write and test small pieces of code in real time. A shell can exist in any of the environments mentioned above.

Each of these environments serves as a gateway to Python programming, offering different levels of complexity and control. As a beginner, starting with the Python Interpreter or IDLE is not a bad plan, as they provide a more forgiving platform for experimenting and learning. Still, I recommend diving into a custom IDE and getting started sooner rather than later. You’ll end up there anyway, so why wait?

Custom IDEs: Enhancing Your Python Experience

Beyond the basic environments, there's a world of Custom Integrated Development Environments (IDEs) that significantly enhance your Python programming experience. These IDEs are where the vast majority of your Python work will likely occur, offering advanced features and tools that streamline the coding process.

  1. Visual Studio Code (VS Code) is my personal weapon of choice. It's a powerful, free, open-source editor that supports Python through extensions. VS Code is known for its efficiency and customization options.

  2. PyCharm is a widely used IDE specifically for Python. It offers a rich set of features, including intelligent code navigation and fast error checking.

  3. Jupyter Notebook: Popular in data science, it allows you to create and share documents containing live code, equations, visualizations, and narrative text. I use Jupyter Notebooks for all of my engineering calculations. The Jupyter extension works well with VS Code and its file management system, so I don't use the dedicated Jupyter desktop app.

  4. Atom: A customizable text editor known for its ease of use and GitHub integration.

  5. Spyder: Often preferred for scientific development, it integrates essential tools like iPython, NumPy, and Matplotlib.

Integration with VS Code

In my experience, while the simpler methods (like IDLE, CMD, and PowerShell) are foundational, they integrate seamlessly into VS Code, combining the simplicity of basic environments with advanced features. For instance, running scripts in VS Code's terminal allows you to use CMD or PowerShell directly within the IDE. This integration facilitates a smoother workflow, especially as you transition from basic tasks to more complex projects.

Benefits of Using an IDE like VS Code

  • Syntax Highlighting: One of the most immediate benefits is syntax highlighting. It makes code more readable by colour-coding elements like variables, functions, and operators. This not only makes it easier to spot errors but also helps in understanding the structure of your code at a glance.

  • Extensions and Plugins: VS Code offers a plethora of extensions, enhancing its functionality. Extensions like Python, Jupyter, Prettier, ChatGPT or Github Copilot can dramatically improve your coding efficiency, offering features like code completion, formatting, and version control.

  • Customization and Flexibility: VS Code allows personalization to suit your coding style. You can customize everything from the theme to the behaviour of the editor.

  • Integrated Terminal and Git Support: The integrated terminal in VS Code is a powerful feature, allowing you to run Python scripts and commands within the IDE. Additionally, its Git support streamlines version control, which is crucial for collaborative projects.

Understanding Python File Types

A Python script is a file containing Python code that is designed to perform a specific task or a set of tasks. Typically, these scripts are saved with a .py file extension. This extension distinguishes them as Python executable files, which can be run by the Python interpreter.

Script vs File: While all Python scripts are files, not all files are Python scripts. A Python script is specifically a text file containing Python code, saved with the .py extension.

Execution: Python scripts are not automatically executed (or ‘ran’) upon opening. They must be run through a Python interpreter, which can be done in several ways, as discussed above.

A Python script is a fundamental element for executing Python code, and it serves as a versatile tool in a wide range of applications, from simple task automation to complex computational processes in engineering and data science.

Your First Python Calculations

Using the Python IDLE

To start writing Python code, open Python IDLE, which is installed along with Python. It provides a simple interface to write and run Python scripts, making it the easiest way to start.

In Python IDLE, you can execute Python code in two primary ways: running individual lines of code in the interactive shell or running a full script.

When you first open Python IDLE, you're presented with an interactive shell. Here, each line of code is executed as soon as you press Enter. This method is beneficial for quick tests, learning syntax, or doing simple calculations.

If you have a script with multiple lines of code, like several print statements, you can write this code in the text editor window of IDLE (accessible via File > New File). After writing your script, you can run the entire script at once. This is done by saving the file with a .py extension and pressing F5 or selecting Run > Run Module from the menu. IDLE will execute the entire script in one go, showing the output in the interactive shell window.

  1. Opening your Python IDLE: Search for 'IDLE' in your Windows search bar and open it.

  2. Creating a New File: In IDLE, go to File > New File. This opens a text editor window where you can write your Python code.

Writing Basic Arithmetic Operations

Let’s create a simple script to perform basic arithmetic operations:

# Addition
sum = 5 + 3
print("The sum is", sum)

# Subtraction
difference = 10 - 2
print("The difference is", difference)
  1. Saving Your File: Save the script by going to File > Save or pressing Ctrl + S. Name it simple_calculator.py.

  2. Running the Script: Run your script in IDLE by pressing F5. The results of the arithmetic operations will be displayed in the IDLE shell.

Hands-On Exercise: Building a Basic Calculator

Now, let’s extend this concept to build your basic calculator.

  1. Set Up Your Script: Open a new file in IDLE and save it as basic_calculator.py.

  2. Creating Calculator Functions: Define the inputs for two numbers from the user:

    num1 = float(input("Enter first number: "))
    num2 = float(input("Enter second number: "))
  3. Perform and display addition:

    sum = num1 + num2print("The sum is ", sum)
  1. Similarly, you can add subtraction, multiplication, and division operations.

  1. Experiment with Operations: Encourage trying different arithmetic operations by modifying the script. Experiment with multiplication (`*`), division (/), and more complex operations.

  2. Run Your Calculator: Save and run your script (F5) in IDLE to see your basic calculator in action.

This hands-on exercise introduces you to basic programming concepts in Python, such as variables, input/output, and arithmetic operations. Feel free to experiment with different operations and see immediate results – a great way to enhance your understanding of Python basics.

Conclusion and Next Steps

The examples presented may seem almost rudimentary, especially to accomplished engineers accustomed to grappling with brain-melting, finite element analyses and multi-dimensional complexities. However, it's crucial to remember the importance of building a strong foundation. Just as a complex structure relies on a solid footing, mastering the fundamentals of Python is key to effectively applying it in sophisticated engineering contexts.

To those of you eagerly anticipating more intricate and challenging material: rest assured, we will delve deep into the weeds. Your day will come. Our journey through Python will evolve, growing in complexity and rigour. I ask for your patience as we lay the groundwork. These initial steps, though they may appear simple, are essential building blocks. They set the stage for us to tackle more advanced programming concepts and applications in engineering.

“I learned very early the difference between knowing the name of something and knowing something.”

Richard Feynman.

You've just scratched the surface of what's possible with Python in engineering. We've covered the basics of setting up Python, explored various environments, and even built a basic calculator.

As you continue this journey, remember that Python is a vast language with immense potential in engineering. Structured learning and practice are vital to truly harness its power, and that's where Flocode's courses come in.

I am working extremely hard on the Flocode course curriculum. Things are progressing; I will keep everyone updated. Your feedback, enthusiasm, and engagement have already been instrumental in helping to shape Flocode into a platform that genuinely resonates with the engineering community.

Stay tuned for more content, and in the meantime, please experiment with Python, explore its possibilities, and share your experiences.

Keep innovating, and I’ll see you in the next one!

James 🌊

Reply

or to participate.